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 static RegisterPass<StrongPHIElimination>
154 X("strong-phi-node-elimination",
155 "Eliminate PHI nodes for register allocation, intelligently");
157 const PassInfo *const llvm::StrongPHIEliminationID = &X;
159 /// computeDFS - Computes the DFS-in and DFS-out numbers of the dominator tree
160 /// of the given MachineFunction. These numbers are then used in other parts
161 /// of the PHI elimination process.
162 void StrongPHIElimination::computeDFS(MachineFunction& MF) {
163 SmallPtrSet<MachineDomTreeNode*, 8> frontier;
164 SmallPtrSet<MachineDomTreeNode*, 8> visited;
168 MachineDominatorTree& DT = getAnalysis<MachineDominatorTree>();
170 MachineDomTreeNode* node = DT.getRootNode();
172 std::vector<MachineDomTreeNode*> worklist;
173 worklist.push_back(node);
175 while (!worklist.empty()) {
176 MachineDomTreeNode* currNode = worklist.back();
178 if (!frontier.count(currNode)) {
179 frontier.insert(currNode);
181 preorder.insert(std::make_pair(currNode->getBlock(), time));
184 bool inserted = false;
185 for (MachineDomTreeNode::iterator I = currNode->begin(), E = currNode->end();
187 if (!frontier.count(*I) && !visited.count(*I)) {
188 worklist.push_back(*I);
194 frontier.erase(currNode);
195 visited.insert(currNode);
196 maxpreorder.insert(std::make_pair(currNode->getBlock(), time));
205 /// PreorderSorter - a helper class that is used to sort registers
206 /// according to the preorder number of their defining blocks
207 class PreorderSorter {
209 DenseMap<MachineBasicBlock*, unsigned>& preorder;
210 MachineRegisterInfo& MRI;
213 PreorderSorter(DenseMap<MachineBasicBlock*, unsigned>& p,
214 MachineRegisterInfo& M) : preorder(p), MRI(M) { }
216 bool operator()(unsigned A, unsigned B) {
220 MachineBasicBlock* ABlock = MRI.getVRegDef(A)->getParent();
221 MachineBasicBlock* BBlock = MRI.getVRegDef(B)->getParent();
223 if (preorder[ABlock] < preorder[BBlock])
225 else if (preorder[ABlock] > preorder[BBlock])
234 /// computeDomForest - compute the subforest of the DomTree corresponding
235 /// to the defining blocks of the registers in question
236 std::vector<StrongPHIElimination::DomForestNode*>
237 StrongPHIElimination::computeDomForest(
238 std::map<unsigned, MachineBasicBlock*>& regs,
239 MachineRegisterInfo& MRI) {
240 // Begin by creating a virtual root node, since the actual results
241 // may well be a forest. Assume this node has maximum DFS-out number.
242 DomForestNode* VirtualRoot = new DomForestNode(0, 0);
243 maxpreorder.insert(std::make_pair((MachineBasicBlock*)0, ~0UL));
245 // Populate a worklist with the registers
246 std::vector<unsigned> worklist;
247 worklist.reserve(regs.size());
248 for (std::map<unsigned, MachineBasicBlock*>::iterator I = regs.begin(),
249 E = regs.end(); I != E; ++I)
250 worklist.push_back(I->first);
252 // Sort the registers by the DFS-in number of their defining block
253 PreorderSorter PS(preorder, MRI);
254 std::sort(worklist.begin(), worklist.end(), PS);
256 // Create a "current parent" stack, and put the virtual root on top of it
257 DomForestNode* CurrentParent = VirtualRoot;
258 std::vector<DomForestNode*> stack;
259 stack.push_back(VirtualRoot);
261 // Iterate over all the registers in the previously computed order
262 for (std::vector<unsigned>::iterator I = worklist.begin(), E = worklist.end();
264 unsigned pre = preorder[MRI.getVRegDef(*I)->getParent()];
265 MachineBasicBlock* parentBlock = CurrentParent->getReg() ?
266 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
269 // If the DFS-in number of the register is greater than the DFS-out number
270 // of the current parent, repeatedly pop the parent stack until it isn't.
271 while (pre > maxpreorder[parentBlock]) {
273 CurrentParent = stack.back();
275 parentBlock = CurrentParent->getReg() ?
276 MRI.getVRegDef(CurrentParent->getReg())->getParent() :
280 // Now that we've found the appropriate parent, create a DomForestNode for
281 // this register and attach it to the forest
282 DomForestNode* child = new DomForestNode(*I, CurrentParent);
284 // Push this new node on the "current parent" stack
285 stack.push_back(child);
286 CurrentParent = child;
289 // Return a vector containing the children of the virtual root node
290 std::vector<DomForestNode*> ret;
291 ret.insert(ret.end(), VirtualRoot->begin(), VirtualRoot->end());
295 /// isLiveIn - helper method that determines, from a regno, if a register
296 /// is live into a block
297 static bool isLiveIn(unsigned r, MachineBasicBlock* MBB,
299 LiveInterval& I = LI.getOrCreateInterval(r);
300 SlotIndex idx = LI.getMBBStartIdx(MBB);
301 return I.liveAt(idx);
304 /// isLiveOut - help method that determines, from a regno, if a register is
305 /// live out of a block.
306 static bool isLiveOut(unsigned r, MachineBasicBlock* MBB,
308 for (MachineBasicBlock::succ_iterator PI = MBB->succ_begin(),
309 E = MBB->succ_end(); PI != E; ++PI)
310 if (isLiveIn(r, *PI, LI))
316 /// interferes - checks for local interferences by scanning a block. The only
317 /// trick parameter is 'mode' which tells it the relationship of the two
318 /// registers. 0 - defined in the same block, 1 - first properly dominates
319 /// second, 2 - second properly dominates first
320 static bool interferes(unsigned a, unsigned b, MachineBasicBlock* scan,
321 LiveIntervals& LV, unsigned mode) {
322 MachineInstr* def = 0;
323 MachineInstr* kill = 0;
325 // The code is still in SSA form at this point, so there is only one
326 // definition per VReg. Thus we can safely use MRI->getVRegDef().
327 const MachineRegisterInfo* MRI = &scan->getParent()->getRegInfo();
329 bool interference = false;
331 // Wallk the block, checking for interferences
332 for (MachineBasicBlock::iterator MBI = scan->begin(), MBE = scan->end();
334 MachineInstr* curr = MBI;
336 // Same defining block...
338 if (curr == MRI->getVRegDef(a)) {
339 // If we find our first definition, save it
342 // If there's already an unkilled definition, then
343 // this is an interference
347 // If there's a definition followed by a KillInst, then
348 // they can't interfere
350 interference = false;
353 // Symmetric with the above
354 } else if (curr == MRI->getVRegDef(b)) {
361 interference = false;
364 // Store KillInsts if they match up with the definition
365 } else if (curr->killsRegister(a)) {
366 if (def == MRI->getVRegDef(a)) {
368 } else if (curr->killsRegister(b)) {
369 if (def == MRI->getVRegDef(b)) {
374 // First properly dominates second...
375 } else if (mode == 1) {
376 if (curr == MRI->getVRegDef(b)) {
377 // Definition of second without kill of first is an interference
381 // Definition after a kill is a non-interference
383 interference = false;
386 // Save KillInsts of First
387 } else if (curr->killsRegister(a)) {
390 // Symmetric with the above
391 } else if (mode == 2) {
392 if (curr == MRI->getVRegDef(a)) {
397 interference = false;
400 } else if (curr->killsRegister(b)) {
409 /// processBlock - Determine how to break up PHIs in the current block. Each
410 /// PHI is broken up by some combination of renaming its operands and inserting
411 /// copies. This method is responsible for determining which operands receive
413 void StrongPHIElimination::processBlock(MachineBasicBlock* MBB) {
414 LiveIntervals& LI = getAnalysis<LiveIntervals>();
415 MachineRegisterInfo& MRI = MBB->getParent()->getRegInfo();
417 // Holds names that have been added to a set in any PHI within this block
418 // before the current one.
419 std::set<unsigned> ProcessedNames;
421 // Iterate over all the PHI nodes in this block
422 MachineBasicBlock::iterator P = MBB->begin();
423 while (P != MBB->end() && P->isPHI()) {
424 unsigned DestReg = P->getOperand(0).getReg();
426 // Don't both doing PHI elimination for dead PHI's.
427 if (P->registerDefIsDead(DestReg)) {
432 LiveInterval& PI = LI.getOrCreateInterval(DestReg);
433 SlotIndex pIdx = LI.getInstructionIndex(P).getDefIndex();
434 VNInfo* PVN = PI.getLiveRangeContaining(pIdx)->valno;
435 PhiValueNumber.insert(std::make_pair(DestReg, PVN->id));
437 // PHIUnion is the set of incoming registers to the PHI node that
438 // are going to be renames rather than having copies inserted. This set
439 // is refinded over the course of this function. UnionedBlocks is the set
440 // of corresponding MBBs.
441 std::map<unsigned, MachineBasicBlock*> PHIUnion;
442 SmallPtrSet<MachineBasicBlock*, 8> UnionedBlocks;
444 // Iterate over the operands of the PHI node
445 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
446 unsigned SrcReg = P->getOperand(i-1).getReg();
448 // Don't need to try to coalesce a register with itself.
449 if (SrcReg == DestReg) {
450 ProcessedNames.insert(SrcReg);
454 // We don't need to insert copies for implicit_defs.
455 MachineInstr* DefMI = MRI.getVRegDef(SrcReg);
456 if (DefMI->isImplicitDef())
457 ProcessedNames.insert(SrcReg);
459 // Check for trivial interferences via liveness information, allowing us
460 // to avoid extra work later. Any registers that interfere cannot both
461 // be in the renaming set, so choose one and add copies for it instead.
462 // The conditions are:
463 // 1) if the operand is live into the PHI node's block OR
464 // 2) if the PHI node is live out of the operand's defining block OR
465 // 3) if the operand is itself a PHI node and the original PHI is
466 // live into the operand's defining block OR
467 // 4) if the operand is already being renamed for another PHI node
469 // 5) if any two operands are defined in the same block, insert copies
471 if (isLiveIn(SrcReg, P->getParent(), LI) ||
472 isLiveOut(P->getOperand(0).getReg(),
473 MRI.getVRegDef(SrcReg)->getParent(), LI) ||
474 ( MRI.getVRegDef(SrcReg)->isPHI() &&
475 isLiveIn(P->getOperand(0).getReg(),
476 MRI.getVRegDef(SrcReg)->getParent(), LI) ) ||
477 ProcessedNames.count(SrcReg) ||
478 UnionedBlocks.count(MRI.getVRegDef(SrcReg)->getParent())) {
480 // Add a copy for the selected register
481 MachineBasicBlock* From = P->getOperand(i).getMBB();
482 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
483 UsedByAnother.insert(SrcReg);
485 // Otherwise, add it to the renaming set
486 PHIUnion.insert(std::make_pair(SrcReg,P->getOperand(i).getMBB()));
487 UnionedBlocks.insert(MRI.getVRegDef(SrcReg)->getParent());
491 // Compute the dominator forest for the renaming set. This is a forest
492 // where the nodes are the registers and the edges represent dominance
493 // relations between the defining blocks of the registers
494 std::vector<StrongPHIElimination::DomForestNode*> DF =
495 computeDomForest(PHIUnion, MRI);
497 // Walk DomForest to resolve interferences at an inter-block level. This
498 // will remove registers from the renaming set (and insert copies for them)
499 // if interferences are found.
500 std::vector<std::pair<unsigned, unsigned> > localInterferences;
501 processPHIUnion(P, PHIUnion, DF, localInterferences);
503 // If one of the inputs is defined in the same block as the current PHI
504 // then we need to check for a local interference between that input and
506 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
507 E = PHIUnion.end(); I != E; ++I)
508 if (MRI.getVRegDef(I->first)->getParent() == P->getParent())
509 localInterferences.push_back(std::make_pair(I->first,
510 P->getOperand(0).getReg()));
512 // The dominator forest walk may have returned some register pairs whose
513 // interference cannot be determined from dominator analysis. We now
514 // examine these pairs for local interferences.
515 for (std::vector<std::pair<unsigned, unsigned> >::iterator I =
516 localInterferences.begin(), E = localInterferences.end(); I != E; ++I) {
517 std::pair<unsigned, unsigned> p = *I;
519 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
521 // Determine the block we need to scan and the relationship between
523 MachineBasicBlock* scan = 0;
525 if (MRI.getVRegDef(p.first)->getParent() ==
526 MRI.getVRegDef(p.second)->getParent()) {
527 scan = MRI.getVRegDef(p.first)->getParent();
528 mode = 0; // Same block
529 } else if (MDT.dominates(MRI.getVRegDef(p.first)->getParent(),
530 MRI.getVRegDef(p.second)->getParent())) {
531 scan = MRI.getVRegDef(p.second)->getParent();
532 mode = 1; // First dominates second
534 scan = MRI.getVRegDef(p.first)->getParent();
535 mode = 2; // Second dominates first
538 // If there's an interference, we need to insert copies
539 if (interferes(p.first, p.second, scan, LI, mode)) {
540 // Insert copies for First
541 for (int i = P->getNumOperands() - 1; i >= 2; i-=2) {
542 if (P->getOperand(i-1).getReg() == p.first) {
543 unsigned SrcReg = p.first;
544 MachineBasicBlock* From = P->getOperand(i).getMBB();
546 Waiting[From].insert(std::make_pair(SrcReg,
547 P->getOperand(0).getReg()));
548 UsedByAnother.insert(SrcReg);
550 PHIUnion.erase(SrcReg);
556 // Add the renaming set for this PHI node to our overall renaming information
557 for (std::map<unsigned, MachineBasicBlock*>::iterator QI = PHIUnion.begin(),
558 QE = PHIUnion.end(); QI != QE; ++QI) {
559 DEBUG(dbgs() << "Adding Renaming: " << QI->first << " -> "
560 << P->getOperand(0).getReg() << "\n");
563 RenameSets.insert(std::make_pair(P->getOperand(0).getReg(), PHIUnion));
565 // Remember which registers are already renamed, so that we don't try to
566 // rename them for another PHI node in this block
567 for (std::map<unsigned, MachineBasicBlock*>::iterator I = PHIUnion.begin(),
568 E = PHIUnion.end(); I != E; ++I)
569 ProcessedNames.insert(I->first);
575 /// processPHIUnion - Take a set of candidate registers to be coalesced when
576 /// decomposing the PHI instruction. Use the DominanceForest to remove the ones
577 /// that are known to interfere, and flag others that need to be checked for
578 /// local interferences.
579 void StrongPHIElimination::processPHIUnion(MachineInstr* Inst,
580 std::map<unsigned, MachineBasicBlock*>& PHIUnion,
581 std::vector<StrongPHIElimination::DomForestNode*>& DF,
582 std::vector<std::pair<unsigned, unsigned> >& locals) {
584 std::vector<DomForestNode*> worklist(DF.begin(), DF.end());
585 SmallPtrSet<DomForestNode*, 4> visited;
587 // Code is still in SSA form, so we can use MRI::getVRegDef()
588 MachineRegisterInfo& MRI = Inst->getParent()->getParent()->getRegInfo();
590 LiveIntervals& LI = getAnalysis<LiveIntervals>();
591 unsigned DestReg = Inst->getOperand(0).getReg();
593 // DF walk on the DomForest
594 while (!worklist.empty()) {
595 DomForestNode* DFNode = worklist.back();
597 visited.insert(DFNode);
599 bool inserted = false;
600 for (DomForestNode::iterator CI = DFNode->begin(), CE = DFNode->end();
602 DomForestNode* child = *CI;
604 // If the current node is live-out of the defining block of one of its
605 // children, insert a copy for it. NOTE: The paper actually calls for
606 // a more elaborate heuristic for determining whether to insert copies
607 // for the child or the parent. In the interest of simplicity, we're
608 // just always choosing the parent.
609 if (isLiveOut(DFNode->getReg(),
610 MRI.getVRegDef(child->getReg())->getParent(), LI)) {
611 // Insert copies for parent
612 for (int i = Inst->getNumOperands() - 1; i >= 2; i-=2) {
613 if (Inst->getOperand(i-1).getReg() == DFNode->getReg()) {
614 unsigned SrcReg = DFNode->getReg();
615 MachineBasicBlock* From = Inst->getOperand(i).getMBB();
617 Waiting[From].insert(std::make_pair(SrcReg, DestReg));
618 UsedByAnother.insert(SrcReg);
620 PHIUnion.erase(SrcReg);
624 // If a node is live-in to the defining block of one of its children, but
625 // not live-out, then we need to scan that block for local interferences.
626 } else if (isLiveIn(DFNode->getReg(),
627 MRI.getVRegDef(child->getReg())->getParent(), LI) ||
628 MRI.getVRegDef(DFNode->getReg())->getParent() ==
629 MRI.getVRegDef(child->getReg())->getParent()) {
630 // Add (p, c) to possible local interferences
631 locals.push_back(std::make_pair(DFNode->getReg(), child->getReg()));
634 if (!visited.count(child)) {
635 worklist.push_back(child);
640 if (!inserted) worklist.pop_back();
644 /// ScheduleCopies - Insert copies into predecessor blocks, scheduling
645 /// them properly so as to avoid the 'lost copy' and the 'virtual swap'
648 /// Based on "Practical Improvements to the Construction and Destruction
649 /// of Static Single Assignment Form" by Briggs, et al.
650 void StrongPHIElimination::ScheduleCopies(MachineBasicBlock* MBB,
651 std::set<unsigned>& pushed) {
652 // FIXME: This function needs to update LiveIntervals
653 std::multimap<unsigned, unsigned>& copy_set= Waiting[MBB];
655 std::multimap<unsigned, unsigned> worklist;
656 std::map<unsigned, unsigned> map;
658 // Setup worklist of initial copies
659 for (std::multimap<unsigned, unsigned>::iterator I = copy_set.begin(),
660 E = copy_set.end(); I != E; ) {
661 map.insert(std::make_pair(I->first, I->first));
662 map.insert(std::make_pair(I->second, I->second));
664 if (!UsedByAnother.count(I->second)) {
667 // Avoid iterator invalidation
668 std::multimap<unsigned, unsigned>::iterator OI = I;
676 LiveIntervals& LI = getAnalysis<LiveIntervals>();
677 MachineFunction* MF = MBB->getParent();
678 MachineRegisterInfo& MRI = MF->getRegInfo();
679 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
681 SmallVector<std::pair<unsigned, MachineInstr*>, 4> InsertedPHIDests;
683 // Iterate over the worklist, inserting copies
684 while (!worklist.empty() || !copy_set.empty()) {
685 while (!worklist.empty()) {
686 std::multimap<unsigned, unsigned>::iterator WI = worklist.begin();
687 std::pair<unsigned, unsigned> curr = *WI;
690 const TargetRegisterClass *RC = MF->getRegInfo().getRegClass(curr.first);
692 if (isLiveOut(curr.second, MBB, LI)) {
693 // Create a temporary
694 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
696 // Insert copy from curr.second to a temporary at
697 // the Phi defining curr.second
698 MachineBasicBlock::iterator PI = MRI.getVRegDef(curr.second);
699 BuildMI(*PI->getParent(), PI, DebugLoc(), TII->get(TargetOpcode::COPY),
700 t).addReg(curr.second);
701 DEBUG(dbgs() << "Inserted copy from " << curr.second << " to " << t
704 // Push temporary on Stacks
705 Stacks[curr.second].push_back(t);
707 // Insert curr.second in pushed
708 pushed.insert(curr.second);
710 // Create a live interval for this temporary
711 InsertedPHIDests.push_back(std::make_pair(t, --PI));
714 // Insert copy from map[curr.first] to curr.second
715 BuildMI(*MBB, MBB->getFirstTerminator(), DebugLoc(),
716 TII->get(TargetOpcode::COPY), curr.second).addReg(map[curr.first]);
717 map[curr.first] = curr.second;
718 DEBUG(dbgs() << "Inserted copy from " << curr.first << " to "
719 << curr.second << "\n");
721 // Push this copy onto InsertedPHICopies so we can
722 // update LiveIntervals with it.
723 MachineBasicBlock::iterator MI = MBB->getFirstTerminator();
724 InsertedPHIDests.push_back(std::make_pair(curr.second, --MI));
726 // If curr.first is a destination in copy_set...
727 for (std::multimap<unsigned, unsigned>::iterator I = copy_set.begin(),
728 E = copy_set.end(); I != E; )
729 if (curr.first == I->second) {
730 std::pair<unsigned, unsigned> temp = *I;
731 worklist.insert(temp);
733 // Avoid iterator invalidation
734 std::multimap<unsigned, unsigned>::iterator OI = I;
744 if (!copy_set.empty()) {
745 std::multimap<unsigned, unsigned>::iterator CI = copy_set.begin();
746 std::pair<unsigned, unsigned> curr = *CI;
747 worklist.insert(curr);
750 LiveInterval& I = LI.getInterval(curr.second);
751 MachineBasicBlock::iterator term = MBB->getFirstTerminator();
752 SlotIndex endIdx = SlotIndex();
753 if (term != MBB->end())
754 endIdx = LI.getInstructionIndex(term);
756 endIdx = LI.getMBBEndIdx(MBB);
758 if (I.liveAt(endIdx)) {
759 const TargetRegisterClass *RC =
760 MF->getRegInfo().getRegClass(curr.first);
762 // Insert a copy from dest to a new temporary t at the end of b
763 unsigned t = MF->getRegInfo().createVirtualRegister(RC);
764 BuildMI(*MBB, MBB->getFirstTerminator(), DebugLoc(),
765 TII->get(TargetOpcode::COPY), t).addReg(curr.second);
766 map[curr.second] = t;
768 MachineBasicBlock::iterator TI = MBB->getFirstTerminator();
769 InsertedPHIDests.push_back(std::make_pair(t, --TI));
774 // Renumber the instructions so that we can perform the index computations
775 // needed to create new live intervals.
778 // For copies that we inserted at the ends of predecessors, we construct
779 // live intervals. This is pretty easy, since we know that the destination
780 // register cannot have be in live at that point previously. We just have
781 // to make sure that, for registers that serve as inputs to more than one
782 // PHI, we don't create multiple overlapping live intervals.
783 std::set<unsigned> RegHandled;
784 for (SmallVector<std::pair<unsigned, MachineInstr*>, 4>::iterator I =
785 InsertedPHIDests.begin(), E = InsertedPHIDests.end(); I != E; ++I) {
786 if (RegHandled.insert(I->first).second) {
787 LiveInterval& Int = LI.getOrCreateInterval(I->first);
788 SlotIndex instrIdx = LI.getInstructionIndex(I->second);
789 if (Int.liveAt(instrIdx.getDefIndex()))
790 Int.removeRange(instrIdx.getDefIndex(),
791 LI.getMBBEndIdx(I->second->getParent()).getNextSlot(),
794 LiveRange R = LI.addLiveRangeToEndOfBlock(I->first, I->second);
795 R.valno->setCopy(I->second);
796 R.valno->def = LI.getInstructionIndex(I->second).getDefIndex();
801 /// InsertCopies - insert copies into MBB and all of its successors
802 void StrongPHIElimination::InsertCopies(MachineDomTreeNode* MDTN,
803 SmallPtrSet<MachineBasicBlock*, 16>& visited) {
804 MachineBasicBlock* MBB = MDTN->getBlock();
807 std::set<unsigned> pushed;
809 LiveIntervals& LI = getAnalysis<LiveIntervals>();
810 // Rewrite register uses from Stacks
811 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
816 for (unsigned i = 0; i < I->getNumOperands(); ++i)
817 if (I->getOperand(i).isReg() &&
818 Stacks[I->getOperand(i).getReg()].size()) {
819 // Remove the live range for the old vreg.
820 LiveInterval& OldInt = LI.getInterval(I->getOperand(i).getReg());
821 LiveInterval::iterator OldLR =
822 OldInt.FindLiveRangeContaining(LI.getInstructionIndex(I).getUseIndex());
823 if (OldLR != OldInt.end())
824 OldInt.removeRange(*OldLR, true);
826 // Change the register
827 I->getOperand(i).setReg(Stacks[I->getOperand(i).getReg()].back());
829 // Add a live range for the new vreg
830 LiveInterval& Int = LI.getInterval(I->getOperand(i).getReg());
831 VNInfo* FirstVN = *Int.vni_begin();
832 FirstVN->setHasPHIKill(false);
833 LiveRange LR (LI.getMBBStartIdx(I->getParent()),
834 LI.getInstructionIndex(I).getUseIndex().getNextSlot(),
841 // Schedule the copies for this block
842 ScheduleCopies(MBB, pushed);
844 // Recur down the dominator tree.
845 for (MachineDomTreeNode::iterator I = MDTN->begin(),
846 E = MDTN->end(); I != E; ++I)
847 if (!visited.count((*I)->getBlock()))
848 InsertCopies(*I, visited);
850 // As we exit this block, pop the names we pushed while processing it
851 for (std::set<unsigned>::iterator I = pushed.begin(),
852 E = pushed.end(); I != E; ++I)
853 Stacks[*I].pop_back();
856 bool StrongPHIElimination::mergeLiveIntervals(unsigned primary,
857 unsigned secondary) {
859 LiveIntervals& LI = getAnalysis<LiveIntervals>();
860 LiveInterval& LHS = LI.getOrCreateInterval(primary);
861 LiveInterval& RHS = LI.getOrCreateInterval(secondary);
865 DenseMap<VNInfo*, VNInfo*> VNMap;
866 for (LiveInterval::iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
869 SlotIndex Start = R.start;
870 SlotIndex End = R.end;
871 if (LHS.getLiveRangeContaining(Start))
874 if (LHS.getLiveRangeContaining(End))
877 LiveInterval::iterator RI = std::upper_bound(LHS.begin(), LHS.end(), R);
878 if (RI != LHS.end() && RI->start < End)
882 for (LiveInterval::iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
884 VNInfo* OldVN = R.valno;
885 VNInfo*& NewVN = VNMap[OldVN];
887 NewVN = LHS.createValueCopy(OldVN, LI.getVNInfoAllocator());
890 LiveRange LR (R.start, R.end, NewVN);
894 LI.removeInterval(RHS.reg);
899 bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
900 LiveIntervals& LI = getAnalysis<LiveIntervals>();
902 // Compute DFS numbers of each block
905 // Determine which phi node operands need copies
906 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
907 if (!I->empty() && I->begin()->isPHI())
910 // Break interferences where two different phis want to coalesce
911 // in the same register.
912 std::set<unsigned> seen;
913 typedef std::map<unsigned, std::map<unsigned, MachineBasicBlock*> >
915 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
917 for (std::map<unsigned, MachineBasicBlock*>::iterator
918 OI = I->second.begin(), OE = I->second.end(); OI != OE; ) {
919 if (!seen.count(OI->first)) {
920 seen.insert(OI->first);
923 Waiting[OI->second].insert(std::make_pair(OI->first, I->first));
924 unsigned reg = OI->first;
926 I->second.erase(reg);
927 DEBUG(dbgs() << "Removing Renaming: " << reg << " -> " << I->first
934 // FIXME: This process should probably preserve LiveIntervals
935 SmallPtrSet<MachineBasicBlock*, 16> visited;
936 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
937 InsertCopies(MDT.getRootNode(), visited);
940 for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
942 while (I->second.size()) {
943 std::map<unsigned, MachineBasicBlock*>::iterator SI = I->second.begin();
945 DEBUG(dbgs() << "Renaming: " << SI->first << " -> " << I->first << "\n");
947 if (SI->first != I->first) {
948 if (mergeLiveIntervals(I->first, SI->first)) {
949 Fn.getRegInfo().replaceRegWith(SI->first, I->first);
951 if (RenameSets.count(SI->first)) {
952 I->second.insert(RenameSets[SI->first].begin(),
953 RenameSets[SI->first].end());
954 RenameSets.erase(SI->first);
957 // Insert a last-minute copy if a conflict was detected.
958 const TargetInstrInfo *TII = Fn.getTarget().getInstrInfo();
959 BuildMI(*SI->second, SI->second->getFirstTerminator(), DebugLoc(),
960 TII->get(TargetOpcode::COPY), I->first).addReg(SI->first);
964 LiveInterval& Int = LI.getOrCreateInterval(I->first);
966 LI.getInstructionIndex(--SI->second->getFirstTerminator());
967 if (Int.liveAt(instrIdx.getDefIndex()))
968 Int.removeRange(instrIdx.getDefIndex(),
969 LI.getMBBEndIdx(SI->second).getNextSlot(), true);
971 LiveRange R = LI.addLiveRangeToEndOfBlock(I->first,
972 --SI->second->getFirstTerminator());
973 R.valno->setCopy(--SI->second->getFirstTerminator());
974 R.valno->def = instrIdx.getDefIndex();
976 DEBUG(dbgs() << "Renaming failed: " << SI->first << " -> "
977 << I->first << "\n");
981 LiveInterval& Int = LI.getOrCreateInterval(I->first);
982 const LiveRange* LR =
983 Int.getLiveRangeContaining(LI.getMBBEndIdx(SI->second));
984 LR->valno->setHasPHIKill(true);
986 I->second.erase(SI->first);
990 std::vector<MachineInstr*> phis;
991 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
992 for (MachineBasicBlock::iterator BI = I->begin(), BE = I->end();
998 for (std::vector<MachineInstr*>::iterator I = phis.begin(), E = phis.end();
1000 MachineInstr* PInstr = *(I++);
1002 // If this is a dead PHI node, then remove it from LiveIntervals.
1003 unsigned DestReg = PInstr->getOperand(0).getReg();
1004 LiveInterval& PI = LI.getInterval(DestReg);
1005 if (PInstr->registerDefIsDead(DestReg)) {
1006 if (PI.containsOneValue()) {
1007 LI.removeInterval(DestReg);
1009 SlotIndex idx = LI.getInstructionIndex(PInstr).getDefIndex();
1010 PI.removeRange(*PI.getLiveRangeContaining(idx), true);
1013 // Trim live intervals of input registers. They are no longer live into
1014 // this block if they died after the PHI. If they lived after it, don't
1015 // trim them because they might have other legitimate uses.
1016 for (unsigned i = 1; i < PInstr->getNumOperands(); i += 2) {
1017 unsigned reg = PInstr->getOperand(i).getReg();
1019 MachineBasicBlock* MBB = PInstr->getOperand(i+1).getMBB();
1020 LiveInterval& InputI = LI.getInterval(reg);
1021 if (MBB != PInstr->getParent() &&
1022 InputI.liveAt(LI.getMBBStartIdx(PInstr->getParent())) &&
1023 InputI.expiredAt(LI.getInstructionIndex(PInstr).getNextIndex()))
1024 InputI.removeRange(LI.getMBBStartIdx(PInstr->getParent()),
1025 LI.getInstructionIndex(PInstr),
1029 // If the PHI is not dead, then the valno defined by the PHI
1030 // now has an unknown def.
1031 SlotIndex idx = LI.getInstructionIndex(PInstr).getDefIndex();
1032 const LiveRange* PLR = PI.getLiveRangeContaining(idx);
1033 PLR->valno->setIsPHIDef(true);
1034 LiveRange R (LI.getMBBStartIdx(PInstr->getParent()),
1035 PLR->start, PLR->valno);
1039 LI.RemoveMachineInstrFromMaps(PInstr);
1040 PInstr->eraseFromParent();