blob: c608b8d1c4aa5627b3f35f05b856a220ea3812b5 [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"
David Greene25133302007-06-08 17:18:56 +000020#include "llvm/CodeGen/LiveVariables.h"
21#include "llvm/CodeGen/MachineFrameInfo.h"
22#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
David Greene25133302007-06-08 17:18:56 +000024#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
Evan Chengdfb15612007-12-07 00:28:32 +000055 static cl::opt<bool>
56 ReMatSpillWeight("tweak-remat-spill-weight",
57 cl::desc("Tweak spill weight of re-materializable intervals"),
58 cl::init(true));
59
David Greene25133302007-06-08 17:18:56 +000060 RegisterPass<SimpleRegisterCoalescing>
Chris Lattnere76fad22007-08-05 18:45:33 +000061 X("simple-register-coalescing", "Simple Register Coalescing");
David Greene2c17c4d2007-09-06 16:18:45 +000062
63 // Declare that we implement the RegisterCoalescer interface
64 RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
David Greene25133302007-06-08 17:18:56 +000065}
66
67const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
68
69void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
David Greene25133302007-06-08 17:18:56 +000070 AU.addPreserved<LiveIntervals>();
71 AU.addPreservedID(PHIEliminationID);
72 AU.addPreservedID(TwoAddressInstructionPassID);
73 AU.addRequired<LiveVariables>();
74 AU.addRequired<LiveIntervals>();
Evan Cheng22f07ff2007-12-11 02:09:15 +000075 AU.addRequired<MachineLoopInfo>();
David Greene25133302007-06-08 17:18:56 +000076 MachineFunctionPass::getAnalysisUsage(AU);
77}
78
Gabor Greife510b3a2007-07-09 12:00:59 +000079/// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
David Greene25133302007-06-08 17:18:56 +000080/// being the source and IntB being the dest, thus this defines a value number
81/// in IntB. If the source value number (in IntA) is defined by a copy from B,
82/// see if we can merge these two pieces of B into a single value number,
83/// eliminating a copy. For example:
84///
85/// A3 = B0
86/// ...
87/// B1 = A3 <- this copy
88///
89/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
90/// value number to be replaced with B0 (which simplifies the B liveinterval).
91///
92/// This returns true if an interval was modified.
93///
94bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
95 MachineInstr *CopyMI) {
96 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
97
98 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
99 // the example above.
100 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000101 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000102
103 // Get the location that B is defined at. Two options: either this value has
104 // an unknown definition point or it is defined at CopyIdx. If unknown, we
105 // can't process it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000106 if (!BValNo->reg) return false;
107 assert(BValNo->def == CopyIdx &&
David Greene25133302007-06-08 17:18:56 +0000108 "Copy doesn't define the value?");
109
110 // AValNo is the value number in A that defines the copy, A0 in the example.
111 LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000112 VNInfo *AValNo = AValLR->valno;
David Greene25133302007-06-08 17:18:56 +0000113
114 // If AValNo is defined as a copy from IntB, we can potentially process this.
115
116 // Get the instruction that defines this value number.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000117 unsigned SrcReg = AValNo->reg;
David Greene25133302007-06-08 17:18:56 +0000118 if (!SrcReg) return false; // Not defined by a copy.
119
120 // If the value number is not defined by a copy instruction, ignore it.
121
122 // If the source register comes from an interval other than IntB, we can't
123 // handle this.
124 if (rep(SrcReg) != IntB.reg) return false;
125
126 // Get the LiveRange in IntB that this value number starts with.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000127 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
David Greene25133302007-06-08 17:18:56 +0000128
129 // Make sure that the end of the live range is inside the same block as
130 // CopyMI.
131 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
132 if (!ValLREndInst ||
133 ValLREndInst->getParent() != CopyMI->getParent()) return false;
134
135 // Okay, we now know that ValLR ends in the same block that the CopyMI
136 // live-range starts. If there are no intervening live ranges between them in
137 // IntB, we can merge them.
138 if (ValLR+1 != BLR) return false;
Evan Chengdc5294f2007-08-14 23:19:28 +0000139
140 // If a live interval is a physical register, conservatively check if any
141 // of its sub-registers is overlapping the live interval of the virtual
142 // register. If so, do not coalesce.
143 if (MRegisterInfo::isPhysicalRegister(IntB.reg) &&
144 *mri_->getSubRegisters(IntB.reg)) {
145 for (const unsigned* SR = mri_->getSubRegisters(IntB.reg); *SR; ++SR)
146 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
147 DOUT << "Interfere with sub-register ";
148 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
149 return false;
150 }
151 }
David Greene25133302007-06-08 17:18:56 +0000152
153 DOUT << "\nExtending: "; IntB.print(DOUT, mri_);
154
Evan Chenga8d94f12007-08-07 23:49:57 +0000155 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
David Greene25133302007-06-08 17:18:56 +0000156 // We are about to delete CopyMI, so need to remove it as the 'instruction
Evan Chenga8d94f12007-08-07 23:49:57 +0000157 // that defines this value #'. Update the the valnum with the new defining
158 // instruction #.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000159 BValNo->def = FillerStart;
160 BValNo->reg = 0;
David Greene25133302007-06-08 17:18:56 +0000161
162 // Okay, we can merge them. We need to insert a new liverange:
163 // [ValLR.end, BLR.begin) of either value number, then we merge the
164 // two value numbers.
David Greene25133302007-06-08 17:18:56 +0000165 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
166
167 // If the IntB live range is assigned to a physical register, and if that
168 // physreg has aliases,
169 if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
170 // Update the liveintervals of sub-registers.
171 for (const unsigned *AS = mri_->getSubRegisters(IntB.reg); *AS; ++AS) {
172 LiveInterval &AliasLI = li_->getInterval(*AS);
173 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
Evan Chengf3bb2e62007-09-05 21:46:51 +0000174 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
David Greene25133302007-06-08 17:18:56 +0000175 }
176 }
177
178 // Okay, merge "B1" into the same value number as "B0".
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000179 if (BValNo != ValLR->valno)
180 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
David Greene25133302007-06-08 17:18:56 +0000181 DOUT << " result = "; IntB.print(DOUT, mri_);
182 DOUT << "\n";
183
184 // If the source instruction was killing the source register before the
185 // merge, unset the isKill marker given the live range has been extended.
186 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
187 if (UIdx != -1)
188 ValLREndInst->getOperand(UIdx).unsetIsKill();
189
David Greene25133302007-06-08 17:18:56 +0000190 ++numPeep;
191 return true;
192}
193
Evan Cheng4ae31a52007-10-18 07:49:59 +0000194/// AddSubRegIdxPairs - Recursively mark all the registers represented by the
195/// specified register as sub-registers. The recursion level is expected to be
196/// shallow.
197void SimpleRegisterCoalescing::AddSubRegIdxPairs(unsigned Reg, unsigned SubIdx) {
198 std::vector<unsigned> &JoinedRegs = r2rRevMap_[Reg];
199 for (unsigned i = 0, e = JoinedRegs.size(); i != e; ++i) {
200 SubRegIdxes.push_back(std::make_pair(JoinedRegs[i], SubIdx));
201 AddSubRegIdxPairs(JoinedRegs[i], SubIdx);
202 }
203}
204
Evan Cheng8fc9a102007-11-06 08:52:21 +0000205/// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
206///
207bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
208 unsigned DstReg) {
209 MachineBasicBlock *MBB = CopyMI->getParent();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000210 const MachineLoop *L = loopInfo->getLoopFor(MBB);
Evan Cheng8fc9a102007-11-06 08:52:21 +0000211 if (!L)
212 return false;
Evan Cheng22f07ff2007-12-11 02:09:15 +0000213 if (MBB != L->getLoopLatch())
Evan Cheng8fc9a102007-11-06 08:52:21 +0000214 return false;
215
216 DstReg = rep(DstReg);
217 LiveInterval &LI = li_->getInterval(DstReg);
218 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
219 LiveInterval::const_iterator DstLR =
220 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
221 if (DstLR == LI.end())
222 return false;
223 unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM-1;
224 if (DstLR->valno->kills.size() == 1 && DstLR->valno->kills[0] == KillIdx)
225 return true;
226 return false;
227}
228
David Greene25133302007-06-08 17:18:56 +0000229/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
230/// which are the src/dst of the copy instruction CopyMI. This returns true
Evan Cheng0547bab2007-11-01 06:22:48 +0000231/// if the copy was successfully coalesced away. If it is not currently
232/// possible to coalesce this interval, but it may be possible if other
233/// things get coalesced, then it returns true by reference in 'Again'.
Evan Cheng8fc9a102007-11-06 08:52:21 +0000234bool SimpleRegisterCoalescing::JoinCopy(CopyRec TheCopy, bool &Again) {
235 MachineInstr *CopyMI = TheCopy.MI;
236
237 Again = false;
238 if (JoinedCopies.count(CopyMI))
239 return false; // Already done.
240
David Greene25133302007-06-08 17:18:56 +0000241 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
242
243 // Get representative registers.
Evan Cheng8fc9a102007-11-06 08:52:21 +0000244 unsigned SrcReg = TheCopy.SrcReg;
245 unsigned DstReg = TheCopy.DstReg;
David Greene25133302007-06-08 17:18:56 +0000246 unsigned repSrcReg = rep(SrcReg);
247 unsigned repDstReg = rep(DstReg);
248
249 // If they are already joined we continue.
250 if (repSrcReg == repDstReg) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000251 DOUT << "\tCopy already coalesced.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000252 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000253 }
254
255 bool SrcIsPhys = MRegisterInfo::isPhysicalRegister(repSrcReg);
256 bool DstIsPhys = MRegisterInfo::isPhysicalRegister(repDstReg);
David Greene25133302007-06-08 17:18:56 +0000257
258 // If they are both physical registers, we cannot join them.
259 if (SrcIsPhys && DstIsPhys) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000260 DOUT << "\tCan not coalesce physregs.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000261 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000262 }
263
264 // We only join virtual registers with allocatable physical registers.
265 if (SrcIsPhys && !allocatableRegs_[repSrcReg]) {
266 DOUT << "\tSrc 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 }
269 if (DstIsPhys && !allocatableRegs_[repDstReg]) {
270 DOUT << "\tDst reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000271 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000272 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000273
274 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
275 unsigned RealDstReg = 0;
276 if (isExtSubReg) {
277 unsigned SubIdx = CopyMI->getOperand(2).getImm();
278 if (SrcIsPhys)
279 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
280 // coalesced with AX.
281 repSrcReg = mri_->getSubReg(repSrcReg, SubIdx);
282 else if (DstIsPhys) {
283 // If this is a extract_subreg where dst is a physical register, e.g.
284 // cl = EXTRACT_SUBREG reg1024, 1
285 // then create and update the actual physical register allocated to RHS.
Evan Cheng95f0ab62007-10-17 05:29:37 +0000286 const TargetRegisterClass *RC=mf_->getSSARegMap()->getRegClass(repSrcReg);
Evan Cheng32dfbea2007-10-12 08:50:34 +0000287 for (const unsigned *SRs = mri_->getSuperRegisters(repDstReg);
288 unsigned SR = *SRs; ++SRs) {
289 if (repDstReg == mri_->getSubReg(SR, SubIdx) &&
290 RC->contains(SR)) {
291 RealDstReg = SR;
292 break;
293 }
294 }
295 assert(RealDstReg && "Invalid extra_subreg instruction!");
296
297 // For this type of EXTRACT_SUBREG, conservatively
298 // check if the live interval of the source register interfere with the
299 // actual super physical register we are trying to coalesce with.
300 LiveInterval &RHS = li_->getInterval(repSrcReg);
301 if (li_->hasInterval(RealDstReg) &&
302 RHS.overlaps(li_->getInterval(RealDstReg))) {
303 DOUT << "Interfere with register ";
304 DEBUG(li_->getInterval(RealDstReg).print(DOUT, mri_));
Evan Cheng0547bab2007-11-01 06:22:48 +0000305 return false; // Not coalescable
Evan Cheng32dfbea2007-10-12 08:50:34 +0000306 }
307 for (const unsigned* SR = mri_->getSubRegisters(RealDstReg); *SR; ++SR)
308 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
309 DOUT << "Interfere with sub-register ";
310 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
Evan Cheng0547bab2007-11-01 06:22:48 +0000311 return false; // Not coalescable
Evan Cheng32dfbea2007-10-12 08:50:34 +0000312 }
Evan Cheng0547bab2007-11-01 06:22:48 +0000313 } else {
314 unsigned SrcSize= li_->getInterval(repSrcReg).getSize() / InstrSlots::NUM;
315 unsigned DstSize= li_->getInterval(repDstReg).getSize() / InstrSlots::NUM;
316 const TargetRegisterClass *RC=mf_->getSSARegMap()->getRegClass(repDstReg);
317 unsigned Threshold = allocatableRCRegs_[RC].count();
Evan Cheng52c7ff72007-10-12 09:15:53 +0000318 // Be conservative. If both sides are virtual registers, do not coalesce
Evan Cheng0547bab2007-11-01 06:22:48 +0000319 // if this will cause a high use density interval to target a smaller set
320 // of registers.
321 if (DstSize > Threshold || SrcSize > Threshold) {
322 LiveVariables::VarInfo &svi = lv_->getVarInfo(repSrcReg);
323 LiveVariables::VarInfo &dvi = lv_->getVarInfo(repDstReg);
324 if ((float)dvi.NumUses / DstSize < (float)svi.NumUses / SrcSize) {
325 Again = true; // May be possible to coalesce later.
326 return false;
327 }
328 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000329 }
330 } else if (differingRegisterClasses(repSrcReg, repDstReg)) {
331 // If they are not of the same register class, we cannot join them.
David Greene25133302007-06-08 17:18:56 +0000332 DOUT << "\tSrc/Dest are different register classes.\n";
Evan Cheng32dfbea2007-10-12 08:50:34 +0000333 // Allow the coalescer to try again in case either side gets coalesced to
334 // a physical register that's compatible with the other side. e.g.
335 // r1024 = MOV32to32_ r1025
336 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
Evan Cheng0547bab2007-11-01 06:22:48 +0000337 Again = true; // May be possible to coalesce later.
Evan Cheng32dfbea2007-10-12 08:50:34 +0000338 return false;
David Greene25133302007-06-08 17:18:56 +0000339 }
340
341 LiveInterval &SrcInt = li_->getInterval(repSrcReg);
342 LiveInterval &DstInt = li_->getInterval(repDstReg);
343 assert(SrcInt.reg == repSrcReg && DstInt.reg == repDstReg &&
344 "Register mapping is horribly broken!");
345
346 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, mri_);
347 DOUT << " and "; DstInt.print(DOUT, mri_);
348 DOUT << ": ";
349
350 // Check if it is necessary to propagate "isDead" property before intervals
351 // are joined.
352 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg);
353 bool isDead = mopd->isDead();
354 bool isShorten = false;
355 unsigned SrcStart = 0, RemoveStart = 0;
356 unsigned SrcEnd = 0, RemoveEnd = 0;
357 if (isDead) {
358 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
359 LiveInterval::iterator SrcLR =
360 SrcInt.FindLiveRangeContaining(li_->getUseIndex(CopyIdx));
361 RemoveStart = SrcStart = SrcLR->start;
362 RemoveEnd = SrcEnd = SrcLR->end;
363 // The instruction which defines the src is only truly dead if there are
364 // no intermediate uses and there isn't a use beyond the copy.
365 // FIXME: find the last use, mark is kill and shorten the live range.
366 if (SrcEnd > li_->getDefIndex(CopyIdx)) {
367 isDead = false;
368 } else {
369 MachineOperand *MOU;
370 MachineInstr *LastUse= lastRegisterUse(SrcStart, CopyIdx, repSrcReg, MOU);
371 if (LastUse) {
372 // Shorten the liveinterval to the end of last use.
373 MOU->setIsKill();
374 isDead = false;
375 isShorten = true;
376 RemoveStart = li_->getDefIndex(li_->getInstructionIndex(LastUse));
377 RemoveEnd = SrcEnd;
378 } else {
379 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
380 if (SrcMI) {
381 MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
382 if (mops)
383 // A dead def should have a single cycle interval.
384 ++RemoveStart;
385 }
386 }
387 }
388 }
389
390 // We need to be careful about coalescing a source physical register with a
391 // virtual register. Once the coalescing is done, it cannot be broken and
392 // these are not spillable! If the destination interval uses are far away,
393 // think twice about coalescing them!
Evan Cheng32dfbea2007-10-12 08:50:34 +0000394 if (!mopd->isDead() && (SrcIsPhys || DstIsPhys) && !isExtSubReg) {
David Greene25133302007-06-08 17:18:56 +0000395 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
396 unsigned JoinVReg = SrcIsPhys ? repDstReg : repSrcReg;
397 unsigned JoinPReg = SrcIsPhys ? repSrcReg : repDstReg;
398 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(JoinVReg);
399 unsigned Threshold = allocatableRCRegs_[RC].count();
Evan Cheng8fc9a102007-11-06 08:52:21 +0000400 if (TheCopy.isBackEdge)
401 Threshold *= 2; // Favors back edge copies.
David Greene25133302007-06-08 17:18:56 +0000402
Evan Cheng32dfbea2007-10-12 08:50:34 +0000403 // If the virtual register live interval is long but it has low use desity,
David Greene25133302007-06-08 17:18:56 +0000404 // do not join them, instead mark the physical register as its allocation
405 // preference.
406 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
407 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
408 if (Length > Threshold &&
409 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
410 JoinVInt.preference = JoinPReg;
411 ++numAborts;
412 DOUT << "\tMay tie down a physical register, abort!\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000413 Again = true; // May be possible to coalesce later.
David Greene25133302007-06-08 17:18:56 +0000414 return false;
415 }
416 }
417
418 // Okay, attempt to join these two intervals. On failure, this returns false.
419 // Otherwise, if one of the intervals being joined is a physreg, this method
420 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
421 // been modified, so we can use this information below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000422 bool Swapped = false;
423 if (JoinIntervals(DstInt, SrcInt, Swapped)) {
David Greene25133302007-06-08 17:18:56 +0000424 if (isDead) {
425 // Result of the copy is dead. Propagate this property.
426 if (SrcStart == 0) {
427 assert(MRegisterInfo::isPhysicalRegister(repSrcReg) &&
428 "Live-in must be a physical register!");
429 // Live-in to the function but dead. Remove it from entry live-in set.
430 // JoinIntervals may end up swapping the two intervals.
431 mf_->begin()->removeLiveIn(repSrcReg);
432 } else {
433 MachineInstr *SrcMI = li_->getInstructionFromIndex(SrcStart);
434 if (SrcMI) {
435 MachineOperand *mops = findDefOperand(SrcMI, repSrcReg);
436 if (mops)
437 mops->setIsDead();
438 }
439 }
440 }
441
442 if (isShorten || isDead) {
Evan Chengccb36a42007-08-12 01:26:19 +0000443 // Shorten the destination live interval.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000444 if (Swapped)
445 SrcInt.removeRange(RemoveStart, RemoveEnd);
David Greene25133302007-06-08 17:18:56 +0000446 }
447 } else {
Gabor Greife510b3a2007-07-09 12:00:59 +0000448 // Coalescing failed.
David Greene25133302007-06-08 17:18:56 +0000449
450 // If we can eliminate the copy without merging the live ranges, do so now.
Evan Cheng8fc9a102007-11-06 08:52:21 +0000451 if (!isExtSubReg && AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI)) {
452 JoinedCopies.insert(CopyMI);
David Greene25133302007-06-08 17:18:56 +0000453 return true;
Evan Cheng8fc9a102007-11-06 08:52:21 +0000454 }
David Greene25133302007-06-08 17:18:56 +0000455
456 // Otherwise, we are unable to join the intervals.
457 DOUT << "Interference!\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000458 Again = true; // May be possible to coalesce later.
David Greene25133302007-06-08 17:18:56 +0000459 return false;
460 }
461
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000462 LiveInterval *ResSrcInt = &SrcInt;
463 LiveInterval *ResDstInt = &DstInt;
464 if (Swapped) {
David Greene25133302007-06-08 17:18:56 +0000465 std::swap(repSrcReg, repDstReg);
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000466 std::swap(ResSrcInt, ResDstInt);
467 }
David Greene25133302007-06-08 17:18:56 +0000468 assert(MRegisterInfo::isVirtualRegister(repSrcReg) &&
469 "LiveInterval::join didn't work right!");
470
471 // If we're about to merge live ranges into a physical register live range,
472 // we have to update any aliased register's live ranges to indicate that they
473 // have clobbered values for this range.
474 if (MRegisterInfo::isPhysicalRegister(repDstReg)) {
475 // Unset unnecessary kills.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000476 if (!ResDstInt->containsOneValue()) {
477 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->begin(),
478 E = ResSrcInt->end(); I != E; ++I)
David Greene25133302007-06-08 17:18:56 +0000479 unsetRegisterKills(I->start, I->end, repDstReg);
480 }
481
Evan Cheng32dfbea2007-10-12 08:50:34 +0000482 // If this is a extract_subreg where dst is a physical register, e.g.
483 // cl = EXTRACT_SUBREG reg1024, 1
484 // then create and update the actual physical register allocated to RHS.
485 if (RealDstReg) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000486 LiveInterval &RealDstInt = li_->getOrCreateInterval(RealDstReg);
Evan Chengf5c73592007-10-15 18:33:50 +0000487 SmallSet<const VNInfo*, 4> CopiedValNos;
488 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
489 E = ResSrcInt->ranges.end(); I != E; ++I) {
490 LiveInterval::const_iterator DstLR =
491 ResDstInt->FindLiveRangeContaining(I->start);
492 assert(DstLR != ResDstInt->end() && "Invalid joined interval!");
493 const VNInfo *DstValNo = DstLR->valno;
494 if (CopiedValNos.insert(DstValNo)) {
495 VNInfo *ValNo = RealDstInt.getNextValue(DstValNo->def, DstValNo->reg,
496 li_->getVNInfoAllocator());
Evan Chengc3fc7d92007-11-29 09:49:23 +0000497 ValNo->hasPHIKill = DstValNo->hasPHIKill;
Evan Chengf5c73592007-10-15 18:33:50 +0000498 RealDstInt.addKills(ValNo, DstValNo->kills);
499 RealDstInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
500 }
Evan Cheng34729252007-10-14 10:08:34 +0000501 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000502 repDstReg = RealDstReg;
503 }
504
David Greene25133302007-06-08 17:18:56 +0000505 // Update the liveintervals of sub-registers.
506 for (const unsigned *AS = mri_->getSubRegisters(repDstReg); *AS; ++AS)
Evan Cheng32dfbea2007-10-12 08:50:34 +0000507 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
Evan Chengf3bb2e62007-09-05 21:46:51 +0000508 li_->getVNInfoAllocator());
David Greene25133302007-06-08 17:18:56 +0000509 } else {
510 // Merge use info if the destination is a virtual register.
511 LiveVariables::VarInfo& dVI = lv_->getVarInfo(repDstReg);
512 LiveVariables::VarInfo& sVI = lv_->getVarInfo(repSrcReg);
513 dVI.NumUses += sVI.NumUses;
514 }
515
David Greene25133302007-06-08 17:18:56 +0000516 // Remember these liveintervals have been joined.
517 JoinedLIs.set(repSrcReg - MRegisterInfo::FirstVirtualRegister);
518 if (MRegisterInfo::isVirtualRegister(repDstReg))
519 JoinedLIs.set(repDstReg - MRegisterInfo::FirstVirtualRegister);
520
Evan Cheng32dfbea2007-10-12 08:50:34 +0000521 if (isExtSubReg && !SrcIsPhys && !DstIsPhys) {
522 if (!Swapped) {
523 // Make sure we allocate the larger super-register.
524 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
525 std::swap(repSrcReg, repDstReg);
526 std::swap(ResSrcInt, ResDstInt);
527 }
Evan Cheng4ae31a52007-10-18 07:49:59 +0000528 unsigned SubIdx = CopyMI->getOperand(2).getImm();
529 SubRegIdxes.push_back(std::make_pair(repSrcReg, SubIdx));
530 AddSubRegIdxPairs(repSrcReg, SubIdx);
Evan Cheng32dfbea2007-10-12 08:50:34 +0000531 }
532
Evan Cheng8fc9a102007-11-06 08:52:21 +0000533 if (NewHeuristic) {
534 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
535 e = ResSrcInt->vni_end(); i != e; ++i) {
536 const VNInfo *vni = *i;
537 if (vni->def && vni->def != ~1U && vni->def != ~0U) {
538 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
539 unsigned SrcReg, DstReg;
540 if (CopyMI && tii_->isMoveInstr(*CopyMI, SrcReg, DstReg) &&
541 JoinedCopies.count(CopyMI) == 0) {
Evan Cheng22f07ff2007-12-11 02:09:15 +0000542 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
Evan Cheng8fc9a102007-11-06 08:52:21 +0000543 JoinQueue->push(CopyRec(CopyMI, SrcReg, DstReg, LoopDepth,
544 isBackEdgeCopy(CopyMI, DstReg)));
545 }
546 }
547 }
548 }
549
Evan Cheng32dfbea2007-10-12 08:50:34 +0000550 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, mri_);
551 DOUT << "\n";
552
Evan Cheng273288c2007-07-18 23:34:48 +0000553 // repSrcReg is guarateed to be the register whose live interval that is
554 // being merged.
David Greene25133302007-06-08 17:18:56 +0000555 li_->removeInterval(repSrcReg);
556 r2rMap_[repSrcReg] = repDstReg;
Evan Cheng4ae31a52007-10-18 07:49:59 +0000557 r2rRevMap_[repDstReg].push_back(repSrcReg);
David Greene25133302007-06-08 17:18:56 +0000558
559 // Finally, delete the copy instruction.
Evan Cheng8fc9a102007-11-06 08:52:21 +0000560 JoinedCopies.insert(CopyMI);
David Greene25133302007-06-08 17:18:56 +0000561 ++numPeep;
562 ++numJoins;
563 return true;
564}
565
566/// ComputeUltimateVN - Assuming we are going to join two live intervals,
567/// compute what the resultant value numbers for each value in the input two
568/// ranges will be. This is complicated by copies between the two which can
569/// and will commonly cause multiple value numbers to be merged into one.
570///
571/// VN is the value number that we're trying to resolve. InstDefiningValue
572/// keeps track of the new InstDefiningValue assignment for the result
573/// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
574/// whether a value in this or other is a copy from the opposite set.
575/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
576/// already been assigned.
577///
578/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
579/// contains the value number the copy is from.
580///
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000581static unsigned ComputeUltimateVN(VNInfo *VNI,
582 SmallVector<VNInfo*, 16> &NewVNInfo,
Evan Chengfadfb5b2007-08-31 21:23:06 +0000583 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
584 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
David Greene25133302007-06-08 17:18:56 +0000585 SmallVector<int, 16> &ThisValNoAssignments,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000586 SmallVector<int, 16> &OtherValNoAssignments) {
587 unsigned VN = VNI->id;
588
David Greene25133302007-06-08 17:18:56 +0000589 // If the VN has already been computed, just return it.
590 if (ThisValNoAssignments[VN] >= 0)
591 return ThisValNoAssignments[VN];
592// assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000593
David Greene25133302007-06-08 17:18:56 +0000594 // If this val is not a copy from the other val, then it must be a new value
595 // number in the destination.
Evan Chengfadfb5b2007-08-31 21:23:06 +0000596 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
Evan Chengc14b1442007-08-31 08:04:17 +0000597 if (I == ThisFromOther.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000598 NewVNInfo.push_back(VNI);
599 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +0000600 }
Evan Chengc14b1442007-08-31 08:04:17 +0000601 VNInfo *OtherValNo = I->second;
David Greene25133302007-06-08 17:18:56 +0000602
603 // Otherwise, this *is* a copy from the RHS. If the other side has already
604 // been computed, return it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000605 if (OtherValNoAssignments[OtherValNo->id] >= 0)
606 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
David Greene25133302007-06-08 17:18:56 +0000607
608 // Mark this value number as currently being computed, then ask what the
609 // ultimate value # of the other value is.
610 ThisValNoAssignments[VN] = -2;
611 unsigned UltimateVN =
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000612 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
613 OtherValNoAssignments, ThisValNoAssignments);
David Greene25133302007-06-08 17:18:56 +0000614 return ThisValNoAssignments[VN] = UltimateVN;
615}
616
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000617static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
David Greene25133302007-06-08 17:18:56 +0000618 return std::find(V.begin(), V.end(), Val) != V.end();
619}
620
621/// SimpleJoin - Attempt to joint the specified interval into this one. The
622/// caller of this method must guarantee that the RHS only contains a single
623/// value number and that the RHS is not defined by a copy from this
624/// interval. This returns false if the intervals are not joinable, or it
625/// joins them and returns true.
626bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
627 assert(RHS.containsOneValue());
628
629 // Some number (potentially more than one) value numbers in the current
630 // interval may be defined as copies from the RHS. Scan the overlapping
631 // portions of the LHS and RHS, keeping track of this and looking for
632 // overlapping live ranges that are NOT defined as copies. If these exist, we
Gabor Greife510b3a2007-07-09 12:00:59 +0000633 // cannot coalesce.
David Greene25133302007-06-08 17:18:56 +0000634
635 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
636 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
637
638 if (LHSIt->start < RHSIt->start) {
639 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
640 if (LHSIt != LHS.begin()) --LHSIt;
641 } else if (RHSIt->start < LHSIt->start) {
642 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
643 if (RHSIt != RHS.begin()) --RHSIt;
644 }
645
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000646 SmallVector<VNInfo*, 8> EliminatedLHSVals;
David Greene25133302007-06-08 17:18:56 +0000647
648 while (1) {
649 // Determine if these live intervals overlap.
650 bool Overlaps = false;
651 if (LHSIt->start <= RHSIt->start)
652 Overlaps = LHSIt->end > RHSIt->start;
653 else
654 Overlaps = RHSIt->end > LHSIt->start;
655
656 // If the live intervals overlap, there are two interesting cases: if the
657 // LHS interval is defined by a copy from the RHS, it's ok and we record
658 // that the LHS value # is the same as the RHS. If it's not, then we cannot
Gabor Greife510b3a2007-07-09 12:00:59 +0000659 // coalesce these live ranges and we bail out.
David Greene25133302007-06-08 17:18:56 +0000660 if (Overlaps) {
661 // If we haven't already recorded that this value # is safe, check it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000662 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +0000663 // Copy from the RHS?
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000664 unsigned SrcReg = LHSIt->valno->reg;
David Greene25133302007-06-08 17:18:56 +0000665 if (rep(SrcReg) != RHS.reg)
666 return false; // Nope, bail out.
667
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000668 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +0000669 }
670
671 // We know this entire LHS live range is okay, so skip it now.
672 if (++LHSIt == LHSEnd) break;
673 continue;
674 }
675
676 if (LHSIt->end < RHSIt->end) {
677 if (++LHSIt == LHSEnd) break;
678 } else {
679 // One interesting case to check here. It's possible that we have
680 // something like "X3 = Y" which defines a new value number in the LHS,
681 // and is the last use of this liverange of the RHS. In this case, we
Gabor Greife510b3a2007-07-09 12:00:59 +0000682 // want to notice this copy (so that it gets coalesced away) even though
David Greene25133302007-06-08 17:18:56 +0000683 // the live ranges don't actually overlap.
684 if (LHSIt->start == RHSIt->end) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000685 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +0000686 // We already know that this value number is going to be merged in
Gabor Greife510b3a2007-07-09 12:00:59 +0000687 // if coalescing succeeds. Just skip the liverange.
David Greene25133302007-06-08 17:18:56 +0000688 if (++LHSIt == LHSEnd) break;
689 } else {
690 // Otherwise, if this is a copy from the RHS, mark it as being merged
691 // in.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000692 if (rep(LHSIt->valno->reg) == RHS.reg) {
693 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +0000694
695 // We know this entire LHS live range is okay, so skip it now.
696 if (++LHSIt == LHSEnd) break;
697 }
698 }
699 }
700
701 if (++RHSIt == RHSEnd) break;
702 }
703 }
704
Gabor Greife510b3a2007-07-09 12:00:59 +0000705 // If we got here, we know that the coalescing will be successful and that
David Greene25133302007-06-08 17:18:56 +0000706 // the value numbers in EliminatedLHSVals will all be merged together. Since
707 // the most common case is that EliminatedLHSVals has a single number, we
708 // optimize for it: if there is more than one value, we merge them all into
709 // the lowest numbered one, then handle the interval as if we were merging
710 // with one value number.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000711 VNInfo *LHSValNo;
David Greene25133302007-06-08 17:18:56 +0000712 if (EliminatedLHSVals.size() > 1) {
713 // Loop through all the equal value numbers merging them into the smallest
714 // one.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000715 VNInfo *Smallest = EliminatedLHSVals[0];
David Greene25133302007-06-08 17:18:56 +0000716 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000717 if (EliminatedLHSVals[i]->id < Smallest->id) {
David Greene25133302007-06-08 17:18:56 +0000718 // Merge the current notion of the smallest into the smaller one.
719 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
720 Smallest = EliminatedLHSVals[i];
721 } else {
722 // Merge into the smallest.
723 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
724 }
725 }
726 LHSValNo = Smallest;
727 } else {
728 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
729 LHSValNo = EliminatedLHSVals[0];
730 }
731
732 // Okay, now that there is a single LHS value number that we're merging the
733 // RHS into, update the value number info for the LHS to indicate that the
734 // value number is defined where the RHS value number was.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000735 const VNInfo *VNI = RHS.getValNumInfo(0);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000736 LHSValNo->def = VNI->def;
737 LHSValNo->reg = VNI->reg;
David Greene25133302007-06-08 17:18:56 +0000738
739 // Okay, the final step is to loop over the RHS live intervals, adding them to
740 // the LHS.
Evan Chengc3fc7d92007-11-29 09:49:23 +0000741 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
Evan Chengf3bb2e62007-09-05 21:46:51 +0000742 LHS.addKills(LHSValNo, VNI->kills);
Evan Cheng430a7b02007-08-14 01:56:58 +0000743 LHS.MergeRangesInAsValue(RHS, LHSValNo);
David Greene25133302007-06-08 17:18:56 +0000744 LHS.weight += RHS.weight;
745 if (RHS.preference && !LHS.preference)
746 LHS.preference = RHS.preference;
747
748 return true;
749}
750
751/// JoinIntervals - Attempt to join these two intervals. On failure, this
752/// returns false. Otherwise, if one of the intervals being joined is a
753/// physreg, this method always canonicalizes LHS to be it. The output
754/// "RHS" will not have been modified, so we can use this information
755/// below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000756bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
757 LiveInterval &RHS, bool &Swapped) {
David Greene25133302007-06-08 17:18:56 +0000758 // Compute the final value assignment, assuming that the live ranges can be
Gabor Greife510b3a2007-07-09 12:00:59 +0000759 // coalesced.
David Greene25133302007-06-08 17:18:56 +0000760 SmallVector<int, 16> LHSValNoAssignments;
761 SmallVector<int, 16> RHSValNoAssignments;
Evan Chengfadfb5b2007-08-31 21:23:06 +0000762 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
763 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000764 SmallVector<VNInfo*, 16> NewVNInfo;
David Greene25133302007-06-08 17:18:56 +0000765
766 // If a live interval is a physical register, conservatively check if any
767 // of its sub-registers is overlapping the live interval of the virtual
768 // register. If so, do not coalesce.
769 if (MRegisterInfo::isPhysicalRegister(LHS.reg) &&
770 *mri_->getSubRegisters(LHS.reg)) {
771 for (const unsigned* SR = mri_->getSubRegisters(LHS.reg); *SR; ++SR)
772 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
773 DOUT << "Interfere with sub-register ";
774 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
775 return false;
776 }
777 } else if (MRegisterInfo::isPhysicalRegister(RHS.reg) &&
778 *mri_->getSubRegisters(RHS.reg)) {
779 for (const unsigned* SR = mri_->getSubRegisters(RHS.reg); *SR; ++SR)
780 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
781 DOUT << "Interfere with sub-register ";
782 DEBUG(li_->getInterval(*SR).print(DOUT, mri_));
783 return false;
784 }
785 }
786
787 // Compute ultimate value numbers for the LHS and RHS values.
788 if (RHS.containsOneValue()) {
789 // Copies from a liveinterval with a single value are simple to handle and
790 // very common, handle the special case here. This is important, because
791 // often RHS is small and LHS is large (e.g. a physreg).
792
793 // Find out if the RHS is defined as a copy from some value in the LHS.
Evan Cheng4f8ff162007-08-11 00:59:19 +0000794 int RHSVal0DefinedFromLHS = -1;
David Greene25133302007-06-08 17:18:56 +0000795 int RHSValID = -1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000796 VNInfo *RHSValNoInfo = NULL;
Evan Chengf3bb2e62007-09-05 21:46:51 +0000797 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
Evan Chengc14b1442007-08-31 08:04:17 +0000798 unsigned RHSSrcReg = RHSValNoInfo0->reg;
David Greene25133302007-06-08 17:18:56 +0000799 if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
800 // If RHS is not defined as a copy from the LHS, we can use simpler and
Gabor Greife510b3a2007-07-09 12:00:59 +0000801 // faster checks to see if the live ranges are coalescable. This joiner
David Greene25133302007-06-08 17:18:56 +0000802 // can't swap the LHS/RHS intervals though.
803 if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
804 return SimpleJoin(LHS, RHS);
805 } else {
Evan Chengc14b1442007-08-31 08:04:17 +0000806 RHSValNoInfo = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +0000807 }
808 } else {
809 // It was defined as a copy from the LHS, find out what value # it is.
Evan Chengc14b1442007-08-31 08:04:17 +0000810 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000811 RHSValID = RHSValNoInfo->id;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000812 RHSVal0DefinedFromLHS = RHSValID;
David Greene25133302007-06-08 17:18:56 +0000813 }
814
815 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
816 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000817 NewVNInfo.resize(LHS.getNumValNums(), NULL);
David Greene25133302007-06-08 17:18:56 +0000818
819 // Okay, *all* of the values in LHS that are defined as a copy from RHS
820 // should now get updated.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000821 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
822 i != e; ++i) {
823 VNInfo *VNI = *i;
824 unsigned VN = VNI->id;
825 if (unsigned LHSSrcReg = VNI->reg) {
David Greene25133302007-06-08 17:18:56 +0000826 if (rep(LHSSrcReg) != RHS.reg) {
827 // If this is not a copy from the RHS, its value number will be
Gabor Greife510b3a2007-07-09 12:00:59 +0000828 // unmodified by the coalescing.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000829 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +0000830 LHSValNoAssignments[VN] = VN;
831 } else if (RHSValID == -1) {
832 // Otherwise, it is a copy from the RHS, and we don't already have a
833 // value# for it. Keep the current value number, but remember it.
834 LHSValNoAssignments[VN] = RHSValID = VN;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000835 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +0000836 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +0000837 } else {
838 // Otherwise, use the specified value #.
839 LHSValNoAssignments[VN] = RHSValID;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000840 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
841 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +0000842 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000843 }
David Greene25133302007-06-08 17:18:56 +0000844 }
845 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000846 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +0000847 LHSValNoAssignments[VN] = VN;
848 }
849 }
850
851 assert(RHSValID != -1 && "Didn't find value #?");
852 RHSValNoAssignments[0] = RHSValID;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000853 if (RHSVal0DefinedFromLHS != -1) {
Evan Cheng34301352007-09-01 02:03:17 +0000854 // This path doesn't go through ComputeUltimateVN so just set
855 // it to anything.
856 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000857 }
David Greene25133302007-06-08 17:18:56 +0000858 } else {
859 // Loop over the value numbers of the LHS, seeing if any are defined from
860 // the RHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000861 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
862 i != e; ++i) {
863 VNInfo *VNI = *i;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000864 unsigned ValSrcReg = VNI->reg;
Evan Cheng5031fd22007-11-05 06:46:45 +0000865 if (VNI->def == ~1U ||ValSrcReg == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +0000866 continue;
867
868 // DstReg is known to be a register in the LHS interval. If the src is
869 // from the RHS interval, we can use its value #.
870 if (rep(ValSrcReg) != RHS.reg)
871 continue;
872
873 // Figure out the value # from the RHS.
Evan Chengc14b1442007-08-31 08:04:17 +0000874 LHSValsDefinedFromRHS[VNI] = RHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +0000875 }
876
877 // Loop over the value numbers of the RHS, seeing if any are defined from
878 // the LHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000879 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
880 i != e; ++i) {
881 VNInfo *VNI = *i;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000882 unsigned ValSrcReg = VNI->reg;
Evan Cheng5031fd22007-11-05 06:46:45 +0000883 if (VNI->def == ~1U || ValSrcReg == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +0000884 continue;
885
886 // DstReg is known to be a register in the RHS interval. If the src is
887 // from the LHS interval, we can use its value #.
888 if (rep(ValSrcReg) != LHS.reg)
889 continue;
890
891 // Figure out the value # from the LHS.
Evan Chengc14b1442007-08-31 08:04:17 +0000892 RHSValsDefinedFromLHS[VNI]= LHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +0000893 }
894
895 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
896 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000897 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
David Greene25133302007-06-08 17:18:56 +0000898
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000899 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
900 i != e; ++i) {
901 VNInfo *VNI = *i;
902 unsigned VN = VNI->id;
903 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +0000904 continue;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000905 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +0000906 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000907 LHSValNoAssignments, RHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +0000908 }
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000909 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
910 i != e; ++i) {
911 VNInfo *VNI = *i;
912 unsigned VN = VNI->id;
913 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +0000914 continue;
915 // If this value number isn't a copy from the LHS, it's a new number.
Evan Chengc14b1442007-08-31 08:04:17 +0000916 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000917 NewVNInfo.push_back(VNI);
918 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +0000919 continue;
920 }
921
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000922 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +0000923 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000924 RHSValNoAssignments, LHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +0000925 }
926 }
927
928 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
Gabor Greife510b3a2007-07-09 12:00:59 +0000929 // interval lists to see if these intervals are coalescable.
David Greene25133302007-06-08 17:18:56 +0000930 LiveInterval::const_iterator I = LHS.begin();
931 LiveInterval::const_iterator IE = LHS.end();
932 LiveInterval::const_iterator J = RHS.begin();
933 LiveInterval::const_iterator JE = RHS.end();
934
935 // Skip ahead until the first place of potential sharing.
936 if (I->start < J->start) {
937 I = std::upper_bound(I, IE, J->start);
938 if (I != LHS.begin()) --I;
939 } else if (J->start < I->start) {
940 J = std::upper_bound(J, JE, I->start);
941 if (J != RHS.begin()) --J;
942 }
943
944 while (1) {
945 // Determine if these two live ranges overlap.
946 bool Overlaps;
947 if (I->start < J->start) {
948 Overlaps = I->end > J->start;
949 } else {
950 Overlaps = J->end > I->start;
951 }
952
953 // If so, check value # info to determine if they are really different.
954 if (Overlaps) {
955 // If the live range overlap will map to the same value number in the
Gabor Greife510b3a2007-07-09 12:00:59 +0000956 // result liverange, we can still coalesce them. If not, we can't.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000957 if (LHSValNoAssignments[I->valno->id] !=
958 RHSValNoAssignments[J->valno->id])
David Greene25133302007-06-08 17:18:56 +0000959 return false;
960 }
961
962 if (I->end < J->end) {
963 ++I;
964 if (I == IE) break;
965 } else {
966 ++J;
967 if (J == JE) break;
968 }
969 }
970
Evan Cheng34729252007-10-14 10:08:34 +0000971 // Update kill info. Some live ranges are extended due to copy coalescing.
972 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
973 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
974 VNInfo *VNI = I->first;
975 unsigned LHSValID = LHSValNoAssignments[VNI->id];
976 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000977 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +0000978 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
979 }
980
981 // Update kill info. Some live ranges are extended due to copy coalescing.
982 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
983 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
984 VNInfo *VNI = I->first;
985 unsigned RHSValID = RHSValNoAssignments[VNI->id];
986 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000987 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +0000988 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
989 }
990
Gabor Greife510b3a2007-07-09 12:00:59 +0000991 // If we get here, we know that we can coalesce the live ranges. Ask the
992 // intervals to coalesce themselves now.
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000993 if ((RHS.ranges.size() > LHS.ranges.size() &&
994 MRegisterInfo::isVirtualRegister(LHS.reg)) ||
995 MRegisterInfo::isPhysicalRegister(RHS.reg)) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000996 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +0000997 Swapped = true;
998 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000999 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001000 Swapped = false;
1001 }
David Greene25133302007-06-08 17:18:56 +00001002 return true;
1003}
1004
1005namespace {
1006 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1007 // depth of the basic block (the unsigned), and then on the MBB number.
1008 struct DepthMBBCompare {
1009 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1010 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1011 if (LHS.first > RHS.first) return true; // Deeper loops first
1012 return LHS.first == RHS.first &&
1013 LHS.second->getNumber() < RHS.second->getNumber();
1014 }
1015 };
1016}
1017
Evan Cheng8fc9a102007-11-06 08:52:21 +00001018/// getRepIntervalSize - Returns the size of the interval that represents the
1019/// specified register.
1020template<class SF>
1021unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1022 return Rc->getRepIntervalSize(Reg);
1023}
1024
1025/// CopyRecSort::operator - Join priority queue sorting function.
1026///
1027bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1028 // Inner loops first.
1029 if (left.LoopDepth > right.LoopDepth)
1030 return false;
1031 else if (left.LoopDepth == right.LoopDepth) {
1032 if (left.isBackEdge && !right.isBackEdge)
1033 return false;
1034 else if (left.isBackEdge == right.isBackEdge) {
1035 // Join virtuals to physical registers first.
1036 bool LDstIsPhys = MRegisterInfo::isPhysicalRegister(left.DstReg);
1037 bool LSrcIsPhys = MRegisterInfo::isPhysicalRegister(left.SrcReg);
1038 bool LIsPhys = LDstIsPhys || LSrcIsPhys;
1039 bool RDstIsPhys = MRegisterInfo::isPhysicalRegister(right.DstReg);
1040 bool RSrcIsPhys = MRegisterInfo::isPhysicalRegister(right.SrcReg);
1041 bool RIsPhys = RDstIsPhys || RSrcIsPhys;
1042 if (LIsPhys && !RIsPhys)
1043 return false;
1044 else if (LIsPhys == RIsPhys) {
1045 // Join shorter intervals first.
1046 unsigned LSize = 0;
1047 unsigned RSize = 0;
1048 if (LIsPhys) {
1049 LSize = LDstIsPhys ? 0 : JPQ->getRepIntervalSize(left.DstReg);
1050 LSize += LSrcIsPhys ? 0 : JPQ->getRepIntervalSize(left.SrcReg);
1051 RSize = RDstIsPhys ? 0 : JPQ->getRepIntervalSize(right.DstReg);
1052 RSize += RSrcIsPhys ? 0 : JPQ->getRepIntervalSize(right.SrcReg);
1053 } else {
1054 LSize = std::min(JPQ->getRepIntervalSize(left.DstReg),
1055 JPQ->getRepIntervalSize(left.SrcReg));
1056 RSize = std::min(JPQ->getRepIntervalSize(right.DstReg),
1057 JPQ->getRepIntervalSize(right.SrcReg));
1058 }
1059 if (LSize < RSize)
1060 return false;
1061 }
1062 }
1063 }
1064 return true;
1065}
1066
Gabor Greife510b3a2007-07-09 12:00:59 +00001067void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
Evan Cheng8b0b8742007-10-16 08:04:24 +00001068 std::vector<CopyRec> &TryAgain) {
David Greene25133302007-06-08 17:18:56 +00001069 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Evan Cheng8fc9a102007-11-06 08:52:21 +00001070
Evan Cheng8b0b8742007-10-16 08:04:24 +00001071 std::vector<CopyRec> VirtCopies;
1072 std::vector<CopyRec> PhysCopies;
Evan Cheng22f07ff2007-12-11 02:09:15 +00001073 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
David Greene25133302007-06-08 17:18:56 +00001074 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1075 MII != E;) {
1076 MachineInstr *Inst = MII++;
1077
Evan Cheng32dfbea2007-10-12 08:50:34 +00001078 // If this isn't a copy nor a extract_subreg, we can't join intervals.
David Greene25133302007-06-08 17:18:56 +00001079 unsigned SrcReg, DstReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +00001080 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1081 DstReg = Inst->getOperand(0).getReg();
1082 SrcReg = Inst->getOperand(1).getReg();
1083 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1084 continue;
Evan Cheng8b0b8742007-10-16 08:04:24 +00001085
1086 unsigned repSrcReg = rep(SrcReg);
1087 unsigned repDstReg = rep(DstReg);
1088 bool SrcIsPhys = MRegisterInfo::isPhysicalRegister(repSrcReg);
1089 bool DstIsPhys = MRegisterInfo::isPhysicalRegister(repDstReg);
Evan Cheng8fc9a102007-11-06 08:52:21 +00001090 if (NewHeuristic) {
1091 JoinQueue->push(CopyRec(Inst, SrcReg, DstReg, LoopDepth,
1092 isBackEdgeCopy(Inst, DstReg)));
1093 } else {
1094 if (SrcIsPhys || DstIsPhys)
1095 PhysCopies.push_back(CopyRec(Inst, SrcReg, DstReg, 0, false));
1096 else
1097 VirtCopies.push_back(CopyRec(Inst, SrcReg, DstReg, 0, false));
1098 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00001099 }
1100
Evan Cheng8fc9a102007-11-06 08:52:21 +00001101 if (NewHeuristic)
1102 return;
1103
Evan Cheng8b0b8742007-10-16 08:04:24 +00001104 // Try coalescing physical register + virtual register first.
1105 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1106 CopyRec &TheCopy = PhysCopies[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);
Evan Cheng8b0b8742007-10-16 08:04:24 +00001111 }
1112 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1113 CopyRec &TheCopy = VirtCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00001114 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001115 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00001116 if (Again)
1117 TryAgain.push_back(TheCopy);
David Greene25133302007-06-08 17:18:56 +00001118 }
1119}
1120
1121void SimpleRegisterCoalescing::joinIntervals() {
1122 DOUT << "********** JOINING INTERVALS ***********\n";
1123
Evan Cheng8fc9a102007-11-06 08:52:21 +00001124 if (NewHeuristic)
1125 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1126
David Greene25133302007-06-08 17:18:56 +00001127 JoinedLIs.resize(li_->getNumIntervals());
1128 JoinedLIs.reset();
1129
1130 std::vector<CopyRec> TryAgainList;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001131 if (loopInfo->begin() == loopInfo->end()) {
David Greene25133302007-06-08 17:18:56 +00001132 // If there are no loops in the function, join intervals in function order.
1133 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1134 I != E; ++I)
Evan Cheng8b0b8742007-10-16 08:04:24 +00001135 CopyCoalesceInMBB(I, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00001136 } else {
1137 // Otherwise, join intervals in inner loops before other intervals.
1138 // Unfortunately we can't just iterate over loop hierarchy here because
1139 // there may be more MBB's than BB's. Collect MBB's for sorting.
1140
1141 // Join intervals in the function prolog first. We want to join physical
1142 // registers with virtual registers before the intervals got too long.
1143 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
Evan Cheng22f07ff2007-12-11 02:09:15 +00001144 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1145 MachineBasicBlock *MBB = I;
1146 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1147 }
David Greene25133302007-06-08 17:18:56 +00001148
1149 // Sort by loop depth.
1150 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1151
1152 // Finally, join intervals in loop nest order.
1153 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Evan Cheng8b0b8742007-10-16 08:04:24 +00001154 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00001155 }
1156
1157 // Joining intervals can allow other intervals to be joined. Iteratively join
1158 // until we make no progress.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001159 if (NewHeuristic) {
1160 SmallVector<CopyRec, 16> TryAgain;
1161 bool ProgressMade = true;
1162 while (ProgressMade) {
1163 ProgressMade = false;
1164 while (!JoinQueue->empty()) {
1165 CopyRec R = JoinQueue->pop();
Evan Cheng0547bab2007-11-01 06:22:48 +00001166 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001167 bool Success = JoinCopy(R, Again);
1168 if (Success)
Evan Cheng0547bab2007-11-01 06:22:48 +00001169 ProgressMade = true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001170 else if (Again)
1171 TryAgain.push_back(R);
1172 }
1173
1174 if (ProgressMade) {
1175 while (!TryAgain.empty()) {
1176 JoinQueue->push(TryAgain.back());
1177 TryAgain.pop_back();
1178 }
1179 }
1180 }
1181 } else {
1182 bool ProgressMade = true;
1183 while (ProgressMade) {
1184 ProgressMade = false;
1185
1186 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1187 CopyRec &TheCopy = TryAgainList[i];
1188 if (TheCopy.MI) {
1189 bool Again = false;
1190 bool Success = JoinCopy(TheCopy, Again);
1191 if (Success || !Again) {
1192 TheCopy.MI = 0; // Mark this one as done.
1193 ProgressMade = true;
1194 }
Evan Cheng0547bab2007-11-01 06:22:48 +00001195 }
David Greene25133302007-06-08 17:18:56 +00001196 }
1197 }
1198 }
1199
1200 // Some live range has been lengthened due to colaescing, eliminate the
1201 // unnecessary kills.
1202 int RegNum = JoinedLIs.find_first();
1203 while (RegNum != -1) {
1204 unsigned Reg = RegNum + MRegisterInfo::FirstVirtualRegister;
1205 unsigned repReg = rep(Reg);
1206 LiveInterval &LI = li_->getInterval(repReg);
1207 LiveVariables::VarInfo& svi = lv_->getVarInfo(Reg);
1208 for (unsigned i = 0, e = svi.Kills.size(); i != e; ++i) {
1209 MachineInstr *Kill = svi.Kills[i];
1210 // Suppose vr1 = op vr2, x
1211 // and vr1 and vr2 are coalesced. vr2 should still be marked kill
1212 // unless it is a two-address operand.
1213 if (li_->isRemoved(Kill) || hasRegisterDef(Kill, repReg))
1214 continue;
1215 if (LI.liveAt(li_->getInstructionIndex(Kill) + InstrSlots::NUM))
1216 unsetRegisterKill(Kill, repReg);
1217 }
1218 RegNum = JoinedLIs.find_next(RegNum);
1219 }
Evan Cheng8fc9a102007-11-06 08:52:21 +00001220
1221 if (NewHeuristic)
1222 delete JoinQueue;
David Greene25133302007-06-08 17:18:56 +00001223
1224 DOUT << "*** Register mapping ***\n";
Evan Cheng4ae31a52007-10-18 07:49:59 +00001225 for (unsigned i = 0, e = r2rMap_.size(); i != e; ++i)
David Greene25133302007-06-08 17:18:56 +00001226 if (r2rMap_[i]) {
1227 DOUT << " reg " << i << " -> ";
1228 DEBUG(printRegName(r2rMap_[i]));
1229 DOUT << "\n";
1230 }
1231}
1232
1233/// Return true if the two specified registers belong to different register
1234/// classes. The registers may be either phys or virt regs.
1235bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
Evan Cheng32dfbea2007-10-12 08:50:34 +00001236 unsigned RegB) const {
David Greene25133302007-06-08 17:18:56 +00001237
1238 // Get the register classes for the first reg.
1239 if (MRegisterInfo::isPhysicalRegister(RegA)) {
1240 assert(MRegisterInfo::isVirtualRegister(RegB) &&
1241 "Shouldn't consider two physregs!");
1242 return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
1243 }
1244
1245 // Compare against the regclass for the second reg.
1246 const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
1247 if (MRegisterInfo::isVirtualRegister(RegB))
1248 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
1249 else
1250 return !RegClass->contains(RegB);
1251}
1252
1253/// lastRegisterUse - Returns the last use of the specific register between
1254/// cycles Start and End. It also returns the use operand by reference. It
1255/// returns NULL if there are no uses.
1256MachineInstr *
1257SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End, unsigned Reg,
1258 MachineOperand *&MOU) {
1259 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1260 int s = Start;
1261 while (e >= s) {
1262 // Skip deleted instructions
1263 MachineInstr *MI = li_->getInstructionFromIndex(e);
1264 while ((e - InstrSlots::NUM) >= s && !MI) {
1265 e -= InstrSlots::NUM;
1266 MI = li_->getInstructionFromIndex(e);
1267 }
1268 if (e < s || MI == NULL)
1269 return NULL;
1270
1271 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1272 MachineOperand &MO = MI->getOperand(i);
Dan Gohman92dfe202007-09-14 20:33:02 +00001273 if (MO.isRegister() && MO.isUse() && MO.getReg() &&
David Greene25133302007-06-08 17:18:56 +00001274 mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1275 MOU = &MO;
1276 return MI;
1277 }
1278 }
1279
1280 e -= InstrSlots::NUM;
1281 }
1282
1283 return NULL;
1284}
1285
1286
1287/// findDefOperand - Returns the MachineOperand that is a def of the specific
1288/// register. It returns NULL if the def is not found.
1289MachineOperand *SimpleRegisterCoalescing::findDefOperand(MachineInstr *MI, unsigned Reg) {
1290 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1291 MachineOperand &MO = MI->getOperand(i);
Dan Gohman92dfe202007-09-14 20:33:02 +00001292 if (MO.isRegister() && MO.isDef() &&
David Greene25133302007-06-08 17:18:56 +00001293 mri_->regsOverlap(rep(MO.getReg()), Reg))
1294 return &MO;
1295 }
1296 return NULL;
1297}
1298
1299/// unsetRegisterKill - Unset IsKill property of all uses of specific register
1300/// of the specific instruction.
1301void SimpleRegisterCoalescing::unsetRegisterKill(MachineInstr *MI, unsigned Reg) {
1302 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1303 MachineOperand &MO = MI->getOperand(i);
Dan Gohman92dfe202007-09-14 20:33:02 +00001304 if (MO.isRegister() && MO.isKill() && MO.getReg() &&
David Greene25133302007-06-08 17:18:56 +00001305 mri_->regsOverlap(rep(MO.getReg()), Reg))
1306 MO.unsetIsKill();
1307 }
1308}
1309
1310/// unsetRegisterKills - Unset IsKill property of all uses of specific register
1311/// between cycles Start and End.
1312void SimpleRegisterCoalescing::unsetRegisterKills(unsigned Start, unsigned End,
1313 unsigned Reg) {
1314 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1315 int s = Start;
1316 while (e >= s) {
1317 // Skip deleted instructions
1318 MachineInstr *MI = li_->getInstructionFromIndex(e);
1319 while ((e - InstrSlots::NUM) >= s && !MI) {
1320 e -= InstrSlots::NUM;
1321 MI = li_->getInstructionFromIndex(e);
1322 }
1323 if (e < s || MI == NULL)
1324 return;
1325
1326 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1327 MachineOperand &MO = MI->getOperand(i);
Dan Gohman92dfe202007-09-14 20:33:02 +00001328 if (MO.isRegister() && MO.isKill() && MO.getReg() &&
David Greene25133302007-06-08 17:18:56 +00001329 mri_->regsOverlap(rep(MO.getReg()), Reg)) {
1330 MO.unsetIsKill();
1331 }
1332 }
1333
1334 e -= InstrSlots::NUM;
1335 }
1336}
1337
1338/// hasRegisterDef - True if the instruction defines the specific register.
1339///
1340bool SimpleRegisterCoalescing::hasRegisterDef(MachineInstr *MI, unsigned Reg) {
1341 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1342 MachineOperand &MO = MI->getOperand(i);
Dan Gohman92dfe202007-09-14 20:33:02 +00001343 if (MO.isRegister() && MO.isDef() &&
David Greene25133302007-06-08 17:18:56 +00001344 mri_->regsOverlap(rep(MO.getReg()), Reg))
1345 return true;
1346 }
1347 return false;
1348}
1349
1350void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
1351 if (MRegisterInfo::isPhysicalRegister(reg))
1352 cerr << mri_->getName(reg);
1353 else
1354 cerr << "%reg" << reg;
1355}
1356
1357void SimpleRegisterCoalescing::releaseMemory() {
Evan Cheng4ae31a52007-10-18 07:49:59 +00001358 for (unsigned i = 0, e = r2rMap_.size(); i != e; ++i)
1359 r2rRevMap_[i].clear();
1360 r2rRevMap_.clear();
1361 r2rMap_.clear();
1362 JoinedLIs.clear();
1363 SubRegIdxes.clear();
Evan Cheng8fc9a102007-11-06 08:52:21 +00001364 JoinedCopies.clear();
David Greene25133302007-06-08 17:18:56 +00001365}
1366
1367static bool isZeroLengthInterval(LiveInterval *li) {
1368 for (LiveInterval::Ranges::const_iterator
1369 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1370 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1371 return false;
1372 return true;
1373}
1374
1375bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1376 mf_ = &fn;
1377 tm_ = &fn.getTarget();
1378 mri_ = tm_->getRegisterInfo();
1379 tii_ = tm_->getInstrInfo();
1380 li_ = &getAnalysis<LiveIntervals>();
1381 lv_ = &getAnalysis<LiveVariables>();
Evan Cheng22f07ff2007-12-11 02:09:15 +00001382 loopInfo = &getAnalysis<MachineLoopInfo>();
David Greene25133302007-06-08 17:18:56 +00001383
1384 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1385 << "********** Function: "
1386 << ((Value*)mf_->getFunction())->getName() << '\n';
1387
1388 allocatableRegs_ = mri_->getAllocatableSet(fn);
1389 for (MRegisterInfo::regclass_iterator I = mri_->regclass_begin(),
1390 E = mri_->regclass_end(); I != E; ++I)
1391 allocatableRCRegs_.insert(std::make_pair(*I,mri_->getAllocatableSet(fn, *I)));
1392
Evan Cheng32dfbea2007-10-12 08:50:34 +00001393 SSARegMap *RegMap = mf_->getSSARegMap();
1394 r2rMap_.grow(RegMap->getLastVirtReg());
Evan Cheng4ae31a52007-10-18 07:49:59 +00001395 r2rRevMap_.grow(RegMap->getLastVirtReg());
David Greene25133302007-06-08 17:18:56 +00001396
Gabor Greife510b3a2007-07-09 12:00:59 +00001397 // Join (coalesce) intervals if requested.
Evan Chengc498b022007-11-14 07:59:08 +00001398 IndexedMap<unsigned, VirtReg2IndexFunctor> RegSubIdxMap;
David Greene25133302007-06-08 17:18:56 +00001399 if (EnableJoining) {
1400 joinIntervals();
1401 DOUT << "********** INTERVALS POST JOINING **********\n";
1402 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1403 I->second.print(DOUT, mri_);
1404 DOUT << "\n";
1405 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001406
Evan Cheng8fc9a102007-11-06 08:52:21 +00001407 // Delete all coalesced copies.
1408 for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
1409 E = JoinedCopies.end(); I != E; ++I) {
1410 li_->RemoveMachineInstrFromMaps(*I);
1411 (*I)->eraseFromParent();
1412 }
1413
Evan Cheng4ae31a52007-10-18 07:49:59 +00001414 // Transfer sub-registers info to SSARegMap now that coalescing information
1415 // is complete.
Evan Chengc498b022007-11-14 07:59:08 +00001416 RegSubIdxMap.grow(mf_->getSSARegMap()->getLastVirtReg()+1);
Evan Cheng32dfbea2007-10-12 08:50:34 +00001417 while (!SubRegIdxes.empty()) {
1418 std::pair<unsigned, unsigned> RI = SubRegIdxes.back();
1419 SubRegIdxes.pop_back();
Evan Chengc498b022007-11-14 07:59:08 +00001420 RegSubIdxMap[RI.first] = RI.second;
Evan Cheng32dfbea2007-10-12 08:50:34 +00001421 }
David Greene25133302007-06-08 17:18:56 +00001422 }
1423
1424 // perform a final pass over the instructions and compute spill
1425 // weights, coalesce virtual registers and remove identity moves.
David Greene25133302007-06-08 17:18:56 +00001426 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
1427 mbbi != mbbe; ++mbbi) {
1428 MachineBasicBlock* mbb = mbbi;
Evan Cheng22f07ff2007-12-11 02:09:15 +00001429 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
David Greene25133302007-06-08 17:18:56 +00001430
1431 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
1432 mii != mie; ) {
1433 // if the move will be an identity move delete it
1434 unsigned srcReg, dstReg, RegRep;
1435 if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
1436 (RegRep = rep(srcReg)) == rep(dstReg)) {
1437 // remove from def list
1438 LiveInterval &RegInt = li_->getOrCreateInterval(RegRep);
1439 MachineOperand *MO = mii->findRegisterDefOperand(dstReg);
1440 // If def of this move instruction is dead, remove its live range from
1441 // the dstination register's live interval.
1442 if (MO->isDead()) {
1443 unsigned MoveIdx = li_->getDefIndex(li_->getInstructionIndex(mii));
1444 LiveInterval::iterator MLR = RegInt.FindLiveRangeContaining(MoveIdx);
1445 RegInt.removeRange(MLR->start, MoveIdx+1);
1446 if (RegInt.empty())
1447 li_->removeInterval(RegRep);
1448 }
1449 li_->RemoveMachineInstrFromMaps(mii);
1450 mii = mbbi->erase(mii);
1451 ++numPeep;
1452 } else {
1453 SmallSet<unsigned, 4> UniqueUses;
1454 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
1455 const MachineOperand &mop = mii->getOperand(i);
1456 if (mop.isRegister() && mop.getReg() &&
1457 MRegisterInfo::isVirtualRegister(mop.getReg())) {
1458 // replace register with representative register
Evan Cheng32dfbea2007-10-12 08:50:34 +00001459 unsigned OrigReg = mop.getReg();
1460 unsigned reg = rep(OrigReg);
Evan Chengc498b022007-11-14 07:59:08 +00001461 unsigned SubIdx = RegSubIdxMap[OrigReg];
1462 if (SubIdx && MRegisterInfo::isPhysicalRegister(reg))
1463 mii->getOperand(i).setReg(mri_->getSubReg(reg, SubIdx));
1464 else {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001465 mii->getOperand(i).setReg(reg);
Evan Chengc498b022007-11-14 07:59:08 +00001466 mii->getOperand(i).setSubReg(SubIdx);
1467 }
David Greene25133302007-06-08 17:18:56 +00001468
1469 // Multiple uses of reg by the same instruction. It should not
1470 // contribute to spill weight again.
1471 if (UniqueUses.count(reg) != 0)
1472 continue;
1473 LiveInterval &RegInt = li_->getInterval(reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001474 RegInt.weight +=
1475 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
David Greene25133302007-06-08 17:18:56 +00001476 UniqueUses.insert(reg);
1477 }
1478 }
1479 ++mii;
1480 }
1481 }
1482 }
1483
1484 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
1485 LiveInterval &LI = I->second;
1486 if (MRegisterInfo::isVirtualRegister(LI.reg)) {
1487 // If the live interval length is essentially zero, i.e. in every live
1488 // range the use follows def immediately, it doesn't make sense to spill
1489 // it and hope it will be easier to allocate for this li.
1490 if (isZeroLengthInterval(&LI))
1491 LI.weight = HUGE_VALF;
Evan Cheng5ef3a042007-12-06 00:01:56 +00001492 else {
1493 bool isLoad = false;
Evan Chengdfb15612007-12-07 00:28:32 +00001494 if (ReMatSpillWeight && li_->isReMaterializable(LI, isLoad)) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00001495 // If all of the definitions of the interval are re-materializable,
1496 // it is a preferred candidate for spilling. If non of the defs are
1497 // loads, then it's potentially very cheap to re-materialize.
1498 // FIXME: this gets much more complicated once we support non-trivial
1499 // re-materialization.
1500 if (isLoad)
1501 LI.weight *= 0.9F;
1502 else
1503 LI.weight *= 0.5F;
1504 }
1505 }
David Greene25133302007-06-08 17:18:56 +00001506
1507 // Slightly prefer live interval that has been assigned a preferred reg.
1508 if (LI.preference)
1509 LI.weight *= 1.01F;
1510
1511 // Divide the weight of the interval by its size. This encourages
1512 // spilling of intervals that are large and have few uses, and
1513 // discourages spilling of small intervals with many uses.
1514 LI.weight /= LI.getSize();
1515 }
1516 }
1517
1518 DEBUG(dump());
1519 return true;
1520}
1521
1522/// print - Implement the dump method.
1523void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
1524 li_->print(O, m);
1525}
David Greene2c17c4d2007-09-06 16:18:45 +00001526
1527RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
1528 return new SimpleRegisterCoalescing();
1529}
1530
1531// Make sure that anything that uses RegisterCoalescer pulls in this file...
1532DEFINING_FILE_FOR(SimpleRegisterCoalescing)