blob: 00c820e3df923a0462c7b04b0c0c7aec049d0580 [file] [log] [blame]
David Greene25133302007-06-08 17:18:56 +00001//===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a simple register coalescing pass that attempts to
11// aggressively coalesce every register copy that it can.
12//
13//===----------------------------------------------------------------------===//
14
Evan Cheng3b1f55e2007-07-31 22:37:44 +000015#define DEBUG_TYPE "regcoalescing"
Evan Chenga461c4d2007-11-05 17:41:38 +000016#include "SimpleRegisterCoalescing.h"
David Greene25133302007-06-08 17:18:56 +000017#include "VirtRegMap.h"
Evan Chenga461c4d2007-11-05 17:41:38 +000018#include "llvm/CodeGen/LiveIntervalAnalysis.h"
David Greene25133302007-06-08 17:18:56 +000019#include "llvm/Value.h"
20#include "llvm/Analysis/LoopInfo.h"
21#include "llvm/CodeGen/LiveVariables.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineInstr.h"
24#include "llvm/CodeGen/Passes.h"
25#include "llvm/CodeGen/SSARegMap.h"
David Greene2c17c4d2007-09-06 16:18:45 +000026#include "llvm/CodeGen/RegisterCoalescer.h"
David Greene25133302007-06-08 17:18:56 +000027#include "llvm/Target/MRegisterInfo.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetMachine.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/ADT/SmallSet.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/STLExtras.h"
35#include <algorithm>
36#include <cmath>
37using namespace llvm;
38
39STATISTIC(numJoins , "Number of interval joins performed");
40STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
41STATISTIC(numAborts , "Number of times interval joining aborted");
42
43char SimpleRegisterCoalescing::ID = 0;
44namespace {
45 static cl::opt<bool>
46 EnableJoining("join-liveintervals",
Gabor Greife510b3a2007-07-09 12:00:59 +000047 cl::desc("Coalesce copies (default=true)"),
David Greene25133302007-06-08 17:18:56 +000048 cl::init(true));
49
Evan Cheng8fc9a102007-11-06 08:52:21 +000050 static cl::opt<bool>
51 NewHeuristic("new-coalescer-heuristic",
52 cl::desc("Use new coalescer heuristic"),
53 cl::init(false));
54
David Greene25133302007-06-08 17:18:56 +000055 RegisterPass<SimpleRegisterCoalescing>
Chris Lattnere76fad22007-08-05 18:45:33 +000056 X("simple-register-coalescing", "Simple Register Coalescing");
David Greene2c17c4d2007-09-06 16:18:45 +000057
58 // Declare that we implement the RegisterCoalescer interface
59 RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
David Greene25133302007-06-08 17:18:56 +000060}
61
62const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
63
64void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
David Greene25133302007-06-08 17:18:56 +000065 AU.addPreserved<LiveIntervals>();
66 AU.addPreservedID(PHIEliminationID);
67 AU.addPreservedID(TwoAddressInstructionPassID);
68 AU.addRequired<LiveVariables>();
69 AU.addRequired<LiveIntervals>();
70 AU.addRequired<LoopInfo>();
71 MachineFunctionPass::getAnalysisUsage(AU);
72}
73
Gabor Greife510b3a2007-07-09 12:00:59 +000074/// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
David Greene25133302007-06-08 17:18:56 +000075/// being the source and IntB being the dest, thus this defines a value number
76/// in IntB. If the source value number (in IntA) is defined by a copy from B,
77/// see if we can merge these two pieces of B into a single value number,
78/// eliminating a copy. For example:
79///
80/// A3 = B0
81/// ...
82/// B1 = A3 <- this copy
83///
84/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
85/// value number to be replaced with B0 (which simplifies the B liveinterval).
86///
87/// This returns true if an interval was modified.
88///
89bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
90 MachineInstr *CopyMI) {
91 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
92
93 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
94 // the example above.
95 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +000096 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +000097
98 // Get the location that B is defined at. Two options: either this value has
99 // an unknown definition point or it is defined at CopyIdx. If unknown, we
100 // can't process it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000101 if (!BValNo->reg) return false;
102 assert(BValNo->def == CopyIdx &&
David Greene25133302007-06-08 17:18:56 +0000103 "Copy doesn't define the value?");
104
105 // AValNo is the value number in A that defines the copy, A0 in the example.
106 LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000107 VNInfo *AValNo = AValLR->valno;
David Greene25133302007-06-08 17:18:56 +0000108
109 // If AValNo is defined as a copy from IntB, we can potentially process this.
110
111 // Get the instruction that defines this value number.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000112 unsigned SrcReg = AValNo->reg;
David Greene25133302007-06-08 17:18:56 +0000113 if (!SrcReg) return false; // Not defined by a copy.
114
115 // If the value number is not defined by a copy instruction, ignore it.
116
117 // If the source register comes from an interval other than IntB, we can't
118 // handle this.
119 if (rep(SrcReg) != IntB.reg) return false;
120
121 // Get the LiveRange in IntB that this value number starts with.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000122 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
David Greene25133302007-06-08 17:18:56 +0000123
124 // Make sure that the end of the live range is inside the same block as
125 // CopyMI.
126 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
127 if (!ValLREndInst ||
128 ValLREndInst->getParent() != CopyMI->getParent()) return false;
129
130 // Okay, we now know that ValLR ends in the same block that the CopyMI
131 // live-range starts. If there are no intervening live ranges between them in
132 // IntB, we can merge them.
133 if (ValLR+1 != BLR) return false;
Evan Chengdc5294f2007-08-14 23:19:28 +0000134
135 // If a live interval is a physical register, conservatively check if any
136 // of its sub-registers is overlapping the live interval of the virtual
137 // register. If so, do not coalesce.
138 if (MRegisterInfo::isPhysicalRegister(IntB.reg) &&
139 *mri_->getSubRegisters(IntB.reg)) {
140 for (const unsigned* SR = mri_->getSubRegisters(IntB.reg); *SR; ++SR)
141 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
142 DOUT << "Interfere with sub-register ";
143 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
144 return false;
145 }
146 }
David Greene25133302007-06-08 17:18:56 +0000147
148 DOUT << "\nExtending: "; IntB.print(DOUT, mri_);
149
Evan Chenga8d94f12007-08-07 23:49:57 +0000150 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
David Greene25133302007-06-08 17:18:56 +0000151 // We are about to delete CopyMI, so need to remove it as the 'instruction
Evan Chenga8d94f12007-08-07 23:49:57 +0000152 // that defines this value #'. Update the the valnum with the new defining
153 // instruction #.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000154 BValNo->def = FillerStart;
155 BValNo->reg = 0;
David Greene25133302007-06-08 17:18:56 +0000156
157 // Okay, we can merge them. We need to insert a new liverange:
158 // [ValLR.end, BLR.begin) of either value number, then we merge the
159 // two value numbers.
David Greene25133302007-06-08 17:18:56 +0000160 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
161
162 // If the IntB live range is assigned to a physical register, and if that
163 // physreg has aliases,
164 if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
165 // Update the liveintervals of sub-registers.
166 for (const unsigned *AS = mri_->getSubRegisters(IntB.reg); *AS; ++AS) {
167 LiveInterval &AliasLI = li_->getInterval(*AS);
168 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
Evan Chengf3bb2e62007-09-05 21:46:51 +0000169 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
David Greene25133302007-06-08 17:18:56 +0000170 }
171 }
172
173 // Okay, merge "B1" into the same value number as "B0".
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000174 if (BValNo != ValLR->valno)
175 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
David Greene25133302007-06-08 17:18:56 +0000176 DOUT << " result = "; IntB.print(DOUT, mri_);
177 DOUT << "\n";
178
179 // If the source instruction was killing the source register before the
180 // merge, unset the isKill marker given the live range has been extended.
181 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
182 if (UIdx != -1)
183 ValLREndInst->getOperand(UIdx).unsetIsKill();
184
David Greene25133302007-06-08 17:18:56 +0000185 ++numPeep;
186 return true;
187}
188
Evan Cheng4ae31a52007-10-18 07:49:59 +0000189/// AddSubRegIdxPairs - Recursively mark all the registers represented by the
190/// specified register as sub-registers. The recursion level is expected to be
191/// shallow.
192void SimpleRegisterCoalescing::AddSubRegIdxPairs(unsigned Reg, unsigned SubIdx) {
193 std::vector<unsigned> &JoinedRegs = r2rRevMap_[Reg];
194 for (unsigned i = 0, e = JoinedRegs.size(); i != e; ++i) {
195 SubRegIdxes.push_back(std::make_pair(JoinedRegs[i], SubIdx));
196 AddSubRegIdxPairs(JoinedRegs[i], SubIdx);
197 }
198}
199
Evan Cheng8fc9a102007-11-06 08:52:21 +0000200/// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
201///
202bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
203 unsigned DstReg) {
204 MachineBasicBlock *MBB = CopyMI->getParent();
205 const BasicBlock *BB = MBB->getBasicBlock();
206 const Loop *L = loopInfo->getLoopFor(BB);
207 if (!L)
208 return false;
209 if (BB != L->getLoopLatch())
210 return false;
211
212 DstReg = rep(DstReg);
213 LiveInterval &LI = li_->getInterval(DstReg);
214 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
215 LiveInterval::const_iterator DstLR =
216 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
217 if (DstLR == LI.end())
218 return false;
219 unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM-1;
220 if (DstLR->valno->kills.size() == 1 && DstLR->valno->kills[0] == KillIdx)
221 return true;
222 return false;
223}
224
David Greene25133302007-06-08 17:18:56 +0000225/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
226/// which are the src/dst of the copy instruction CopyMI. This returns true
Evan Cheng0547bab2007-11-01 06:22:48 +0000227/// if the copy was successfully coalesced away. If it is not currently
228/// possible to coalesce this interval, but it may be possible if other
229/// things get coalesced, then it returns true by reference in 'Again'.
Evan Cheng8fc9a102007-11-06 08:52:21 +0000230bool SimpleRegisterCoalescing::JoinCopy(CopyRec TheCopy, bool &Again) {
231 MachineInstr *CopyMI = TheCopy.MI;
232
233 Again = false;
234 if (JoinedCopies.count(CopyMI))
235 return false; // Already done.
236
David Greene25133302007-06-08 17:18:56 +0000237 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
238
239 // Get representative registers.
Evan Cheng8fc9a102007-11-06 08:52:21 +0000240 unsigned SrcReg = TheCopy.SrcReg;
241 unsigned DstReg = TheCopy.DstReg;
David Greene25133302007-06-08 17:18:56 +0000242 unsigned repSrcReg = rep(SrcReg);
243 unsigned repDstReg = rep(DstReg);
244
245 // If they are already joined we continue.
246 if (repSrcReg == repDstReg) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000247 DOUT << "\tCopy already coalesced.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000248 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000249 }
250
251 bool SrcIsPhys = MRegisterInfo::isPhysicalRegister(repSrcReg);
252 bool DstIsPhys = MRegisterInfo::isPhysicalRegister(repDstReg);
David Greene25133302007-06-08 17:18:56 +0000253
254 // If they are both physical registers, we cannot join them.
255 if (SrcIsPhys && DstIsPhys) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000256 DOUT << "\tCan not coalesce physregs.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000257 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000258 }
259
260 // We only join virtual registers with allocatable physical registers.
261 if (SrcIsPhys && !allocatableRegs_[repSrcReg]) {
262 DOUT << "\tSrc reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000263 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000264 }
265 if (DstIsPhys && !allocatableRegs_[repDstReg]) {
266 DOUT << "\tDst reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000267 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000268 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000269
270 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
271 unsigned RealDstReg = 0;
272 if (isExtSubReg) {
273 unsigned SubIdx = CopyMI->getOperand(2).getImm();
274 if (SrcIsPhys)
275 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
276 // coalesced with AX.
277 repSrcReg = mri_->getSubReg(repSrcReg, SubIdx);
278 else if (DstIsPhys) {
279 // If this is a extract_subreg where dst is a physical register, e.g.
280 // cl = EXTRACT_SUBREG reg1024, 1
281 // then create and update the actual physical register allocated to RHS.
Evan Cheng95f0ab62007-10-17 05:29:37 +0000282 const TargetRegisterClass *RC=mf_->getSSARegMap()->getRegClass(repSrcReg);
Evan Cheng32dfbea2007-10-12 08:50:34 +0000283 for (const unsigned *SRs = mri_->getSuperRegisters(repDstReg);
284 unsigned SR = *SRs; ++SRs) {
285 if (repDstReg == mri_->getSubReg(SR, SubIdx) &&
286 RC->contains(SR)) {
287 RealDstReg = SR;
288 break;
289 }
290 }
291 assert(RealDstReg && "Invalid extra_subreg instruction!");
292
293 // For this type of EXTRACT_SUBREG, conservatively
294 // check if the live interval of the source register interfere with the
295 // actual super physical register we are trying to coalesce with.
296 LiveInterval &RHS = li_->getInterval(repSrcReg);
297 if (li_->hasInterval(RealDstReg) &&
298 RHS.overlaps(li_->getInterval(RealDstReg))) {
299 DOUT << "Interfere with register ";
300 DEBUG(li_->getInterval(RealDstReg).print(DOUT, mri_));
Evan Cheng0547bab2007-11-01 06:22:48 +0000301 return false; // Not coalescable
Evan Cheng32dfbea2007-10-12 08:50:34 +0000302 }
303 for (const unsigned* SR = mri_->getSubRegisters(RealDstReg); *SR; ++SR)
304 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
305 DOUT << "Interfere with sub-register ";
306 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
Evan Cheng0547bab2007-11-01 06:22:48 +0000307 return false; // Not coalescable
Evan Cheng32dfbea2007-10-12 08:50:34 +0000308 }
Evan Cheng0547bab2007-11-01 06:22:48 +0000309 } else {
310 unsigned SrcSize= li_->getInterval(repSrcReg).getSize() / InstrSlots::NUM;
311 unsigned DstSize= li_->getInterval(repDstReg).getSize() / InstrSlots::NUM;
312 const TargetRegisterClass *RC=mf_->getSSARegMap()->getRegClass(repDstReg);
313 unsigned Threshold = allocatableRCRegs_[RC].count();
Evan Cheng52c7ff72007-10-12 09:15:53 +0000314 // Be conservative. If both sides are virtual registers, do not coalesce
Evan Cheng0547bab2007-11-01 06:22:48 +0000315 // if this will cause a high use density interval to target a smaller set
316 // of registers.
317 if (DstSize > Threshold || SrcSize > Threshold) {
318 LiveVariables::VarInfo &svi = lv_->getVarInfo(repSrcReg);
319 LiveVariables::VarInfo &dvi = lv_->getVarInfo(repDstReg);
320 if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
321 Again = true; // May be possible to coalesce later.
322 return false;
323 }
324 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000325 }
326 } else if (differingRegisterClasses(repSrcReg, repDstReg)) {
327 // If they are not of the same register class, we cannot join them.
David Greene25133302007-06-08 17:18:56 +0000328 DOUT << "\tSrc/Dest are different register classes.\n";
Evan Cheng32dfbea2007-10-12 08:50:34 +0000329 // Allow the coalescer to try again in case either side gets coalesced to
330 // a physical register that's compatible with the other side. e.g.
331 // r1024 = MOV32to32_ r1025
332 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
Evan Cheng0547bab2007-11-01 06:22:48 +0000333 Again = true; // May be possible to coalesce later.
Evan Cheng32dfbea2007-10-12 08:50:34 +0000334 return false;
David Greene25133302007-06-08 17:18:56 +0000335 }
336
337 LiveInterval &SrcInt = li_->getInterval(repSrcReg);
338 LiveInterval &DstInt = li_->getInterval(repDstReg);
339 assert(SrcInt.reg == repSrcReg && DstInt.reg == repDstReg &&
340 "Register mapping is horribly broken!");
341
342 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, mri_);
343 DOUT << " and "; DstInt.print(DOUT, mri_);
344 DOUT << ": ";
345
346 // Check if it is necessary to propagate "isDead" property before intervals
347 // are joined.
348 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
349 bool isDead = mopd->isDead();
350 bool isShorten = false;
351 unsigned SrcStart = 0, RemoveStart = 0;
352 unsigned SrcEnd = 0, RemoveEnd = 0;
353 if (isDead) {
354 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
355 LiveInterval::iterator SrcLR =
356 SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
357 RemoveStart = SrcStart = SrcLR->start;
358 RemoveEnd = SrcEnd = SrcLR->end;
359 // The instruction which defines the src is only truly dead if there are
360 // no intermediate uses and there isn't a use beyond the copy.
361 // FIXME: find the last use, mark is kill and shorten the live range.
362 if (SrcEnd > li_->getDefIndex(CopyIdx)) {
363 isDead = false;
364 } else {
365 MachineOperand *MOU;
366 MachineInstr *LastUse= lastRegisterUse(SrcStart, CopyIdx, repSrcReg, MOU);
367 if (LastUse) {
368 // Shorten the liveinterval to the end of last use.
369 MOU->setIsKill();
370 isDead = false;
371 isShorten = true;
372 RemoveStart = li_->getDefIndex(li_->getInstructionIndex(LastUse));
373 RemoveEnd = SrcEnd;
374 } else {
375 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
376 if (SrcMI) {
377 MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
378 if (mops)
379 // A dead def should have a single cycle interval.
380 ++RemoveStart;
381 }
382 }
383 }
384 }
385
386 // We need to be careful about coalescing a source physical register with a
387 // virtual register. Once the coalescing is done, it cannot be broken and
388 // these are not spillable! If the destination interval uses are far away,
389 // think twice about coalescing them!
Evan Cheng32dfbea2007-10-12 08:50:34 +0000390 if (!mopd->isDead() && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
David Greene25133302007-06-08 17:18:56 +0000391 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
392 unsigned JoinVReg = SrcIsPhys ? repDstReg : repSrcReg;
393 unsigned JoinPReg = SrcIsPhys ? repSrcReg : repDstReg;
394 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(JoinVReg);
395 unsigned Threshold = allocatableRCRegs_[RC].count();
Evan Cheng8fc9a102007-11-06 08:52:21 +0000396 if (TheCopy.isBackEdge)
397 Threshold *= 2; // Favors back edge copies.
David Greene25133302007-06-08 17:18:56 +0000398
Evan Cheng32dfbea2007-10-12 08:50:34 +0000399 // If the virtual register live interval is long but it has low use desity,
David Greene25133302007-06-08 17:18:56 +0000400 // do not join them, instead mark the physical register as its allocation
401 // preference.
402 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
403 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
404 if (Length > Threshold &&
405 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
406 JoinVInt.preference = JoinPReg;
407 ++numAborts;
408 DOUT << "\tMay tie down a physical register, abort!\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000409 Again = true; // May be possible to coalesce later.
David Greene25133302007-06-08 17:18:56 +0000410 return false;
411 }
412 }
413
414 // Okay, attempt to join these two intervals. On failure, this returns false.
415 // Otherwise, if one of the intervals being joined is a physreg, this method
416 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
417 // been modified, so we can use this information below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000418 bool Swapped = false;
419 if (JoinIntervals(DstInt, SrcInt, Swapped)) {
David Greene25133302007-06-08 17:18:56 +0000420 if (isDead) {
421 // Result of the copy is dead. Propagate this property.
422 if (SrcStart == 0) {
423 assert(MRegisterInfo::isPhysicalRegister(repSrcReg) &&
424 "Live-in must be a physical register!");
425 // Live-in to the function but dead. Remove it from entry live-in set.
426 // JoinIntervals may end up swapping the two intervals.
427 mf_->begin()->removeLiveIn(repSrcReg);
428 } else {
429 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
430 if (SrcMI) {
431 MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
432 if (mops)
433 mops->setIsDead();
434 }
435 }
436 }
437
438 if (isShorten || isDead) {
Evan Chengccb36a42007-08-12 01:26:19 +0000439 // Shorten the destination live interval.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000440 if (Swapped)
441 SrcInt.removeRange(RemoveStart, RemoveEnd);
David Greene25133302007-06-08 17:18:56 +0000442 }
443 } else {
Gabor Greife510b3a2007-07-09 12:00:59 +0000444 // Coalescing failed.
David Greene25133302007-06-08 17:18:56 +0000445
446 // If we can eliminate the copy without merging the live ranges, do so now.
Evan Cheng8fc9a102007-11-06 08:52:21 +0000447 if (!isExtSubReg && AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI)) {
448 JoinedCopies.insert(CopyMI);
David Greene25133302007-06-08 17:18:56 +0000449 return true;
Evan Cheng8fc9a102007-11-06 08:52:21 +0000450 }
David Greene25133302007-06-08 17:18:56 +0000451
452 // Otherwise, we are unable to join the intervals.
453 DOUT << "Interference!\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000454 Again = true; // May be possible to coalesce later.
David Greene25133302007-06-08 17:18:56 +0000455 return false;
456 }
457
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000458 LiveInterval *ResSrcInt = &SrcInt;
459 LiveInterval *ResDstInt = &DstInt;
460 if (Swapped) {
David Greene25133302007-06-08 17:18:56 +0000461 std::swap(repSrcReg, repDstReg);
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000462 std::swap(ResSrcInt, ResDstInt);
463 }
David Greene25133302007-06-08 17:18:56 +0000464 assert(MRegisterInfo::isVirtualRegister(repSrcReg) &&
465 "LiveInterval::join didn't work right!");
466
467 // If we're about to merge live ranges into a physical register live range,
468 // we have to update any aliased register's live ranges to indicate that they
469 // have clobbered values for this range.
470 if (MRegisterInfo::isPhysicalRegister(repDstReg)) {
471 // Unset unnecessary kills.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000472 if (!ResDstInt->containsOneValue()) {
473 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->begin(),
474 E = ResSrcInt->end(); I != E; ++I)
David Greene25133302007-06-08 17:18:56 +0000475 unsetRegisterKills(I->start, I->end, repDstReg);
476 }
477
Evan Cheng32dfbea2007-10-12 08:50:34 +0000478 // If this is a extract_subreg where dst is a physical register, e.g.
479 // cl = EXTRACT_SUBREG reg1024, 1
480 // then create and update the actual physical register allocated to RHS.
481 if (RealDstReg) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000482 LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
Evan Chengf5c73592007-10-15 18:33:50 +0000483 SmallSet<const VNInfo*, 4> CopiedValNos;
484 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
485 E = ResSrcInt->ranges.end(); I != E; ++I) {
486 LiveInterval::const_iterator DstLR =
487 ResDstInt->FindLiveRangeContaining(I->start);
488 assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
489 const VNInfo *DstValNo = DstLR->valno;
490 if (CopiedValNos.insert(DstValNo)) {
491 VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->reg,
492 li_->getVNInfoAllocator());
493 RealDstInt.addKills(ValNo, DstValNo->kills);
494 RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
495 }
Evan Cheng34729252007-10-14 10:08:34 +0000496 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000497 repDstReg = RealDstReg;
498 }
499
David Greene25133302007-06-08 17:18:56 +0000500 // Update the liveintervals of sub-registers.
501 for (const unsigned *AS = mri_->getSubRegisters(repDstReg); *AS; ++AS)
Evan Cheng32dfbea2007-10-12 08:50:34 +0000502 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
Evan Chengf3bb2e62007-09-05 21:46:51 +0000503 li_->getVNInfoAllocator());
David Greene25133302007-06-08 17:18:56 +0000504 } else {
505 // Merge use info if the destination is a virtual register.
506 LiveVariables::VarInfo& dVI = lv_->getVarInfo(repDstReg);
507 LiveVariables::VarInfo& sVI = lv_->getVarInfo(repSrcReg);
508 dVI.NumUses += sVI.NumUses;
509 }
510
David Greene25133302007-06-08 17:18:56 +0000511 // Remember these liveintervals have been joined.
512 JoinedLIs.set(repSrcReg - MRegisterInfo::FirstVirtualRegister);
513 if (MRegisterInfo::isVirtualRegister(repDstReg))
514 JoinedLIs.set(repDstReg - MRegisterInfo::FirstVirtualRegister);
515
Evan Cheng32dfbea2007-10-12 08:50:34 +0000516 if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
517 if (!Swapped) {
518 // Make sure we allocate the larger super-register.
519 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
520 std::swap(repSrcReg, repDstReg);
521 std::swap(ResSrcInt, ResDstInt);
522 }
Evan Cheng4ae31a52007-10-18 07:49:59 +0000523 unsigned SubIdx = CopyMI->getOperand(2).getImm();
524 SubRegIdxes.push_back(std::make_pair(repSrcReg, SubIdx));
525 AddSubRegIdxPairs(repSrcReg, SubIdx);
Evan Cheng32dfbea2007-10-12 08:50:34 +0000526 }
527
Evan Cheng8fc9a102007-11-06 08:52:21 +0000528 if (NewHeuristic) {
529 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
530 e = ResSrcInt->vni_end(); i != e; ++i) {
531 const VNInfo *vni = *i;
532 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
533 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
534 unsigned SrcReg, DstReg;
535 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg) &&
536 JoinedCopies.count(CopyMI) == 0) {
537 unsigned LoopDepth =
538 loopInfo->getLoopDepth(CopyMI->getParent()->getBasicBlock());
539 JoinQueue->push(CopyRec(CopyMI, SrcReg, DstReg, LoopDepth,
540 isBackEdgeCopy(CopyMI, DstReg)));
541 }
542 }
543 }
544 }
545
Evan Cheng32dfbea2007-10-12 08:50:34 +0000546 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, mri_);
547 DOUT << "\n";
548
Evan Cheng273288c2007-07-18 23:34:48 +0000549 // repSrcReg is guarateed to be the register whose live interval that is
550 // being merged.
David Greene25133302007-06-08 17:18:56 +0000551 li_->removeInterval(repSrcReg);
552 r2rMap_[repSrcReg] = repDstReg;
Evan Cheng4ae31a52007-10-18 07:49:59 +0000553 r2rRevMap_[repDstReg].push_back(repSrcReg);
David Greene25133302007-06-08 17:18:56 +0000554
555 // Finally, delete the copy instruction.
Evan Cheng8fc9a102007-11-06 08:52:21 +0000556 JoinedCopies.insert(CopyMI);
David Greene25133302007-06-08 17:18:56 +0000557 ++numPeep;
558 ++numJoins;
559 return true;
560}
561
562/// ComputeUltimateVN - Assuming we are going to join two live intervals,
563/// compute what the resultant value numbers for each value in the input two
564/// ranges will be. This is complicated by copies between the two which can
565/// and will commonly cause multiple value numbers to be merged into one.
566///
567/// VN is the value number that we're trying to resolve. InstDefiningValue
568/// keeps track of the new InstDefiningValue assignment for the result
569/// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
570/// whether a value in this or other is a copy from the opposite set.
571/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
572/// already been assigned.
573///
574/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
575/// contains the value number the copy is from.
576///
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000577static unsigned ComputeUltimateVN(VNInfo *VNI,
578 SmallVector<VNInfo*, 16> &NewVNInfo,
Evan Chengfadfb5b2007-08-31 21:23:06 +0000579 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
580 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
David Greene25133302007-06-08 17:18:56 +0000581 SmallVector<int, 16> &ThisValNoAssignments,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000582 SmallVector<int, 16> &OtherValNoAssignments) {
583 unsigned VN = VNI->id;
584
David Greene25133302007-06-08 17:18:56 +0000585 // If the VN has already been computed, just return it.
586 if (ThisValNoAssignments[VN] >= 0)
587 return ThisValNoAssignments[VN];
588// assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000589
David Greene25133302007-06-08 17:18:56 +0000590 // If this val is not a copy from the other val, then it must be a new value
591 // number in the destination.
Evan Chengfadfb5b2007-08-31 21:23:06 +0000592 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
Evan Chengc14b1442007-08-31 08:04:17 +0000593 if (I == ThisFromOther.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000594 NewVNInfo.push_back(VNI);
595 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +0000596 }
Evan Chengc14b1442007-08-31 08:04:17 +0000597 VNInfo *OtherValNo = I->second;
David Greene25133302007-06-08 17:18:56 +0000598
599 // Otherwise, this *is* a copy from the RHS. If the other side has already
600 // been computed, return it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000601 if (OtherValNoAssignments[OtherValNo->id] >= 0)
602 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
David Greene25133302007-06-08 17:18:56 +0000603
604 // Mark this value number as currently being computed, then ask what the
605 // ultimate value # of the other value is.
606 ThisValNoAssignments[VN] = -2;
607 unsigned UltimateVN =
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000608 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
609 OtherValNoAssignments, ThisValNoAssignments);
David Greene25133302007-06-08 17:18:56 +0000610 return ThisValNoAssignments[VN] = UltimateVN;
611}
612
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000613static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
David Greene25133302007-06-08 17:18:56 +0000614 return std::find(V.begin(), V.end(), Val) != V.end();
615}
616
617/// SimpleJoin - Attempt to joint the specified interval into this one. The
618/// caller of this method must guarantee that the RHS only contains a single
619/// value number and that the RHS is not defined by a copy from this
620/// interval. This returns false if the intervals are not joinable, or it
621/// joins them and returns true.
622bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
623 assert(RHS.containsOneValue());
624
625 // Some number (potentially more than one) value numbers in the current
626 // interval may be defined as copies from the RHS. Scan the overlapping
627 // portions of the LHS and RHS, keeping track of this and looking for
628 // overlapping live ranges that are NOT defined as copies. If these exist, we
Gabor Greife510b3a2007-07-09 12:00:59 +0000629 // cannot coalesce.
David Greene25133302007-06-08 17:18:56 +0000630
631 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
632 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
633
634 if (LHSIt->start < RHSIt->start) {
635 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
636 if (LHSIt != LHS.begin()) --LHSIt;
637 } else if (RHSIt->start < LHSIt->start) {
638 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
639 if (RHSIt != RHS.begin()) --RHSIt;
640 }
641
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000642 SmallVector<VNInfo*, 8> EliminatedLHSVals;
David Greene25133302007-06-08 17:18:56 +0000643
644 while (1) {
645 // Determine if these live intervals overlap.
646 bool Overlaps = false;
647 if (LHSIt->start <= RHSIt->start)
648 Overlaps = LHSIt->end > RHSIt->start;
649 else
650 Overlaps = RHSIt->end > LHSIt->start;
651
652 // If the live intervals overlap, there are two interesting cases: if the
653 // LHS interval is defined by a copy from the RHS, it's ok and we record
654 // that the LHS value # is the same as the RHS. If it's not, then we cannot
Gabor Greife510b3a2007-07-09 12:00:59 +0000655 // coalesce these live ranges and we bail out.
David Greene25133302007-06-08 17:18:56 +0000656 if (Overlaps) {
657 // If we haven't already recorded that this value # is safe, check it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000658 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +0000659 // Copy from the RHS?
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000660 unsigned SrcReg = LHSIt->valno->reg;
David Greene25133302007-06-08 17:18:56 +0000661 if (rep(SrcReg) != RHS.reg)
662 return false; // Nope, bail out.
663
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000664 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +0000665 }
666
667 // We know this entire LHS live range is okay, so skip it now.
668 if (++LHSIt == LHSEnd) break;
669 continue;
670 }
671
672 if (LHSIt->end < RHSIt->end) {
673 if (++LHSIt == LHSEnd) break;
674 } else {
675 // One interesting case to check here. It's possible that we have
676 // something like "X3 = Y" which defines a new value number in the LHS,
677 // and is the last use of this liverange of the RHS. In this case, we
Gabor Greife510b3a2007-07-09 12:00:59 +0000678 // want to notice this copy (so that it gets coalesced away) even though
David Greene25133302007-06-08 17:18:56 +0000679 // the live ranges don't actually overlap.
680 if (LHSIt->start == RHSIt->end) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000681 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +0000682 // We already know that this value number is going to be merged in
Gabor Greife510b3a2007-07-09 12:00:59 +0000683 // if coalescing succeeds. Just skip the liverange.
David Greene25133302007-06-08 17:18:56 +0000684 if (++LHSIt == LHSEnd) break;
685 } else {
686 // Otherwise, if this is a copy from the RHS, mark it as being merged
687 // in.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000688 if (rep(LHSIt->valno->reg) == RHS.reg) {
689 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +0000690
691 // We know this entire LHS live range is okay, so skip it now.
692 if (++LHSIt == LHSEnd) break;
693 }
694 }
695 }
696
697 if (++RHSIt == RHSEnd) break;
698 }
699 }
700
Gabor Greife510b3a2007-07-09 12:00:59 +0000701 // If we got here, we know that the coalescing will be successful and that
David Greene25133302007-06-08 17:18:56 +0000702 // the value numbers in EliminatedLHSVals will all be merged together. Since
703 // the most common case is that EliminatedLHSVals has a single number, we
704 // optimize for it: if there is more than one value, we merge them all into
705 // the lowest numbered one, then handle the interval as if we were merging
706 // with one value number.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000707 VNInfo *LHSValNo;
David Greene25133302007-06-08 17:18:56 +0000708 if (EliminatedLHSVals.size() > 1) {
709 // Loop through all the equal value numbers merging them into the smallest
710 // one.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000711 VNInfo *Smallest = EliminatedLHSVals[0];
David Greene25133302007-06-08 17:18:56 +0000712 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000713 if (EliminatedLHSVals[i]->id < Smallest->id) {
David Greene25133302007-06-08 17:18:56 +0000714 // Merge the current notion of the smallest into the smaller one.
715 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
716 Smallest = EliminatedLHSVals[i];
717 } else {
718 // Merge into the smallest.
719 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
720 }
721 }
722 LHSValNo = Smallest;
723 } else {
724 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
725 LHSValNo = EliminatedLHSVals[0];
726 }
727
728 // Okay, now that there is a single LHS value number that we're merging the
729 // RHS into, update the value number info for the LHS to indicate that the
730 // value number is defined where the RHS value number was.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000731 const VNInfo *VNI = RHS.getValNumInfo(0);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000732 LHSValNo->def = VNI->def;
733 LHSValNo->reg = VNI->reg;
David Greene25133302007-06-08 17:18:56 +0000734
735 // Okay, the final step is to loop over the RHS live intervals, adding them to
736 // the LHS.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000737 LHS.addKills(LHSValNo, VNI->kills);
Evan Cheng430a7b02007-08-14 01:56:58 +0000738 LHS.MergeRangesInAsValue(RHS, LHSValNo);
David Greene25133302007-06-08 17:18:56 +0000739 LHS.weight += RHS.weight;
740 if (RHS.preference && !LHS.preference)
741 LHS.preference = RHS.preference;
742
743 return true;
744}
745
746/// JoinIntervals - Attempt to join these two intervals. On failure, this
747/// returns false. Otherwise, if one of the intervals being joined is a
748/// physreg, this method always canonicalizes LHS to be it. The output
749/// "RHS" will not have been modified, so we can use this information
750/// below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000751bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
752 LiveInterval &RHS, bool &Swapped) {
David Greene25133302007-06-08 17:18:56 +0000753 // Compute the final value assignment, assuming that the live ranges can be
Gabor Greife510b3a2007-07-09 12:00:59 +0000754 // coalesced.
David Greene25133302007-06-08 17:18:56 +0000755 SmallVector<int, 16> LHSValNoAssignments;
756 SmallVector<int, 16> RHSValNoAssignments;
Evan Chengfadfb5b2007-08-31 21:23:06 +0000757 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
758 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000759 SmallVector<VNInfo*, 16> NewVNInfo;
David Greene25133302007-06-08 17:18:56 +0000760
761 // If a live interval is a physical register, conservatively check if any
762 // of its sub-registers is overlapping the live interval of the virtual
763 // register. If so, do not coalesce.
764 if (MRegisterInfo::isPhysicalRegister(LHS.reg) &&
765 *mri_->getSubRegisters(LHS.reg)) {
766 for (const unsigned* SR = mri_->getSubRegisters(LHS.reg); *SR; ++SR)
767 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
768 DOUT << "Interfere with sub-register ";
769 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
770 return false;
771 }
772 } else if (MRegisterInfo::isPhysicalRegister(RHS.reg) &&
773 *mri_->getSubRegisters(RHS.reg)) {
774 for (const unsigned* SR = mri_->getSubRegisters(RHS.reg); *SR; ++SR)
775 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
776 DOUT << "Interfere with sub-register ";
777 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
778 return false;
779 }
780 }
781
782 // Compute ultimate value numbers for the LHS and RHS values.
783 if (RHS.containsOneValue()) {
784 // Copies from a liveinterval with a single value are simple to handle and
785 // very common, handle the special case here. This is important, because
786 // often RHS is small and LHS is large (e.g. a physreg).
787
788 // Find out if the RHS is defined as a copy from some value in the LHS.
Evan Cheng4f8ff162007-08-11 00:59:19 +0000789 int RHSVal0DefinedFromLHS = -1;
David Greene25133302007-06-08 17:18:56 +0000790 int RHSValID = -1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000791 VNInfo *RHSValNoInfo = NULL;
Evan Chengf3bb2e62007-09-05 21:46:51 +0000792 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
Evan Chengc14b1442007-08-31 08:04:17 +0000793 unsigned RHSSrcReg = RHSValNoInfo0->reg;
David Greene25133302007-06-08 17:18:56 +0000794 if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
795 // If RHS is not defined as a copy from the LHS, we can use simpler and
Gabor Greife510b3a2007-07-09 12:00:59 +0000796 // faster checks to see if the live ranges are coalescable. This joiner
David Greene25133302007-06-08 17:18:56 +0000797 // can't swap the LHS/RHS intervals though.
798 if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
799 return SimpleJoin(LHS, RHS);
800 } else {
Evan Chengc14b1442007-08-31 08:04:17 +0000801 RHSValNoInfo = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +0000802 }
803 } else {
804 // It was defined as a copy from the LHS, find out what value # it is.
Evan Chengc14b1442007-08-31 08:04:17 +0000805 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000806 RHSValID = RHSValNoInfo->id;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000807 RHSVal0DefinedFromLHS = RHSValID;
David Greene25133302007-06-08 17:18:56 +0000808 }
809
810 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
811 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000812 NewVNInfo.resize(LHS.getNumValNums(), NULL);
David Greene25133302007-06-08 17:18:56 +0000813
814 // Okay, *all* of the values in LHS that are defined as a copy from RHS
815 // should now get updated.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000816 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
817 i != e; ++i) {
818 VNInfo *VNI = *i;
819 unsigned VN = VNI->id;
820 if (unsigned LHSSrcReg = VNI->reg) {
David Greene25133302007-06-08 17:18:56 +0000821 if (rep(LHSSrcReg) != RHS.reg) {
822 // If this is not a copy from the RHS, its value number will be
Gabor Greife510b3a2007-07-09 12:00:59 +0000823 // unmodified by the coalescing.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000824 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +0000825 LHSValNoAssignments[VN] = VN;
826 } else if (RHSValID == -1) {
827 // Otherwise, it is a copy from the RHS, and we don't already have a
828 // value# for it. Keep the current value number, but remember it.
829 LHSValNoAssignments[VN] = RHSValID = VN;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000830 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +0000831 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +0000832 } else {
833 // Otherwise, use the specified value #.
834 LHSValNoAssignments[VN] = RHSValID;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000835 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
836 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +0000837 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000838 }
David Greene25133302007-06-08 17:18:56 +0000839 }
840 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000841 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +0000842 LHSValNoAssignments[VN] = VN;
843 }
844 }
845
846 assert(RHSValID != -1 && "Didn't find value #?");
847 RHSValNoAssignments[0] = RHSValID;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000848 if (RHSVal0DefinedFromLHS != -1) {
Evan Cheng34301352007-09-01 02:03:17 +0000849 // This path doesn't go through ComputeUltimateVN so just set
850 // it to anything.
851 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000852 }
David Greene25133302007-06-08 17:18:56 +0000853 } else {
854 // Loop over the value numbers of the LHS, seeing if any are defined from
855 // the RHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000856 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
857 i != e; ++i) {
858 VNInfo *VNI = *i;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000859 unsigned ValSrcReg = VNI->reg;
Evan Cheng5031fd22007-11-05 06:46:45 +0000860 if (VNI->def == ~1U ||ValSrcReg == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +0000861 continue;
862
863 // DstReg is known to be a register in the LHS interval. If the src is
864 // from the RHS interval, we can use its value #.
865 if (rep(ValSrcReg) != RHS.reg)
866 continue;
867
868 // Figure out the value # from the RHS.
Evan Chengc14b1442007-08-31 08:04:17 +0000869 LHSValsDefinedFromRHS[VNI] = RHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +0000870 }
871
872 // Loop over the value numbers of the RHS, seeing if any are defined from
873 // the LHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000874 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
875 i != e; ++i) {
876 VNInfo *VNI = *i;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000877 unsigned ValSrcReg = VNI->reg;
Evan Cheng5031fd22007-11-05 06:46:45 +0000878 if (VNI->def == ~1U || ValSrcReg == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +0000879 continue;
880
881 // DstReg is known to be a register in the RHS interval. If the src is
882 // from the LHS interval, we can use its value #.
883 if (rep(ValSrcReg) != LHS.reg)
884 continue;
885
886 // Figure out the value # from the LHS.
Evan Chengc14b1442007-08-31 08:04:17 +0000887 RHSValsDefinedFromLHS[VNI]= LHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +0000888 }
889
890 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
891 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000892 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
David Greene25133302007-06-08 17:18:56 +0000893
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000894 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
895 i != e; ++i) {
896 VNInfo *VNI = *i;
897 unsigned VN = VNI->id;
898 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +0000899 continue;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000900 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +0000901 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000902 LHSValNoAssignments, RHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +0000903 }
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000904 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
905 i != e; ++i) {
906 VNInfo *VNI = *i;
907 unsigned VN = VNI->id;
908 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +0000909 continue;
910 // If this value number isn't a copy from the LHS, it's a new number.
Evan Chengc14b1442007-08-31 08:04:17 +0000911 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000912 NewVNInfo.push_back(VNI);
913 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +0000914 continue;
915 }
916
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000917 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +0000918 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000919 RHSValNoAssignments, LHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +0000920 }
921 }
922
923 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
Gabor Greife510b3a2007-07-09 12:00:59 +0000924 // interval lists to see if these intervals are coalescable.
David Greene25133302007-06-08 17:18:56 +0000925 LiveInterval::const_iterator I = LHS.begin();
926 LiveInterval::const_iterator IE = LHS.end();
927 LiveInterval::const_iterator J = RHS.begin();
928 LiveInterval::const_iterator JE = RHS.end();
929
930 // Skip ahead until the first place of potential sharing.
931 if (I->start < J->start) {
932 I = std::upper_bound(I, IE, J->start);
933 if (I != LHS.begin()) --I;
934 } else if (J->start < I->start) {
935 J = std::upper_bound(J, JE, I->start);
936 if (J != RHS.begin()) --J;
937 }
938
939 while (1) {
940 // Determine if these two live ranges overlap.
941 bool Overlaps;
942 if (I->start < J->start) {
943 Overlaps = I->end > J->start;
944 } else {
945 Overlaps = J->end > I->start;
946 }
947
948 // If so, check value # info to determine if they are really different.
949 if (Overlaps) {
950 // If the live range overlap will map to the same value number in the
Gabor Greife510b3a2007-07-09 12:00:59 +0000951 // result liverange, we can still coalesce them. If not, we can't.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000952 if (LHSValNoAssignments[I->valno->id] !=
953 RHSValNoAssignments[J->valno->id])
David Greene25133302007-06-08 17:18:56 +0000954 return false;
955 }
956
957 if (I->end < J->end) {
958 ++I;
959 if (I == IE) break;
960 } else {
961 ++J;
962 if (J == JE) break;
963 }
964 }
965
Evan Cheng34729252007-10-14 10:08:34 +0000966 // Update kill info. Some live ranges are extended due to copy coalescing.
967 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
968 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
969 VNInfo *VNI = I->first;
970 unsigned LHSValID = LHSValNoAssignments[VNI->id];
971 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
972 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
973 }
974
975 // Update kill info. Some live ranges are extended due to copy coalescing.
976 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
977 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
978 VNInfo *VNI = I->first;
979 unsigned RHSValID = RHSValNoAssignments[VNI->id];
980 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
981 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
982 }
983
Gabor Greife510b3a2007-07-09 12:00:59 +0000984 // If we get here, we know that we can coalesce the live ranges. Ask the
985 // intervals to coalesce themselves now.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000986 if ((RHS.ranges.size() > LHS.ranges.size() &&
987 MRegisterInfo::isVirtualRegister(LHS.reg)) ||
988 MRegisterInfo::isPhysicalRegister(RHS.reg)) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000989 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000990 Swapped = true;
991 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000992 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000993 Swapped = false;
994 }
David Greene25133302007-06-08 17:18:56 +0000995 return true;
996}
997
998namespace {
999 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1000 // depth of the basic block (the unsigned), and then on the MBB number.
1001 struct DepthMBBCompare {
1002 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1003 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1004 if (LHS.first > RHS.first) return true; // Deeper loops first
1005 return LHS.first == RHS.first &&
1006 LHS.second->getNumber() < RHS.second->getNumber();
1007 }
1008 };
1009}
1010
Evan Cheng8fc9a102007-11-06 08:52:21 +00001011/// getRepIntervalSize - Returns the size of the interval that represents the
1012/// specified register.
1013template<class SF>
1014unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1015 return Rc->getRepIntervalSize(Reg);
1016}
1017
1018/// CopyRecSort::operator - Join priority queue sorting function.
1019///
1020bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1021 // Inner loops first.
1022 if (left.LoopDepth > right.LoopDepth)
1023 return false;
1024 else if (left.LoopDepth == right.LoopDepth) {
1025 if (left.isBackEdge && !right.isBackEdge)
1026 return false;
1027 else if (left.isBackEdge == right.isBackEdge) {
1028 // Join virtuals to physical registers first.
1029 bool LDstIsPhys = MRegisterInfo::isPhysicalRegister(left.DstReg);
1030 bool LSrcIsPhys = MRegisterInfo::isPhysicalRegister(left.SrcReg);
1031 bool LIsPhys = LDstIsPhys || LSrcIsPhys;
1032 bool RDstIsPhys = MRegisterInfo::isPhysicalRegister(right.DstReg);
1033 bool RSrcIsPhys = MRegisterInfo::isPhysicalRegister(right.SrcReg);
1034 bool RIsPhys = RDstIsPhys || RSrcIsPhys;
1035 if (LIsPhys && !RIsPhys)
1036 return false;
1037 else if (LIsPhys == RIsPhys) {
1038 // Join shorter intervals first.
1039 unsigned LSize = 0;
1040 unsigned RSize = 0;
1041 if (LIsPhys) {
1042 LSize = LDstIsPhys ? 0 : JPQ->getRepIntervalSize(left.DstReg);
1043 LSize += LSrcIsPhys ? 0 : JPQ->getRepIntervalSize(left.SrcReg);
1044 RSize = RDstIsPhys ? 0 : JPQ->getRepIntervalSize(right.DstReg);
1045 RSize += RSrcIsPhys ? 0 : JPQ->getRepIntervalSize(right.SrcReg);
1046 } else {
1047 LSize = std::min(JPQ->getRepIntervalSize(left.DstReg),
1048 JPQ->getRepIntervalSize(left.SrcReg));
1049 RSize = std::min(JPQ->getRepIntervalSize(right.DstReg),
1050 JPQ->getRepIntervalSize(right.SrcReg));
1051 }
1052 if (LSize < RSize)
1053 return false;
1054 }
1055 }
1056 }
1057 return true;
1058}
1059
Gabor Greife510b3a2007-07-09 12:00:59 +00001060void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
Evan Cheng8b0b8742007-10-16 08:04:24 +00001061 std::vector<CopyRec> &TryAgain) {
David Greene25133302007-06-08 17:18:56 +00001062 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Evan Cheng8fc9a102007-11-06 08:52:21 +00001063
Evan Cheng8b0b8742007-10-16 08:04:24 +00001064 std::vector<CopyRec> VirtCopies;
1065 std::vector<CopyRec> PhysCopies;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001066 unsigned LoopDepth = loopInfo->getLoopDepth(MBB->getBasicBlock());
David Greene25133302007-06-08 17:18:56 +00001067 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1068 MII != E;) {
1069 MachineInstr *Inst = MII++;
1070
Evan Cheng32dfbea2007-10-12 08:50:34 +00001071 // If this isn't a copy nor a extract_subreg, we can't join intervals.
David Greene25133302007-06-08 17:18:56 +00001072 unsigned SrcReg, DstReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +00001073 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1074 DstReg = Inst->getOperand(0).getReg();
1075 SrcReg = Inst->getOperand(1).getReg();
1076 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1077 continue;
Evan Cheng8b0b8742007-10-16 08:04:24 +00001078
1079 unsigned repSrcReg = rep(SrcReg);
1080 unsigned repDstReg = rep(DstReg);
1081 bool SrcIsPhys = MRegisterInfo::isPhysicalRegister(repSrcReg);
1082 bool DstIsPhys = MRegisterInfo::isPhysicalRegister(repDstReg);
Evan Cheng8fc9a102007-11-06 08:52:21 +00001083 if (NewHeuristic) {
1084 JoinQueue->push(CopyRec(Inst, SrcReg, DstReg, LoopDepth,
1085 isBackEdgeCopy(Inst, DstReg)));
1086 } else {
1087 if (SrcIsPhys || DstIsPhys)
1088 PhysCopies.push_back(CopyRec(Inst, SrcReg, DstReg, 0, false));
1089 else
1090 VirtCopies.push_back(CopyRec(Inst, SrcReg, DstReg, 0, false));
1091 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00001092 }
1093
Evan Cheng8fc9a102007-11-06 08:52:21 +00001094 if (NewHeuristic)
1095 return;
1096
Evan Cheng8b0b8742007-10-16 08:04:24 +00001097 // Try coalescing physical register + virtual register first.
1098 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1099 CopyRec &TheCopy = PhysCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00001100 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001101 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00001102 if (Again)
1103 TryAgain.push_back(TheCopy);
Evan Cheng8b0b8742007-10-16 08:04:24 +00001104 }
1105 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1106 CopyRec &TheCopy = VirtCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00001107 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001108 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00001109 if (Again)
1110 TryAgain.push_back(TheCopy);
David Greene25133302007-06-08 17:18:56 +00001111 }
1112}
1113
1114void SimpleRegisterCoalescing::joinIntervals() {
1115 DOUT << "********** JOINING INTERVALS ***********\n";
1116
Evan Cheng8fc9a102007-11-06 08:52:21 +00001117 if (NewHeuristic)
1118 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1119
David Greene25133302007-06-08 17:18:56 +00001120 JoinedLIs.resize(li_->getNumIntervals());
1121 JoinedLIs.reset();
1122
1123 std::vector<CopyRec> TryAgainList;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001124 if (loopInfo->begin() == loopInfo->end()) {
David Greene25133302007-06-08 17:18:56 +00001125 // If there are no loops in the function, join intervals in function order.
1126 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1127 I != E; ++I)
Evan Cheng8b0b8742007-10-16 08:04:24 +00001128 CopyCoalesceInMBB(I, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00001129 } else {
1130 // Otherwise, join intervals in inner loops before other intervals.
1131 // Unfortunately we can't just iterate over loop hierarchy here because
1132 // there may be more MBB's than BB's. Collect MBB's for sorting.
1133
1134 // Join intervals in the function prolog first. We want to join physical
1135 // registers with virtual registers before the intervals got too long.
1136 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1137 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end(); I != E;++I)
Evan Cheng8fc9a102007-11-06 08:52:21 +00001138 MBBs.push_back(std::make_pair(loopInfo->
1139 getLoopDepth(I->getBasicBlock()), I));
David Greene25133302007-06-08 17:18:56 +00001140
1141 // Sort by loop depth.
1142 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1143
1144 // Finally, join intervals in loop nest order.
1145 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Evan Cheng8b0b8742007-10-16 08:04:24 +00001146 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00001147 }
1148
1149 // Joining intervals can allow other intervals to be joined. Iteratively join
1150 // until we make no progress.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001151 if (NewHeuristic) {
1152 SmallVector<CopyRec, 16> TryAgain;
1153 bool ProgressMade = true;
1154 while (ProgressMade) {
1155 ProgressMade = false;
1156 while (!JoinQueue->empty()) {
1157 CopyRec R = JoinQueue->pop();
Evan Cheng0547bab2007-11-01 06:22:48 +00001158 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001159 bool Success = JoinCopy(R, Again);
1160 if (Success)
Evan Cheng0547bab2007-11-01 06:22:48 +00001161 ProgressMade = true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001162 else if (Again)
1163 TryAgain.push_back(R);
1164 }
1165
1166 if (ProgressMade) {
1167 while (!TryAgain.empty()) {
1168 JoinQueue->push(TryAgain.back());
1169 TryAgain.pop_back();
1170 }
1171 }
1172 }
1173 } else {
1174 bool ProgressMade = true;
1175 while (ProgressMade) {
1176 ProgressMade = false;
1177
1178 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1179 CopyRec &TheCopy = TryAgainList[i];
1180 if (TheCopy.MI) {
1181 bool Again = false;
1182 bool Success = JoinCopy(TheCopy, Again);
1183 if (Success || !Again) {
1184 TheCopy.MI = 0; // Mark this one as done.
1185 ProgressMade = true;
1186 }
Evan Cheng0547bab2007-11-01 06:22:48 +00001187 }
David Greene25133302007-06-08 17:18:56 +00001188 }
1189 }
1190 }
1191
1192 // Some live range has been lengthened due to colaescing, eliminate the
1193 // unnecessary kills.
1194 int RegNum = JoinedLIs.find_first();
1195 while (RegNum != -1) {
1196 unsigned Reg = RegNum + MRegisterInfo::FirstVirtualRegister;
1197 unsigned repReg = rep(Reg);
1198 LiveInterval &LI = li_->getInterval(repReg);
1199 LiveVariables::VarInfo& svi = lv_->getVarInfo(Reg);
1200 for (unsigned i = 0, e = svi.Kills.size(); i != e; ++i) {
1201 MachineInstr *Kill = svi.Kills[i];
1202 // Suppose vr1 = op vr2, x
1203 // and vr1 and vr2 are coalesced. vr2 should still be marked kill
1204 // unless it is a two-address operand.
1205 if (li_->isRemoved(Kill) || hasRegisterDef(Kill, repReg))
1206 continue;
1207 if (LI.liveAt(li_->getInstructionIndex(Kill) + InstrSlots::NUM))
1208 unsetRegisterKill(Kill, repReg);
1209 }
1210 RegNum = JoinedLIs.find_next(RegNum);
1211 }
Evan Cheng8fc9a102007-11-06 08:52:21 +00001212
1213 if (NewHeuristic)
1214 delete JoinQueue;
David Greene25133302007-06-08 17:18:56 +00001215
1216 DOUT << "*** Register mapping ***\n";
Evan Cheng4ae31a52007-10-18 07:49:59 +00001217 for (unsigned i = 0, e = r2rMap_.size(); i != e; ++i)
David Greene25133302007-06-08 17:18:56 +00001218 if (r2rMap_[i]) {
1219 DOUT << " reg " << i << " -> ";
1220 DEBUG(printRegName(r2rMap_[i]));
1221 DOUT << "\n";
1222 }
1223}
1224
1225/// Return true if the two specified registers belong to different register
1226/// classes. The registers may be either phys or virt regs.
1227bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
Evan Cheng32dfbea2007-10-12 08:50:34 +00001228 unsigned RegB) const {
David Greene25133302007-06-08 17:18:56 +00001229
1230 // Get the register classes for the first reg.
1231 if (MRegisterInfo::isPhysicalRegister(RegA)) {
1232 assert(MRegisterInfo::isVirtualRegister(RegB) &&
1233 "Shouldn't consider two physregs!");
1234 return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
1235 }
1236
1237 // Compare against the regclass for the second reg.
1238 const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
1239 if (MRegisterInfo::isVirtualRegister(RegB))
1240 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
1241 else
1242 return !RegClass->contains(RegB);
1243}
1244
1245/// lastRegisterUse - Returns the last use of the specific register between
1246/// cycles Start and End. It also returns the use operand by reference. It
1247/// returns NULL if there are no uses.
1248MachineInstr *
1249SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End, unsigned Reg,
1250 MachineOperand *&MOU) {
1251 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1252 int s = Start;
1253 while (e >= s) {
1254 // Skip deleted instructions
1255 MachineInstr *MI = li_->getInstructionFromIndex(e);
1256 while ((e - InstrSlots::NUM) >= s && !MI) {
1257 e -= InstrSlots::NUM;
1258 MI = li_->getInstructionFromIndex(e);
1259 }
1260 if (e < s || MI == NULL)
1261 return NULL;
1262
1263 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1264 MachineOperand &MO = MI->getOperand(i);
Dan Gohman92dfe202007-09-14 20:33:02 +00001265 if (MO.isRegister() && MO.isUse() && MO.getReg() &&
David Greene25133302007-06-08 17:18:56 +00001266 mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1267 MOU = &MO;
1268 return MI;
1269 }
1270 }
1271
1272 e -= InstrSlots::NUM;
1273 }
1274
1275 return NULL;
1276}
1277
1278
1279/// findDefOperand - Returns the MachineOperand that is a def of the specific
1280/// register. It returns NULL if the def is not found.
1281MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI, unsigned Reg) {
1282 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1283 MachineOperand &MO = MI->getOperand(i);
Dan Gohman92dfe202007-09-14 20:33:02 +00001284 if (MO.isRegister() && MO.isDef() &&
David Greene25133302007-06-08 17:18:56 +00001285 mri_->regsOverlap(rep(MO.getReg()), Reg))
1286 return &MO;
1287 }
1288 return NULL;
1289}
1290
1291/// unsetRegisterKill - Unset IsKill property of all uses of specific register
1292/// of the specific instruction.
1293void SimpleRegisterCoalescing::unsetRegisterKill(MachineInstr *MI, unsigned Reg) {
1294 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1295 MachineOperand &MO = MI->getOperand(i);
Dan Gohman92dfe202007-09-14 20:33:02 +00001296 if (MO.isRegister() && MO.isKill() && MO.getReg() &&
David Greene25133302007-06-08 17:18:56 +00001297 mri_->regsOverlap(rep(MO.getReg()), Reg))
1298 MO.unsetIsKill();
1299 }
1300}
1301
1302/// unsetRegisterKills - Unset IsKill property of all uses of specific register
1303/// between cycles Start and End.
1304void SimpleRegisterCoalescing::unsetRegisterKills(unsigned Start, unsigned End,
1305 unsigned Reg) {
1306 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1307 int s = Start;
1308 while (e >= s) {
1309 // Skip deleted instructions
1310 MachineInstr *MI = li_->getInstructionFromIndex(e);
1311 while ((e - InstrSlots::NUM) >= s && !MI) {
1312 e -= InstrSlots::NUM;
1313 MI = li_->getInstructionFromIndex(e);
1314 }
1315 if (e < s || MI == NULL)
1316 return;
1317
1318 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1319 MachineOperand &MO = MI->getOperand(i);
Dan Gohman92dfe202007-09-14 20:33:02 +00001320 if (MO.isRegister() && MO.isKill() && MO.getReg() &&
David Greene25133302007-06-08 17:18:56 +00001321 mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1322 MO.unsetIsKill();
1323 }
1324 }
1325
1326 e -= InstrSlots::NUM;
1327 }
1328}
1329
1330/// hasRegisterDef - True if the instruction defines the specific register.
1331///
1332bool SimpleRegisterCoalescing::hasRegisterDef(MachineInstr *MI, unsigned Reg) {
1333 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1334 MachineOperand &MO = MI->getOperand(i);
Dan Gohman92dfe202007-09-14 20:33:02 +00001335 if (MO.isRegister() && MO.isDef() &&
David Greene25133302007-06-08 17:18:56 +00001336 mri_->regsOverlap(rep(MO.getReg()), Reg))
1337 return true;
1338 }
1339 return false;
1340}
1341
1342void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1343 if (MRegisterInfo::isPhysicalRegister(reg))
1344 cerr << mri_->getName(reg);
1345 else
1346 cerr << "%reg" << reg;
1347}
1348
1349void SimpleRegisterCoalescing::releaseMemory() {
Evan Cheng4ae31a52007-10-18 07:49:59 +00001350 for (unsigned i = 0, e = r2rMap_.size(); i != e; ++i)
1351 r2rRevMap_[i].clear();
1352 r2rRevMap_.clear();
1353 r2rMap_.clear();
1354 JoinedLIs.clear();
1355 SubRegIdxes.clear();
Evan Cheng8fc9a102007-11-06 08:52:21 +00001356 JoinedCopies.clear();
David Greene25133302007-06-08 17:18:56 +00001357}
1358
1359static bool isZeroLengthInterval(LiveInterval *li) {
1360 for (LiveInterval::Ranges::const_iterator
1361 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1362 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1363 return false;
1364 return true;
1365}
1366
1367bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1368 mf_ = &fn;
1369 tm_ = &fn.getTarget();
1370 mri_ = tm_->getRegisterInfo();
1371 tii_ = tm_->getInstrInfo();
1372 li_ = &getAnalysis<LiveIntervals>();
1373 lv_ = &getAnalysis<LiveVariables>();
Evan Cheng8fc9a102007-11-06 08:52:21 +00001374 loopInfo = &getAnalysis<LoopInfo>();
David Greene25133302007-06-08 17:18:56 +00001375
1376 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1377 << "********** Function: "
1378 << ((Value*)mf_->getFunction())->getName() << '\n';
1379
1380 allocatableRegs_ = mri_->getAllocatableSet(fn);
1381 for (MRegisterInfo::regclass_iterator I = mri_->regclass_begin(),
1382 E = mri_->regclass_end(); I != E; ++I)
1383 allocatableRCRegs_.insert(std::make_pair(*I,mri_->getAllocatableSet(fn, *I)));
1384
Evan Cheng32dfbea2007-10-12 08:50:34 +00001385 SSARegMap *RegMap = mf_->getSSARegMap();
1386 r2rMap_.grow(RegMap->getLastVirtReg());
Evan Cheng4ae31a52007-10-18 07:49:59 +00001387 r2rRevMap_.grow(RegMap->getLastVirtReg());
David Greene25133302007-06-08 17:18:56 +00001388
Gabor Greife510b3a2007-07-09 12:00:59 +00001389 // Join (coalesce) intervals if requested.
David Greene25133302007-06-08 17:18:56 +00001390 if (EnableJoining) {
1391 joinIntervals();
1392 DOUT << "********** INTERVALS POST JOINING **********\n";
1393 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1394 I->second.print(DOUT, mri_);
1395 DOUT << "\n";
1396 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001397
Evan Cheng8fc9a102007-11-06 08:52:21 +00001398 // Delete all coalesced copies.
1399 for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1400 E = JoinedCopies.end(); I != E; ++I) {
1401 li_->RemoveMachineInstrFromMaps(*I);
1402 (*I)->eraseFromParent();
1403 }
1404
Evan Cheng4ae31a52007-10-18 07:49:59 +00001405 // Transfer sub-registers info to SSARegMap now that coalescing information
1406 // is complete.
Evan Cheng32dfbea2007-10-12 08:50:34 +00001407 while (!SubRegIdxes.empty()) {
1408 std::pair<unsigned, unsigned> RI = SubRegIdxes.back();
1409 SubRegIdxes.pop_back();
1410 mf_->getSSARegMap()->setIsSubRegister(RI.first, rep(RI.first), RI.second);
1411 }
David Greene25133302007-06-08 17:18:56 +00001412 }
1413
1414 // perform a final pass over the instructions and compute spill
1415 // weights, coalesce virtual registers and remove identity moves.
David Greene25133302007-06-08 17:18:56 +00001416 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1417 mbbi != mbbe; ++mbbi) {
1418 MachineBasicBlock* mbb = mbbi;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001419 unsigned loopDepth = loopInfo->getLoopDepth(mbb->getBasicBlock());
David Greene25133302007-06-08 17:18:56 +00001420
1421 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1422 mii != mie; ) {
1423 // if the move will be an identity move delete it
1424 unsigned srcReg, dstReg, RegRep;
1425 if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
1426 (RegRep = rep(srcReg)) == rep(dstReg)) {
1427 // remove from def list
1428 LiveInterval &RegInt = li_->getOrCreateInterval(RegRep);
1429 MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1430 // If def of this move instruction is dead, remove its live range from
1431 // the dstination register's live interval.
1432 if (MO->isDead()) {
1433 unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1434 LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1435 RegInt.removeRange(MLR->start, MoveIdx+1);
1436 if (RegInt.empty())
1437 li_->removeInterval(RegRep);
1438 }
1439 li_->RemoveMachineInstrFromMaps(mii);
1440 mii = mbbi->erase(mii);
1441 ++numPeep;
1442 } else {
1443 SmallSet<unsigned, 4> UniqueUses;
1444 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1445 const MachineOperand &mop = mii->getOperand(i);
1446 if (mop.isRegister() && mop.getReg() &&
1447 MRegisterInfo::isVirtualRegister(mop.getReg())) {
1448 // replace register with representative register
Evan Cheng32dfbea2007-10-12 08:50:34 +00001449 unsigned OrigReg = mop.getReg();
1450 unsigned reg = rep(OrigReg);
1451 // Don't rewrite if it is a sub-register of a virtual register.
1452 if (!RegMap->isSubRegister(OrigReg))
1453 mii->getOperand(i).setReg(reg);
1454 else if (MRegisterInfo::isPhysicalRegister(reg))
1455 mii->getOperand(i).setReg(mri_->getSubReg(reg,
1456 RegMap->getSubRegisterIndex(OrigReg)));
David Greene25133302007-06-08 17:18:56 +00001457
1458 // Multiple uses of reg by the same instruction. It should not
1459 // contribute to spill weight again.
1460 if (UniqueUses.count(reg) != 0)
1461 continue;
1462 LiveInterval &RegInt = li_->getInterval(reg);
1463 float w = (mop.isUse()+mop.isDef()) * powf(10.0F, (float)loopDepth);
David Greene25133302007-06-08 17:18:56 +00001464 RegInt.weight += w;
1465 UniqueUses.insert(reg);
1466 }
1467 }
1468 ++mii;
1469 }
1470 }
1471 }
1472
1473 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1474 LiveInterval &LI = I->second;
1475 if (MRegisterInfo::isVirtualRegister(LI.reg)) {
1476 // If the live interval length is essentially zero, i.e. in every live
1477 // range the use follows def immediately, it doesn't make sense to spill
1478 // it and hope it will be easier to allocate for this li.
1479 if (isZeroLengthInterval(&LI))
1480 LI.weight = HUGE_VALF;
1481
1482 // Slightly prefer live interval that has been assigned a preferred reg.
1483 if (LI.preference)
1484 LI.weight *= 1.01F;
1485
1486 // Divide the weight of the interval by its size. This encourages
1487 // spilling of intervals that are large and have few uses, and
1488 // discourages spilling of small intervals with many uses.
1489 LI.weight /= LI.getSize();
1490 }
1491 }
1492
1493 DEBUG(dump());
1494 return true;
1495}
1496
1497/// print - Implement the dump method.
1498void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1499 li_->print(O, m);
1500}
David Greene2c17c4d2007-09-06 16:18:45 +00001501
1502RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1503 return new SimpleRegisterCoalescing();
1504}
1505
1506// Make sure that anything that uses RegisterCoalescer pulls in this file...
1507DEFINING_FILE_FOR(SimpleRegisterCoalescing)