1
//===- StrongPhiElimination.cpp - Eliminate PHI nodes by inserting copies -===//
3
// The LLVM Compiler Infrastructure
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
8
//===----------------------------------------------------------------------===//
10
// This pass eliminates machine instruction PHI nodes by inserting copy
11
// instructions, using an intelligent copy-folding technique based on
12
// dominator information. This is technique is derived from:
14
// Budimlic, et al. Fast copy coalescing and live-range identification.
15
// In Proceedings of the ACM SIGPLAN 2002 Conference on Programming Language
16
// Design and Implementation (Berlin, Germany, June 17 - 19, 2002).
17
// PLDI '02. ACM, New York, NY, 25-32.
18
// DOI= http://doi.acm.org/10.1145/512529.512534
20
//===----------------------------------------------------------------------===//
22
#define DEBUG_TYPE "strongphielim"
23
#include "llvm/CodeGen/Passes.h"
24
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
25
#include "llvm/CodeGen/MachineDominators.h"
26
#include "llvm/CodeGen/MachineFunctionPass.h"
27
#include "llvm/CodeGen/MachineInstr.h"
28
#include "llvm/CodeGen/MachineLoopInfo.h"
29
#include "llvm/CodeGen/MachineRegisterInfo.h"
30
#include "llvm/CodeGen/RegisterCoalescer.h"
31
#include "llvm/Target/TargetInstrInfo.h"
32
#include "llvm/Target/TargetMachine.h"
33
#include "llvm/ADT/DepthFirstIterator.h"
34
#include "llvm/ADT/Statistic.h"
35
#include "llvm/Support/Debug.h"
39
struct StrongPHIElimination : public MachineFunctionPass {
40
static char ID; // Pass identification, replacement for typeid
41
StrongPHIElimination() : MachineFunctionPass(&ID) {}
43
// Waiting stores, for each MBB, the set of copies that need to
44
// be inserted into that MBB
45
DenseMap<MachineBasicBlock*,
46
std::multimap<unsigned, unsigned> > Waiting;
48
// Stacks holds the renaming stack for each register
49
std::map<unsigned, std::vector<unsigned> > Stacks;
51
// Registers in UsedByAnother are PHI nodes that are themselves
52
// used as operands to another PHI node
53
std::set<unsigned> UsedByAnother;
55
// RenameSets are the is a map from a PHI-defined register
56
// to the input registers to be coalesced along with the
57
// predecessor block for those input registers.
58
std::map<unsigned, std::map<unsigned, MachineBasicBlock*> > RenameSets;
60
// PhiValueNumber holds the ID numbers of the VNs for each phi that we're
61
// eliminating, indexed by the register defined by that phi.
62
std::map<unsigned, unsigned> PhiValueNumber;
64
// Store the DFS-in number of each block
65
DenseMap<MachineBasicBlock*, unsigned> preorder;
67
// Store the DFS-out number of each block
68
DenseMap<MachineBasicBlock*, unsigned> maxpreorder;
70
bool runOnMachineFunction(MachineFunction &Fn);
72
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74
AU.addRequired<MachineDominatorTree>();
75
AU.addRequired<SlotIndexes>();
76
AU.addPreserved<SlotIndexes>();
77
AU.addRequired<LiveIntervals>();
79
// TODO: Actually make this true.
80
AU.addPreserved<LiveIntervals>();
81
AU.addPreserved<RegisterCoalescer>();
82
MachineFunctionPass::getAnalysisUsage(AU);
85
virtual void releaseMemory() {
91
UsedByAnother.clear();
97
/// DomForestNode - Represents a node in the "dominator forest". This is
98
/// a forest in which the nodes represent registers and the edges
99
/// represent a dominance relation in the block defining those registers.
100
struct DomForestNode {
102
// Store references to our children
103
std::vector<DomForestNode*> children;
104
// The register we represent
107
// Add another node as our child
108
void addChild(DomForestNode* DFN) { children.push_back(DFN); }
111
typedef std::vector<DomForestNode*>::iterator iterator;
113
// Create a DomForestNode by providing the register it represents, and
114
// the node to be its parent. The virtual root node has register 0
115
// and a null parent.
116
DomForestNode(unsigned r, DomForestNode* parent) : reg(r) {
118
parent->addChild(this);
122
for (iterator I = begin(), E = end(); I != E; ++I)
126
/// getReg - Return the regiser that this node represents
127
inline unsigned getReg() { return reg; }
129
// Provide iterator access to our children
130
inline DomForestNode::iterator begin() { return children.begin(); }
131
inline DomForestNode::iterator end() { return children.end(); }
134
void computeDFS(MachineFunction& MF);
135
void processBlock(MachineBasicBlock* MBB);
137
std::vector<DomForestNode*> computeDomForest(
138
std::map<unsigned, MachineBasicBlock*>& instrs,
139
MachineRegisterInfo& MRI);
140
void processPHIUnion(MachineInstr* Inst,
141
std::map<unsigned, MachineBasicBlock*>& PHIUnion,
142
std::vector<StrongPHIElimination::DomForestNode*>& DF,
143
std::vector<std::pair<unsigned, unsigned> >& locals);
144
void ScheduleCopies(MachineBasicBlock* MBB, std::set<unsigned>& pushed);
145
void InsertCopies(MachineDomTreeNode* MBB,
146
SmallPtrSet<MachineBasicBlock*, 16>& v);
147
bool mergeLiveIntervals(unsigned primary, unsigned secondary);
151
char StrongPHIElimination::ID = 0;
152
static RegisterPass<StrongPHIElimination>
153
X("strong-phi-node-elimination",
154
"Eliminate PHI nodes for register allocation, intelligently");
156
const PassInfo *const llvm::StrongPHIEliminationID = &X;
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
TII->copyRegToReg(*PI->getParent(), PI, t,
699
curr.second, RC, RC);
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
TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), curr.second,
716
map[curr.first], RC, RC);
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
TII->copyRegToReg(*MBB, MBB->getFirstTerminator(), t,
765
curr.second, RC, RC);
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
if (I->getOperand(i).isKill())
834
FirstVN->addKill(LI.getInstructionIndex(I).getUseIndex());
836
LiveRange LR (LI.getMBBStartIdx(I->getParent()),
837
LI.getInstructionIndex(I).getUseIndex().getNextSlot(),
844
// Schedule the copies for this block
845
ScheduleCopies(MBB, pushed);
847
// Recur down the dominator tree.
848
for (MachineDomTreeNode::iterator I = MDTN->begin(),
849
E = MDTN->end(); I != E; ++I)
850
if (!visited.count((*I)->getBlock()))
851
InsertCopies(*I, visited);
853
// As we exit this block, pop the names we pushed while processing it
854
for (std::set<unsigned>::iterator I = pushed.begin(),
855
E = pushed.end(); I != E; ++I)
856
Stacks[*I].pop_back();
859
bool StrongPHIElimination::mergeLiveIntervals(unsigned primary,
860
unsigned secondary) {
862
LiveIntervals& LI = getAnalysis<LiveIntervals>();
863
LiveInterval& LHS = LI.getOrCreateInterval(primary);
864
LiveInterval& RHS = LI.getOrCreateInterval(secondary);
868
DenseMap<VNInfo*, VNInfo*> VNMap;
869
for (LiveInterval::iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
872
SlotIndex Start = R.start;
873
SlotIndex End = R.end;
874
if (LHS.getLiveRangeContaining(Start))
877
if (LHS.getLiveRangeContaining(End))
880
LiveInterval::iterator RI = std::upper_bound(LHS.begin(), LHS.end(), R);
881
if (RI != LHS.end() && RI->start < End)
885
for (LiveInterval::iterator I = RHS.begin(), E = RHS.end(); I != E; ++I) {
887
VNInfo* OldVN = R.valno;
888
VNInfo*& NewVN = VNMap[OldVN];
890
NewVN = LHS.createValueCopy(OldVN, LI.getVNInfoAllocator());
893
LiveRange LR (R.start, R.end, NewVN);
897
LI.removeInterval(RHS.reg);
902
bool StrongPHIElimination::runOnMachineFunction(MachineFunction &Fn) {
903
LiveIntervals& LI = getAnalysis<LiveIntervals>();
905
// Compute DFS numbers of each block
908
// Determine which phi node operands need copies
909
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
910
if (!I->empty() && I->begin()->isPHI())
913
// Break interferences where two different phis want to coalesce
914
// in the same register.
915
std::set<unsigned> seen;
916
typedef std::map<unsigned, std::map<unsigned, MachineBasicBlock*> >
918
for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
920
for (std::map<unsigned, MachineBasicBlock*>::iterator
921
OI = I->second.begin(), OE = I->second.end(); OI != OE; ) {
922
if (!seen.count(OI->first)) {
923
seen.insert(OI->first);
926
Waiting[OI->second].insert(std::make_pair(OI->first, I->first));
927
unsigned reg = OI->first;
929
I->second.erase(reg);
930
DEBUG(dbgs() << "Removing Renaming: " << reg << " -> " << I->first
937
// FIXME: This process should probably preserve LiveIntervals
938
SmallPtrSet<MachineBasicBlock*, 16> visited;
939
MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
940
InsertCopies(MDT.getRootNode(), visited);
943
for (RenameSetType::iterator I = RenameSets.begin(), E = RenameSets.end();
945
while (I->second.size()) {
946
std::map<unsigned, MachineBasicBlock*>::iterator SI = I->second.begin();
948
DEBUG(dbgs() << "Renaming: " << SI->first << " -> " << I->first << "\n");
950
if (SI->first != I->first) {
951
if (mergeLiveIntervals(I->first, SI->first)) {
952
Fn.getRegInfo().replaceRegWith(SI->first, I->first);
954
if (RenameSets.count(SI->first)) {
955
I->second.insert(RenameSets[SI->first].begin(),
956
RenameSets[SI->first].end());
957
RenameSets.erase(SI->first);
960
// Insert a last-minute copy if a conflict was detected.
961
const TargetInstrInfo *TII = Fn.getTarget().getInstrInfo();
962
const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(I->first);
963
TII->copyRegToReg(*SI->second, SI->second->getFirstTerminator(),
964
I->first, SI->first, RC, RC);
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();