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(StrongPHIElimination, "strong-phi-node-elimination",
154 "Eliminate PHI nodes for register allocation, intelligently", false, false);
156 char &llvm::StrongPHIEliminationID = StrongPHIElimination::ID;
158 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
159 /// of the given MachineFunction. These numbers are then used in other parts
160 /// of the PHI elimination process.
161 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
162 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
163 SmallPtrSet<MachineDomTreeNode*, 8> visited;
167 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
169 MachineDomTreeNode* node = DT.getRootNode();
171 std::vector<MachineDomTreeNode*> worklist;
172 worklist.push_back(node);
174 while (!worklist.empty()) {
175 MachineDomTreeNode* currNode = worklist.back();
177 if (!frontier.count(currNode)) {
178 frontier.insert(currNode);
180 preorder.insert(std::make_pair(currNode->getBlock(), time));
183 bool inserted = false;
184 for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
186 if (!frontier.count(*I) && !visited.count(*I)) {
187 worklist.push_back(*I);
193 frontier.erase(currNode);
194 visited.insert(currNode);
195 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
204 /// PreorderSorter - a helper class that is used to sort registers
205 /// according to the preorder number of their defining blocks
206 class PreorderSorter {
208 DenseMap<MachineBasicBlock*, unsigned>& preorder;
209 MachineRegisterInfo& MRI;
212 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
213 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
215 bool operator()(unsigned A, unsigned B) {
219 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
220 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
222 if (preorder[ABlock] < preorder[BBlock])
224 else if (preorder[ABlock] > preorder[BBlock])
233 /// computeDomForest - compute the subforest of the DomTree corresponding
234 /// to the defining blocks of the registers in question
235 std::vector<StrongPHIElimination::DomForestNode*>
236 StrongPHIElimination::computeDomForest(
237 std::map<unsigned, MachineBasicBlock*>& regs,
238 MachineRegisterInfo& MRI) {
239 // Begin by creating a virtual root node, since the actual results
240 // may well be a forest. Assume this node has maximum DFS-out number.
241 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
242 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
244 // Populate a worklist with the registers
245 std::vector<unsigned> worklist;
246 worklist.reserve(regs.size());
247 for (std::map<unsigned, MachineBasicBlock*>::iterator I = regs.begin(),
248 E = regs.end(); I != E; ++I)
249 worklist.push_back(I->first);
251 // Sort the registers by the DFS-in number of their defining block
252 PreorderSorter PS(preorder, MRI);
253 std::sort(worklist.begin(), worklist.end(), PS);
255 // Create a "current parent" stack, and put the virtual root on top of it
256 DomForestNode* CurrentParent = VirtualRoot;
257 std::vector<DomForestNode*> stack;
258 stack.push_back(VirtualRoot);
260 // Iterate over all the registers in the previously computed order
261 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
263 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
264 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
265 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
268 // If the DFS-in number of the register is greater than the DFS-out number
269 // of the current parent, repeatedly pop the parent stack until it isn't.
270 while (pre > maxpreorder[parentBlock]) {
272 CurrentParent = stack.back();
274 parentBlock = CurrentParent->getReg() ?
275 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
279 // Now that we've found the appropriate parent, create a DomForestNode for
280 // this register and attach it to the forest
281 DomForestNode* child = new DomForestNode(*I, CurrentParent);
283 // Push this new node on the "current parent" stack
284 stack.push_back(child);
285 CurrentParent = child;
288 // Return a vector containing the children of the virtual root node
289 std::vector<DomForestNode*> ret;
290 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
294 /// isLiveIn - helper method that determines, from a regno, if a register
295 /// is live into a block
296 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
298 LiveInterval& I = LI.getOrCreateInterval(r);
299 SlotIndex idx = LI.getMBBStartIdx(MBB);
300 return I.liveAt(idx);
303 /// isLiveOut - help method that determines, from a regno, if a register is
304 /// live out of a block.
305 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
307 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
308 E = MBB->succ_end(); PI != E; ++PI)
309 if (isLiveIn(r, *PI, LI))
315 /// interferes - checks for local interferences by scanning a block. The only
316 /// trick parameter is 'mode' which tells it the relationship of the two
317 /// registers. 0 - defined in the same block, 1 - first properly dominates
318 /// second, 2 - second properly dominates first
319 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
320 LiveIntervals& LV, unsigned mode) {
321 MachineInstr* def = 0;
322 MachineInstr* kill = 0;
324 // The code is still in SSA form at this point, so there is only one
325 // definition per VReg. Thus we can safely use MRI->getVRegDef().
326 const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
328 bool interference = false;
330 // Wallk the block, checking for interferences
331 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
333 MachineInstr* curr = MBI;
335 // Same defining block...
337 if (curr == MRI->getVRegDef(a)) {
338 // If we find our first definition, save it
341 // If there's already an unkilled definition, then
342 // this is an interference
346 // If there's a definition followed by a KillInst, then
347 // they can't interfere
349 interference = false;
352 // Symmetric with the above
353 } else if (curr == MRI->getVRegDef(b)) {
360 interference = false;
363 // Store KillInsts if they match up with the definition
364 } else if (curr->killsRegister(a)) {
365 if (def == MRI->getVRegDef(a)) {
367 } else if (curr->killsRegister(b)) {
368 if (def == MRI->getVRegDef(b)) {
373 // First properly dominates second...
374 } else if (mode == 1) {
375 if (curr == MRI->getVRegDef(b)) {
376 // Definition of second without kill of first is an interference
380 // Definition after a kill is a non-interference
382 interference = false;
385 // Save KillInsts of First
386 } else if (curr->killsRegister(a)) {
389 // Symmetric with the above
390 } else if (mode == 2) {
391 if (curr == MRI->getVRegDef(a)) {
396 interference = false;
399 } else if (curr->killsRegister(b)) {
408 /// processBlock - Determine how to break up PHIs in the current block. Each
409 /// PHI is broken up by some combination of renaming its operands and inserting
410 /// copies. This method is responsible for determining which operands receive
412 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
413 LiveIntervals& LI = getAnalysis<LiveIntervals>();
414 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
416 // Holds names that have been added to a set in any PHI within this block
417 // before the current one.
418 std::set<unsigned> ProcessedNames;
420 // Iterate over all the PHI nodes in this block
421 MachineBasicBlock::iterator P = MBB->begin();
422 while (P != MBB->end() && P->isPHI()) {
423 unsigned DestReg = P->getOperand(0).getReg();
425 // Don't both doing PHI elimination for dead PHI's.
426 if (P->registerDefIsDead(DestReg)) {
431 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
432 SlotIndex pIdx = LI.getInstructionIndex(P).getDefIndex();
433 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
434 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
436 // PHIUnion is the set of incoming registers to the PHI node that
437 // are going to be renames rather than having copies inserted. This set
438 // is refinded over the course of this function. UnionedBlocks is the set
439 // of corresponding MBBs.
440 std::map<unsigned, MachineBasicBlock*> PHIUnion;
441 SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
443 // Iterate over the operands of the PHI node
444 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
445 unsigned SrcReg = P->getOperand(i-1).getReg();
447 // Don't need to try to coalesce a register with itself.
448 if (SrcReg == DestReg) {
449 ProcessedNames.insert(SrcReg);
453 // We don't need to insert copies for implicit_defs.
454 MachineInstr* DefMI = MRI.getVRegDef(SrcReg);
455 if (DefMI->isImplicitDef())
456 ProcessedNames.insert(SrcReg);
458 // Check for trivial interferences via liveness information, allowing us
459 // to avoid extra work later. Any registers that interfere cannot both
460 // be in the renaming set, so choose one and add copies for it instead.
461 // The conditions are:
462 // 1) if the operand is live into the PHI node's block OR
463 // 2) if the PHI node is live out of the operand's defining block OR
464 // 3) if the operand is itself a PHI node and the original PHI is
465 // live into the operand's defining block OR
466 // 4) if the operand is already being renamed for another PHI node
468 // 5) if any two operands are defined in the same block, insert copies
470 if (isLiveIn(SrcReg, P->getParent(), LI) ||
471 isLiveOut(P->getOperand(0).getReg(),
472 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
473 ( MRI.getVRegDef(SrcReg)->isPHI() &&
474 isLiveIn(P->getOperand(0).getReg(),
475 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
476 ProcessedNames.count(SrcReg) ||
477 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
479 // Add a copy for the selected register
480 MachineBasicBlock* From = P->getOperand(i).getMBB();
481 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
482 UsedByAnother.insert(SrcReg);
484 // Otherwise, add it to the renaming set
485 PHIUnion.insert(std::make_pair(SrcReg,P->getOperand(i).getMBB()));
486 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
490 // Compute the dominator forest for the renaming set. This is a forest
491 // where the nodes are the registers and the edges represent dominance
492 // relations between the defining blocks of the registers
493 std::vector<StrongPHIElimination::DomForestNode*> DF =
494 computeDomForest(PHIUnion, MRI);
496 // Walk DomForest to resolve interferences at an inter-block level. This
497 // will remove registers from the renaming set (and insert copies for them)
498 // if interferences are found.
499 std::vector<std::pair<unsigned, unsigned> > localInterferences;
500 processPHIUnion(P, PHIUnion, DF, localInterferences);
502 // If one of the inputs is defined in the same block as the current PHI
503 // then we need to check for a local interference between that input and
505 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
506 E = PHIUnion.end(); I != E; ++I)
507 if (MRI.getVRegDef(I->first)->getParent() == P->getParent())
508 localInterferences.push_back(std::make_pair(I->first,
509 P->getOperand(0).getReg()));
511 // The dominator forest walk may have returned some register pairs whose
512 // interference cannot be determined from dominator analysis. We now
513 // examine these pairs for local interferences.
514 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
515 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
516 std::pair<unsigned, unsigned> p = *I;
518 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
520 // Determine the block we need to scan and the relationship between
522 MachineBasicBlock* scan = 0;
524 if (MRI.getVRegDef(p.first)->getParent() ==
525 MRI.getVRegDef(p.second)->getParent()) {
526 scan = MRI.getVRegDef(p.first)->getParent();
527 mode = 0; // Same block
528 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
529 MRI.getVRegDef(p.second)->getParent())) {
530 scan = MRI.getVRegDef(p.second)->getParent();
531 mode = 1; // First dominates second
533 scan = MRI.getVRegDef(p.first)->getParent();
534 mode = 2; // Second dominates first
537 // If there's an interference, we need to insert copies
538 if (interferes(p.first, p.second, scan, LI, mode)) {
539 // Insert copies for First
540 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
541 if (P->getOperand(i-1).getReg() == p.first) {
542 unsigned SrcReg = p.first;
543 MachineBasicBlock* From = P->getOperand(i).getMBB();
545 Waiting[From].insert(std::make_pair(SrcReg,
546 P->getOperand(0).getReg()));
547 UsedByAnother.insert(SrcReg);
549 PHIUnion.erase(SrcReg);
555 // Add the renaming set for this PHI node to our overall renaming information
556 for (std::map<unsigned, MachineBasicBlock*>::iterator QI = PHIUnion.begin(),
557 QE = PHIUnion.end(); QI != QE; ++QI) {
558 DEBUG(dbgs() << "Adding Renaming: " << QI->first << " -> "
559 << P->getOperand(0).getReg() << "\n");
562 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
564 // Remember which registers are already renamed, so that we don't try to
565 // rename them for another PHI node in this block
566 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
567 E = PHIUnion.end(); I != E; ++I)
568 ProcessedNames.insert(I->first);
574 /// processPHIUnion - Take a set of candidate registers to be coalesced when
575 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
576 /// that are known to interfere, and flag others that need to be checked for
577 /// local interferences.
578 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
579 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
580 std::vector<StrongPHIElimination::DomForestNode*>& DF,
581 std::vector<std::pair<unsigned, unsigned> >& locals) {
583 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
584 SmallPtrSet<DomForestNode*, 4> visited;
586 // Code is still in SSA form, so we can use MRI::getVRegDef()
587 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
589 LiveIntervals& LI = getAnalysis<LiveIntervals>();
590 unsigned DestReg = Inst->getOperand(0).getReg();
592 // DF walk on the DomForest
593 while (!worklist.empty()) {
594 DomForestNode* DFNode = worklist.back();
596 visited.insert(DFNode);
598 bool inserted = false;
599 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
601 DomForestNode* child = *CI;
603 // If the current node is live-out of the defining block of one of its
604 // children, insert a copy for it. NOTE: The paper actually calls for
605 // a more elaborate heuristic for determining whether to insert copies
606 // for the child or the parent. In the interest of simplicity, we're
607 // just always choosing the parent.
608 if (isLiveOut(DFNode->getReg(),
609 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
610 // Insert copies for parent
611 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
612 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
613 unsigned SrcReg = DFNode->getReg();
614 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
616 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
617 UsedByAnother.insert(SrcReg);
619 PHIUnion.erase(SrcReg);
623 // If a node is live-in to the defining block of one of its children, but
624 // not live-out, then we need to scan that block for local interferences.
625 } else if (isLiveIn(DFNode->getReg(),
626 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
627 MRI.getVRegDef(DFNode->getReg())->getParent() ==
628 MRI.getVRegDef(child->getReg())->getParent()) {
629 // Add (p, c) to possible local interferences
630 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
633 if (!visited.count(child)) {
634 worklist.push_back(child);
639 if (!inserted) worklist.pop_back();
643 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
644 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
647 /// Based on "Practical Improvements to the Construction and Destruction
648 /// of Static Single Assignment Form" by Briggs, et al.
649 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
650 std::set<unsigned>& pushed) {
651 // FIXME: This function needs to update LiveIntervals
652 std::multimap<unsigned, unsigned>& copy_set= Waiting[MBB];
654 std::multimap<unsigned, unsigned> worklist;
655 std::map<unsigned, unsigned> map;
657 // Setup worklist of initial copies
658 for (std::multimap<unsigned, unsigned>::iterator I = copy_set.begin(),
659 E = copy_set.end(); I != E; ) {
660 map.insert(std::make_pair(I->first, I->first));
661 map.insert(std::make_pair(I->second, I->second));
663 if (!UsedByAnother.count(I->second)) {
666 // Avoid iterator invalidation
667 std::multimap<unsigned, unsigned>::iterator OI = I;
675 LiveIntervals& LI = getAnalysis<LiveIntervals>();
676 MachineFunction* MF = MBB->getParent();
677 MachineRegisterInfo& MRI = MF->getRegInfo();
678 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
680 SmallVector<std::pair<unsigned, MachineInstr*>, 4> InsertedPHIDests;
682 // Iterate over the worklist, inserting copies
683 while (!worklist.empty() || !copy_set.empty()) {
684 while (!worklist.empty()) {
685 std::multimap<unsigned, unsigned>::iterator WI = worklist.begin();
686 std::pair<unsigned, unsigned> curr = *WI;
689 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
691 if (isLiveOut(curr.second, MBB, LI)) {
692 // Create a temporary
693 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
695 // Insert copy from curr.second to a temporary at
696 // the Phi defining curr.second
697 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
698 BuildMI(*PI->getParent(), PI, DebugLoc(), TII->get(TargetOpcode::COPY),
699 t).addReg(curr.second);
700 DEBUG(dbgs() << "Inserted copy from " << curr.second << " to " << t
703 // Push temporary on Stacks
704 Stacks[curr.second].push_back(t);
706 // Insert curr.second in pushed
707 pushed.insert(curr.second);
709 // Create a live interval for this temporary
710 InsertedPHIDests.push_back(std::make_pair(t, --PI));
713 // Insert copy from map[curr.first] to curr.second
714 BuildMI(*MBB, MBB->getFirstTerminator(), DebugLoc(),
715 TII->get(TargetOpcode::COPY), curr.second).addReg(map[curr.first]);
716 map[curr.first] = curr.second;
717 DEBUG(dbgs() << "Inserted copy from " << curr.first << " to "
718 << curr.second << "\n");
720 // Push this copy onto InsertedPHICopies so we can
721 // update LiveIntervals with it.
722 MachineBasicBlock::iterator MI = MBB->getFirstTerminator();
723 InsertedPHIDests.push_back(std::make_pair(curr.second, --MI));
725 // If curr.first is a destination in copy_set...
726 for (std::multimap<unsigned, unsigned>::iterator I = copy_set.begin(),
727 E = copy_set.end(); I != E; )
728 if (curr.first == I->second) {
729 std::pair<unsigned, unsigned> temp = *I;
730 worklist.insert(temp);
732 // Avoid iterator invalidation
733 std::multimap<unsigned, unsigned>::iterator OI = I;
743 if (!copy_set.empty()) {
744 std::multimap<unsigned, unsigned>::iterator CI = copy_set.begin();
745 std::pair<unsigned, unsigned> curr = *CI;
746 worklist.insert(curr);
749 LiveInterval& I = LI.getInterval(curr.second);
750 MachineBasicBlock::iterator term = MBB->getFirstTerminator();
751 SlotIndex endIdx = SlotIndex();
752 if (term != MBB->end())
753 endIdx = LI.getInstructionIndex(term);
755 endIdx = LI.getMBBEndIdx(MBB);
757 if (I.liveAt(endIdx)) {
758 const TargetRegisterClass *RC =
759 MF->getRegInfo().getRegClass(curr.first);
761 // Insert a copy from dest to a new temporary t at the end of b
762 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
763 BuildMI(*MBB, MBB->getFirstTerminator(), DebugLoc(),
764 TII->get(TargetOpcode::COPY), t).addReg(curr.second);
765 map[curr.second] = t;
767 MachineBasicBlock::iterator TI = MBB->getFirstTerminator();
768 InsertedPHIDests.push_back(std::make_pair(t, --TI));
773 // Renumber the instructions so that we can perform the index computations
774 // needed to create new live intervals.
777 // For copies that we inserted at the ends of predecessors, we construct
778 // live intervals. This is pretty easy, since we know that the destination
779 // register cannot have be in live at that point previously. We just have
780 // to make sure that, for registers that serve as inputs to more than one
781 // PHI, we don't create multiple overlapping live intervals.
782 std::set<unsigned> RegHandled;
783 for (SmallVector<std::pair<unsigned, MachineInstr*>, 4>::iterator I =
784 InsertedPHIDests.begin(), E = InsertedPHIDests.end(); I != E; ++I) {
785 if (RegHandled.insert(I->first).second) {
786 LiveInterval& Int = LI.getOrCreateInterval(I->first);
787 SlotIndex instrIdx = LI.getInstructionIndex(I->second);
788 if (Int.liveAt(instrIdx.getDefIndex()))
789 Int.removeRange(instrIdx.getDefIndex(),
790 LI.getMBBEndIdx(I->second->getParent()).getNextSlot(),
793 LiveRange R = LI.addLiveRangeToEndOfBlock(I->first, I->second);
794 R.valno->setCopy(I->second);
795 R.valno->def = LI.getInstructionIndex(I->second).getDefIndex();
800 /// InsertCopies - insert copies into MBB and all of its successors
801 void StrongPHIElimination::InsertCopies(MachineDomTreeNode* MDTN,
802 SmallPtrSet<MachineBasicBlock*, 16>& visited) {
803 MachineBasicBlock* MBB = MDTN->getBlock();
806 std::set<unsigned> pushed;
808 LiveIntervals& LI = getAnalysis<LiveIntervals>();
809 // Rewrite register uses from Stacks
810 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
815 for (unsigned i = 0; i < I->getNumOperands(); ++i)
816 if (I->getOperand(i).isReg() &&
817 Stacks[I->getOperand(i).getReg()].size()) {
818 // Remove the live range for the old vreg.
819 LiveInterval& OldInt = LI.getInterval(I->getOperand(i).getReg());
820 LiveInterval::iterator OldLR =
821 OldInt.FindLiveRangeContaining(LI.getInstructionIndex(I).getUseIndex());
822 if (OldLR != OldInt.end())
823 OldInt.removeRange(*OldLR, true);
825 // Change the register
826 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
828 // Add a live range for the new vreg
829 LiveInterval& Int = LI.getInterval(I->getOperand(i).getReg());
830 VNInfo* FirstVN = *Int.vni_begin();
831 FirstVN->setHasPHIKill(false);
832 LiveRange LR (LI.getMBBStartIdx(I->getParent()),
833 LI.getInstructionIndex(I).getUseIndex().getNextSlot(),
840 // Schedule the copies for this block
841 ScheduleCopies(MBB, pushed);
843 // Recur down the dominator tree.
844 for (MachineDomTreeNode::iterator I = MDTN->begin(),
845 E = MDTN->end(); I != E; ++I)
846 if (!visited.count((*I)->getBlock()))
847 InsertCopies(*I, visited);
849 // As we exit this block, pop the names we pushed while processing it
850 for (std::set<unsigned>::iterator I = pushed.begin(),
851 E = pushed.end(); I != E; ++I)
852 Stacks[*I].pop_back();
855 bool StrongPHIElimination::mergeLiveIntervals(unsigned primary,
856 unsigned secondary) {
858 LiveIntervals& LI = getAnalysis<LiveIntervals>();
859 LiveInterval& LHS = LI.getOrCreateInterval(primary);
860 LiveInterval& RHS = LI.getOrCreateInterval(secondary);
864 DenseMap<VNInfo*, VNInfo*> VNMap;
865 for (LiveInterval::iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
868 SlotIndex Start = R.start;
869 SlotIndex End = R.end;
870 if (LHS.getLiveRangeContaining(Start))
873 if (LHS.getLiveRangeContaining(End))
876 LiveInterval::iterator RI = std::upper_bound(LHS.begin(), LHS.end(), R);
877 if (RI != LHS.end() && RI->start < End)
881 for (LiveInterval::iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
883 VNInfo* OldVN = R.valno;
884 VNInfo*& NewVN = VNMap[OldVN];
886 NewVN = LHS.createValueCopy(OldVN, LI.getVNInfoAllocator());
889 LiveRange LR (R.start, R.end, NewVN);
893 LI.removeInterval(RHS.reg);
898 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
899 LiveIntervals& LI = getAnalysis<LiveIntervals>();
901 // Compute DFS numbers of each block
904 // Determine which phi node operands need copies
905 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
906 if (!I->empty() && I->begin()->isPHI())
909 // Break interferences where two different phis want to coalesce
910 // in the same register.
911 std::set<unsigned> seen;
912 typedef std::map<unsigned, std::map<unsigned, MachineBasicBlock*> >
914 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
916 for (std::map<unsigned, MachineBasicBlock*>::iterator
917 OI = I->second.begin(), OE = I->second.end(); OI != OE; ) {
918 if (!seen.count(OI->first)) {
919 seen.insert(OI->first);
922 Waiting[OI->second].insert(std::make_pair(OI->first, I->first));
923 unsigned reg = OI->first;
925 I->second.erase(reg);
926 DEBUG(dbgs() << "Removing Renaming: " << reg << " -> " << I->first
933 // FIXME: This process should probably preserve LiveIntervals
934 SmallPtrSet<MachineBasicBlock*, 16> visited;
935 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
936 InsertCopies(MDT.getRootNode(), visited);
939 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
941 while (I->second.size()) {
942 std::map<unsigned, MachineBasicBlock*>::iterator SI = I->second.begin();
944 DEBUG(dbgs() << "Renaming: " << SI->first << " -> " << I->first << "\n");
946 if (SI->first != I->first) {
947 if (mergeLiveIntervals(I->first, SI->first)) {
948 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
950 if (RenameSets.count(SI->first)) {
951 I->second.insert(RenameSets[SI->first].begin(),
952 RenameSets[SI->first].end());
953 RenameSets.erase(SI->first);
956 // Insert a last-minute copy if a conflict was detected.
957 const TargetInstrInfo *TII = Fn.getTarget().getInstrInfo();
958 BuildMI(*SI->second, SI->second->getFirstTerminator(), DebugLoc(),
959 TII->get(TargetOpcode::COPY), I->first).addReg(SI->first);
963 LiveInterval& Int = LI.getOrCreateInterval(I->first);
965 LI.getInstructionIndex(--SI->second->getFirstTerminator());
966 if (Int.liveAt(instrIdx.getDefIndex()))
967 Int.removeRange(instrIdx.getDefIndex(),
968 LI.getMBBEndIdx(SI->second).getNextSlot(), true);
970 LiveRange R = LI.addLiveRangeToEndOfBlock(I->first,
971 --SI->second->getFirstTerminator());
972 R.valno->setCopy(--SI->second->getFirstTerminator());
973 R.valno->def = instrIdx.getDefIndex();
975 DEBUG(dbgs() << "Renaming failed: " << SI->first << " -> "
976 << I->first << "\n");
980 LiveInterval& Int = LI.getOrCreateInterval(I->first);
981 const LiveRange* LR =
982 Int.getLiveRangeContaining(LI.getMBBEndIdx(SI->second));
983 LR->valno->setHasPHIKill(true);
985 I->second.erase(SI->first);
989 std::vector<MachineInstr*> phis;
990 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
991 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
997 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
999 MachineInstr* PInstr = *(I++);
1001 // If this is a dead PHI node, then remove it from LiveIntervals.
1002 unsigned DestReg = PInstr->getOperand(0).getReg();
1003 LiveInterval& PI = LI.getInterval(DestReg);
1004 if (PInstr->registerDefIsDead(DestReg)) {
1005 if (PI.containsOneValue()) {
1006 LI.removeInterval(DestReg);
1008 SlotIndex idx = LI.getInstructionIndex(PInstr).getDefIndex();
1009 PI.removeRange(*PI.getLiveRangeContaining(idx), true);
1012 // Trim live intervals of input registers. They are no longer live into
1013 // this block if they died after the PHI. If they lived after it, don't
1014 // trim them because they might have other legitimate uses.
1015 for (unsigned i = 1; i < PInstr->getNumOperands(); i += 2) {
1016 unsigned reg = PInstr->getOperand(i).getReg();
1018 MachineBasicBlock* MBB = PInstr->getOperand(i+1).getMBB();
1019 LiveInterval& InputI = LI.getInterval(reg);
1020 if (MBB != PInstr->getParent() &&
1021 InputI.liveAt(LI.getMBBStartIdx(PInstr->getParent())) &&
1022 InputI.expiredAt(LI.getInstructionIndex(PInstr).getNextIndex()))
1023 InputI.removeRange(LI.getMBBStartIdx(PInstr->getParent()),
1024 LI.getInstructionIndex(PInstr),
1028 // If the PHI is not dead, then the valno defined by the PHI
1029 // now has an unknown def.
1030 SlotIndex idx = LI.getInstructionIndex(PInstr).getDefIndex();
1031 const LiveRange* PLR = PI.getLiveRangeContaining(idx);
1032 PLR->valno->setIsPHIDef(true);
1033 LiveRange R (LI.getMBBStartIdx(PInstr->getParent()),
1034 PLR->start, PLR->valno);
1038 LI.RemoveMachineInstrFromMaps(PInstr);
1039 PInstr->eraseFromParent();