blob: 29e634b477d16db1fa211ebfe2199cfc79c1da97 [file] [log] [blame]
David Greene25133302007-06-08 17:18:56 +00001//===-- SimpleRegisterCoalescing.cpp - Register Coalescing ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
David Greene25133302007-06-08 17:18:56 +00007//
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/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000022#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000023#include "llvm/CodeGen/MachineRegisterInfo.h"
David Greene25133302007-06-08 17:18:56 +000024#include "llvm/CodeGen/Passes.h"
David Greene2c17c4d2007-09-06 16:18:45 +000025#include "llvm/CodeGen/RegisterCoalescer.h"
David Greene25133302007-06-08 17:18:56 +000026#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/ADT/SmallSet.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/STLExtras.h"
33#include <algorithm>
34#include <cmath>
35using namespace llvm;
36
37STATISTIC(numJoins , "Number of interval joins performed");
Evan Chenge00f5de2008-06-19 01:39:21 +000038STATISTIC(numSubJoins , "Number of subclass joins performed");
Evan Cheng70071432008-02-13 03:01:43 +000039STATISTIC(numCommutes , "Number of instruction commuting performed");
40STATISTIC(numExtends , "Number of copies extended");
David Greene25133302007-06-08 17:18:56 +000041STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
42STATISTIC(numAborts , "Number of times interval joining aborted");
43
44char SimpleRegisterCoalescing::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000045static cl::opt<bool>
46EnableJoining("join-liveintervals",
47 cl::desc("Coalesce copies (default=true)"),
48 cl::init(true));
David Greene25133302007-06-08 17:18:56 +000049
Dan Gohman844731a2008-05-13 00:00:25 +000050static cl::opt<bool>
51NewHeuristic("new-coalescer-heuristic",
Evan Chenge00f5de2008-06-19 01:39:21 +000052 cl::desc("Use new coalescer heuristic"),
53 cl::init(false), cl::Hidden);
54
55static cl::opt<bool>
56CrossClassJoin("join-subclass-copies",
57 cl::desc("Coalesce copies to sub- register class"),
58 cl::init(false), cl::Hidden);
Evan Cheng8fc9a102007-11-06 08:52:21 +000059
Dan Gohman844731a2008-05-13 00:00:25 +000060static RegisterPass<SimpleRegisterCoalescing>
61X("simple-register-coalescing", "Simple Register Coalescing");
David Greene2c17c4d2007-09-06 16:18:45 +000062
Dan Gohman844731a2008-05-13 00:00:25 +000063// Declare that we implement the RegisterCoalescer interface
64static RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
David Greene25133302007-06-08 17:18:56 +000065
Dan Gohman6ddba2b2008-05-13 02:05:11 +000066const PassInfo *const llvm::SimpleRegisterCoalescingID = &X;
David Greene25133302007-06-08 17:18:56 +000067
68void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
David Greene25133302007-06-08 17:18:56 +000069 AU.addPreserved<LiveIntervals>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000070 AU.addPreserved<MachineLoopInfo>();
71 AU.addPreservedID(MachineDominatorsID);
David Greene25133302007-06-08 17:18:56 +000072 AU.addPreservedID(PHIEliminationID);
73 AU.addPreservedID(TwoAddressInstructionPassID);
David Greene25133302007-06-08 17:18:56 +000074 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///
Bill Wendling2674d712008-01-04 08:59:18 +000094bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
95 LiveInterval &IntB,
96 MachineInstr *CopyMI) {
David Greene25133302007-06-08 17:18:56 +000097 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
98
99 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
100 // the example above.
101 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000102 if (BLR == IntB.end()) // Should never happen!
103 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000104 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000105
106 // Get the location that B is defined at. Two options: either this value has
107 // an unknown definition point or it is defined at CopyIdx. If unknown, we
108 // can't process it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000109 if (!BValNo->copy) return false;
110 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
David Greene25133302007-06-08 17:18:56 +0000111
Evan Cheng70071432008-02-13 03:01:43 +0000112 // AValNo is the value number in A that defines the copy, A3 in the example.
113 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
Evan Chengff7a3e52008-04-16 18:48:43 +0000114 if (ALR == IntA.end()) // Should never happen!
115 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000116 VNInfo *AValNo = ALR->valno;
David Greene25133302007-06-08 17:18:56 +0000117
Evan Cheng70071432008-02-13 03:01:43 +0000118 // If AValNo is defined as a copy from IntB, we can potentially process this.
David Greene25133302007-06-08 17:18:56 +0000119 // Get the instruction that defines this value number.
Evan Chengc8d044e2008-02-15 18:24:29 +0000120 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
David Greene25133302007-06-08 17:18:56 +0000121 if (!SrcReg) return false; // Not defined by a copy.
122
123 // If the value number is not defined by a copy instruction, ignore it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000124
David Greene25133302007-06-08 17:18:56 +0000125 // If the source register comes from an interval other than IntB, we can't
126 // handle this.
Evan Chengc8d044e2008-02-15 18:24:29 +0000127 if (SrcReg != IntB.reg) return false;
David Greene25133302007-06-08 17:18:56 +0000128
129 // Get the LiveRange in IntB that this value number starts with.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000130 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
Evan Chengff7a3e52008-04-16 18:48:43 +0000131 if (ValLR == IntB.end()) // Should never happen!
132 return false;
David Greene25133302007-06-08 17:18:56 +0000133
134 // Make sure that the end of the live range is inside the same block as
135 // CopyMI.
136 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
137 if (!ValLREndInst ||
138 ValLREndInst->getParent() != CopyMI->getParent()) return false;
139
140 // Okay, we now know that ValLR ends in the same block that the CopyMI
141 // live-range starts. If there are no intervening live ranges between them in
142 // IntB, we can merge them.
143 if (ValLR+1 != BLR) return false;
Evan Chengdc5294f2007-08-14 23:19:28 +0000144
145 // If a live interval is a physical register, conservatively check if any
146 // of its sub-registers is overlapping the live interval of the virtual
147 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000148 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
149 *tri_->getSubRegisters(IntB.reg)) {
150 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
Evan Chengdc5294f2007-08-14 23:19:28 +0000151 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
152 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000153 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
Evan Chengdc5294f2007-08-14 23:19:28 +0000154 return false;
155 }
156 }
David Greene25133302007-06-08 17:18:56 +0000157
Dan Gohman6f0d0242008-02-10 18:45:23 +0000158 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000159
Evan Chenga8d94f12007-08-07 23:49:57 +0000160 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
David Greene25133302007-06-08 17:18:56 +0000161 // We are about to delete CopyMI, so need to remove it as the 'instruction
Evan Chenga8d94f12007-08-07 23:49:57 +0000162 // that defines this value #'. Update the the valnum with the new defining
163 // instruction #.
Evan Chengc8d044e2008-02-15 18:24:29 +0000164 BValNo->def = FillerStart;
165 BValNo->copy = NULL;
David Greene25133302007-06-08 17:18:56 +0000166
167 // Okay, we can merge them. We need to insert a new liverange:
168 // [ValLR.end, BLR.begin) of either value number, then we merge the
169 // two value numbers.
David Greene25133302007-06-08 17:18:56 +0000170 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
171
172 // If the IntB live range is assigned to a physical register, and if that
173 // physreg has aliases,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000174 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
David Greene25133302007-06-08 17:18:56 +0000175 // Update the liveintervals of sub-registers.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000176 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
David Greene25133302007-06-08 17:18:56 +0000177 LiveInterval &AliasLI = li_->getInterval(*AS);
178 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
Evan Chengf3bb2e62007-09-05 21:46:51 +0000179 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
David Greene25133302007-06-08 17:18:56 +0000180 }
181 }
182
183 // Okay, merge "B1" into the same value number as "B0".
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000184 if (BValNo != ValLR->valno)
185 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000186 DOUT << " result = "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000187 DOUT << "\n";
188
189 // If the source instruction was killing the source register before the
190 // merge, unset the isKill marker given the live range has been extended.
191 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
192 if (UIdx != -1)
Chris Lattnerf7382302007-12-30 21:56:09 +0000193 ValLREndInst->getOperand(UIdx).setIsKill(false);
Evan Cheng70071432008-02-13 03:01:43 +0000194
195 ++numExtends;
196 return true;
197}
198
Evan Cheng559f4222008-02-16 02:32:17 +0000199/// HasOtherReachingDefs - Return true if there are definitions of IntB
200/// other than BValNo val# that can reach uses of AValno val# of IntA.
201bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
202 LiveInterval &IntB,
203 VNInfo *AValNo,
204 VNInfo *BValNo) {
205 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
206 AI != AE; ++AI) {
207 if (AI->valno != AValNo) continue;
208 LiveInterval::Ranges::iterator BI =
209 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
210 if (BI != IntB.ranges.begin())
211 --BI;
212 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
213 if (BI->valno == BValNo)
214 continue;
215 if (BI->start <= AI->start && BI->end > AI->start)
216 return true;
217 if (BI->start > AI->start && BI->start < AI->end)
218 return true;
219 }
220 }
221 return false;
222}
223
Evan Cheng70071432008-02-13 03:01:43 +0000224/// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
225/// being the source and IntB being the dest, thus this defines a value number
226/// in IntB. If the source value number (in IntA) is defined by a commutable
227/// instruction and its other operand is coalesced to the copy dest register,
228/// see if we can transform the copy into a noop by commuting the definition. For
229/// example,
230///
231/// A3 = op A2 B0<kill>
232/// ...
233/// B1 = A3 <- this copy
234/// ...
235/// = op A3 <- more uses
236///
237/// ==>
238///
239/// B2 = op B0 A2<kill>
240/// ...
241/// B1 = B2 <- now an identify copy
242/// ...
243/// = op B2 <- more uses
244///
245/// This returns true if an interval was modified.
246///
247bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
248 LiveInterval &IntB,
249 MachineInstr *CopyMI) {
Evan Cheng70071432008-02-13 03:01:43 +0000250 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
251
Evan Chenga9407f52008-02-18 18:56:31 +0000252 // FIXME: For now, only eliminate the copy by commuting its def when the
253 // source register is a virtual register. We want to guard against cases
254 // where the copy is a back edge copy and commuting the def lengthen the
255 // live interval of the source register to the entire loop.
256 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
Evan Cheng96cfff02008-02-18 08:40:53 +0000257 return false;
258
Evan Chengc8d044e2008-02-15 18:24:29 +0000259 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
Evan Cheng70071432008-02-13 03:01:43 +0000260 // the example above.
261 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000262 if (BLR == IntB.end()) // Should never happen!
263 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000264 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000265
Evan Cheng70071432008-02-13 03:01:43 +0000266 // Get the location that B is defined at. Two options: either this value has
267 // an unknown definition point or it is defined at CopyIdx. If unknown, we
268 // can't process it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000269 if (!BValNo->copy) return false;
Evan Cheng70071432008-02-13 03:01:43 +0000270 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
271
272 // AValNo is the value number in A that defines the copy, A3 in the example.
273 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
Evan Chengff7a3e52008-04-16 18:48:43 +0000274 if (ALR == IntA.end()) // Should never happen!
275 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000276 VNInfo *AValNo = ALR->valno;
Evan Chenge35a6d12008-02-13 08:41:08 +0000277 // If other defs can reach uses of this def, then it's not safe to perform
278 // the optimization.
279 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
Evan Cheng70071432008-02-13 03:01:43 +0000280 return false;
281 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
282 const TargetInstrDesc &TID = DefMI->getDesc();
Evan Chengc8d044e2008-02-15 18:24:29 +0000283 unsigned NewDstIdx;
284 if (!TID.isCommutable() ||
285 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
Evan Cheng70071432008-02-13 03:01:43 +0000286 return false;
287
Evan Chengc8d044e2008-02-15 18:24:29 +0000288 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
289 unsigned NewReg = NewDstMO.getReg();
290 if (NewReg != IntB.reg || !NewDstMO.isKill())
Evan Cheng70071432008-02-13 03:01:43 +0000291 return false;
292
293 // Make sure there are no other definitions of IntB that would reach the
294 // uses which the new definition can reach.
Evan Cheng559f4222008-02-16 02:32:17 +0000295 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
296 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000297
Evan Chenged70cbb32008-03-26 19:03:01 +0000298 // If some of the uses of IntA.reg is already coalesced away, return false.
299 // It's not possible to determine whether it's safe to perform the coalescing.
300 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
301 UE = mri_->use_end(); UI != UE; ++UI) {
302 MachineInstr *UseMI = &*UI;
303 unsigned UseIdx = li_->getInstructionIndex(UseMI);
304 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000305 if (ULR == IntA.end())
306 continue;
Evan Chenged70cbb32008-03-26 19:03:01 +0000307 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
308 return false;
309 }
310
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000311 // At this point we have decided that it is legal to do this
312 // transformation. Start by commuting the instruction.
Evan Cheng70071432008-02-13 03:01:43 +0000313 MachineBasicBlock *MBB = DefMI->getParent();
314 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
Evan Cheng559f4222008-02-16 02:32:17 +0000315 if (!NewMI)
316 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000317 if (NewMI != DefMI) {
318 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
319 MBB->insert(DefMI, NewMI);
320 MBB->erase(DefMI);
321 }
Evan Cheng6130f662008-03-05 00:59:57 +0000322 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
Evan Cheng70071432008-02-13 03:01:43 +0000323 NewMI->getOperand(OpIdx).setIsKill();
324
Evan Cheng70071432008-02-13 03:01:43 +0000325 bool BHasPHIKill = BValNo->hasPHIKill;
326 SmallVector<VNInfo*, 4> BDeadValNos;
327 SmallVector<unsigned, 4> BKills;
328 std::map<unsigned, unsigned> BExtend;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000329
330 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
331 // A = or A, B
332 // ...
333 // B = A
334 // ...
335 // C = A<kill>
336 // ...
337 // = B
338 //
339 // then do not add kills of A to the newly created B interval.
340 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
341 if (Extended)
342 BExtend[ALR->end] = BLR->end;
343
344 // Update uses of IntA of the specific Val# with IntB.
Evan Cheng70071432008-02-13 03:01:43 +0000345 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
346 UE = mri_->use_end(); UI != UE;) {
347 MachineOperand &UseMO = UI.getOperand();
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000348 MachineInstr *UseMI = &*UI;
Evan Cheng70071432008-02-13 03:01:43 +0000349 ++UI;
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000350 if (JoinedCopies.count(UseMI))
Evan Chenged70cbb32008-03-26 19:03:01 +0000351 continue;
Evan Cheng70071432008-02-13 03:01:43 +0000352 unsigned UseIdx = li_->getInstructionIndex(UseMI);
353 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000354 if (ULR == IntA.end() || ULR->valno != AValNo)
Evan Cheng70071432008-02-13 03:01:43 +0000355 continue;
356 UseMO.setReg(NewReg);
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000357 if (UseMI == CopyMI)
358 continue;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000359 if (UseMO.isKill()) {
360 if (Extended)
361 UseMO.setIsKill(false);
362 else
363 BKills.push_back(li_->getUseIndex(UseIdx)+1);
364 }
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000365 unsigned SrcReg, DstReg;
366 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
367 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +0000368 if (DstReg == IntB.reg) {
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000369 // This copy will become a noop. If it's defining a new val#,
370 // remove that val# as well. However this live range is being
371 // extended to the end of the existing live range defined by the copy.
372 unsigned DefIdx = li_->getDefIndex(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000373 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000374 BHasPHIKill |= DLR->valno->hasPHIKill;
375 assert(DLR->valno->def == DefIdx);
376 BDeadValNos.push_back(DLR->valno);
377 BExtend[DLR->start] = DLR->end;
378 JoinedCopies.insert(UseMI);
379 // If this is a kill but it's going to be removed, the last use
380 // of the same val# is the new kill.
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000381 if (UseMO.isKill())
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000382 BKills.pop_back();
Evan Cheng70071432008-02-13 03:01:43 +0000383 }
384 }
385
386 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
387 // simply extend BLR if CopyMI doesn't end the range.
388 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
389
Evan Cheng739583b2008-06-17 20:11:16 +0000390 // Remove val#'s defined by copies that will be coalesced away.
Evan Cheng70071432008-02-13 03:01:43 +0000391 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
392 IntB.removeValNo(BDeadValNos[i]);
Evan Cheng739583b2008-06-17 20:11:16 +0000393
394 // Extend BValNo by merging in IntA live ranges of AValNo. Val# definition
395 // is updated. Kills are also updated.
396 VNInfo *ValNo = BValNo;
397 ValNo->def = AValNo->def;
398 ValNo->copy = NULL;
399 for (unsigned j = 0, ee = ValNo->kills.size(); j != ee; ++j) {
400 unsigned Kill = ValNo->kills[j];
401 if (Kill != BLR->end)
402 BKills.push_back(Kill);
403 }
404 ValNo->kills.clear();
Evan Cheng70071432008-02-13 03:01:43 +0000405 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
406 AI != AE; ++AI) {
407 if (AI->valno != AValNo) continue;
408 unsigned End = AI->end;
409 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
410 if (EI != BExtend.end())
411 End = EI->second;
412 IntB.addRange(LiveRange(AI->start, End, ValNo));
413 }
414 IntB.addKills(ValNo, BKills);
415 ValNo->hasPHIKill = BHasPHIKill;
416
417 DOUT << " result = "; IntB.print(DOUT, tri_);
418 DOUT << "\n";
419
420 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
421 IntA.removeValNo(AValNo);
422 DOUT << " result = "; IntA.print(DOUT, tri_);
423 DOUT << "\n";
424
425 ++numCommutes;
David Greene25133302007-06-08 17:18:56 +0000426 return true;
427}
428
Evan Cheng8fc9a102007-11-06 08:52:21 +0000429/// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
430///
431bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
Evan Cheng7e073ba2008-04-09 20:57:25 +0000432 unsigned DstReg) const {
Evan Cheng8fc9a102007-11-06 08:52:21 +0000433 MachineBasicBlock *MBB = CopyMI->getParent();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000434 const MachineLoop *L = loopInfo->getLoopFor(MBB);
Evan Cheng8fc9a102007-11-06 08:52:21 +0000435 if (!L)
436 return false;
Evan Cheng22f07ff2007-12-11 02:09:15 +0000437 if (MBB != L->getLoopLatch())
Evan Cheng8fc9a102007-11-06 08:52:21 +0000438 return false;
439
Evan Cheng8fc9a102007-11-06 08:52:21 +0000440 LiveInterval &LI = li_->getInterval(DstReg);
441 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
442 LiveInterval::const_iterator DstLR =
443 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
444 if (DstLR == LI.end())
445 return false;
Owen Andersonb3db9c92008-06-23 22:12:23 +0000446 unsigned KillIdx = li_->getMBBEndIdx(MBB) + 1;
Evan Cheng70071432008-02-13 03:01:43 +0000447 if (DstLR->valno->kills.size() == 1 &&
448 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
Evan Cheng8fc9a102007-11-06 08:52:21 +0000449 return true;
450 return false;
451}
452
Evan Chengc8d044e2008-02-15 18:24:29 +0000453/// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
454/// update the subregister number if it is not zero. If DstReg is a
455/// physical register and the existing subregister number of the def / use
456/// being updated is not zero, make sure to set it to the correct physical
457/// subregister.
458void
459SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
460 unsigned SubIdx) {
461 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
462 if (DstIsPhys && SubIdx) {
463 // Figure out the real physical register we are updating with.
464 DstReg = tri_->getSubReg(DstReg, SubIdx);
465 SubIdx = 0;
466 }
467
468 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
469 E = mri_->reg_end(); I != E; ) {
470 MachineOperand &O = I.getOperand();
Evan Cheng70366b92008-03-21 19:09:30 +0000471 MachineInstr *UseMI = &*I;
Evan Chengc8d044e2008-02-15 18:24:29 +0000472 ++I;
Evan Cheng621d1572008-04-17 00:06:42 +0000473 unsigned OldSubIdx = O.getSubReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000474 if (DstIsPhys) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000475 unsigned UseDstReg = DstReg;
Evan Cheng621d1572008-04-17 00:06:42 +0000476 if (OldSubIdx)
477 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
Evan Chengc8d044e2008-02-15 18:24:29 +0000478 O.setReg(UseDstReg);
479 O.setSubReg(0);
480 } else {
Evan Chengc886c462008-02-26 08:03:41 +0000481 // Sub-register indexes goes from small to large. e.g.
Evan Chenga8f720d2008-04-18 19:25:26 +0000482 // RAX: 1 -> AL, 2 -> AX, 3 -> EAX
483 // EAX: 1 -> AL, 2 -> AX
Evan Chengc886c462008-02-26 08:03:41 +0000484 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
485 // sub-register 2 is also AX.
486 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
487 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
488 else if (SubIdx)
Evan Chengc8d044e2008-02-15 18:24:29 +0000489 O.setSubReg(SubIdx);
Evan Cheng70366b92008-03-21 19:09:30 +0000490 // Remove would-be duplicated kill marker.
491 if (O.isKill() && UseMI->killsRegister(DstReg))
492 O.setIsKill(false);
Evan Chengc8d044e2008-02-15 18:24:29 +0000493 O.setReg(DstReg);
494 }
495 }
496}
497
Evan Cheng7e073ba2008-04-09 20:57:25 +0000498/// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
499/// registers due to insert_subreg coalescing. e.g.
500/// r1024 = op
501/// r1025 = implicit_def
502/// r1025 = insert_subreg r1025, r1024
503/// = op r1025
504/// =>
505/// r1025 = op
506/// r1025 = implicit_def
507/// r1025 = insert_subreg r1025, r1025
508/// = op r1025
509void
510SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
511 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
512 E = mri_->reg_end(); I != E; ) {
513 MachineOperand &O = I.getOperand();
514 MachineInstr *DefMI = &*I;
515 ++I;
516 if (!O.isDef())
517 continue;
518 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
519 continue;
520 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
521 continue;
522 li_->RemoveMachineInstrFromMaps(DefMI);
523 DefMI->eraseFromParent();
524 }
525}
526
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000527/// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
528/// due to live range lengthening as the result of coalescing.
529void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
530 LiveInterval &LI) {
531 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
532 UE = mri_->use_end(); UI != UE; ++UI) {
533 MachineOperand &UseMO = UI.getOperand();
534 if (UseMO.isKill()) {
535 MachineInstr *UseMI = UseMO.getParent();
536 unsigned SReg, DReg;
537 if (!tii_->isMoveInstr(*UseMI, SReg, DReg))
538 continue;
539 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
540 if (JoinedCopies.count(UseMI))
541 continue;
Evan Chengff7a3e52008-04-16 18:48:43 +0000542 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000543 if (!LI.isKill(UI->valno, UseIdx+1))
544 UseMO.setIsKill(false);
545 }
546 }
547}
548
Evan Cheng3c88d742008-03-18 08:26:47 +0000549/// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
550/// from a physical register live interval as well as from the live intervals
551/// of its sub-registers.
552static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
553 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
554 li.removeRange(Start, End, true);
555 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
556 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
557 if (!li_->hasInterval(*SR))
558 continue;
559 LiveInterval &sli = li_->getInterval(*SR);
560 unsigned RemoveEnd = Start;
561 while (RemoveEnd != End) {
562 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
563 if (LR == sli.end())
564 break;
565 RemoveEnd = (LR->end < End) ? LR->end : End;
566 sli.removeRange(Start, RemoveEnd, true);
567 Start = RemoveEnd;
568 }
569 }
570 }
571}
572
573/// removeIntervalIfEmpty - Check if the live interval of a physical register
574/// is empty, if so remove it and also remove the empty intervals of its
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000575/// sub-registers. Return true if live interval is removed.
576static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
Evan Cheng3c88d742008-03-18 08:26:47 +0000577 const TargetRegisterInfo *tri_) {
578 if (li.empty()) {
Evan Cheng3c88d742008-03-18 08:26:47 +0000579 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
580 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
581 if (!li_->hasInterval(*SR))
582 continue;
583 LiveInterval &sli = li_->getInterval(*SR);
584 if (sli.empty())
585 li_->removeInterval(*SR);
586 }
Evan Chengd94950c2008-04-16 01:22:28 +0000587 li_->removeInterval(li.reg);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000588 return true;
Evan Cheng3c88d742008-03-18 08:26:47 +0000589 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000590 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000591}
592
593/// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000594/// Return true if live interval is removed.
595bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
Evan Chengecb2a8b2008-03-05 22:09:42 +0000596 MachineInstr *CopyMI) {
597 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
598 LiveInterval::iterator MLR =
599 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
Evan Cheng3c88d742008-03-18 08:26:47 +0000600 if (MLR == li.end())
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000601 return false; // Already removed by ShortenDeadCopySrcLiveRange.
Evan Chengecb2a8b2008-03-05 22:09:42 +0000602 unsigned RemoveStart = MLR->start;
603 unsigned RemoveEnd = MLR->end;
Evan Cheng3c88d742008-03-18 08:26:47 +0000604 // Remove the liverange that's defined by this.
605 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
606 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000607 return removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000608 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000609 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000610}
611
Evan Cheng0c284322008-03-26 20:15:49 +0000612/// PropagateDeadness - Propagate the dead marker to the instruction which
613/// defines the val#.
614static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
615 unsigned &LRStart, LiveIntervals *li_,
616 const TargetRegisterInfo* tri_) {
617 MachineInstr *DefMI =
618 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
619 if (DefMI && DefMI != CopyMI) {
620 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
621 if (DeadIdx != -1) {
622 DefMI->getOperand(DeadIdx).setIsDead();
623 // A dead def should have a single cycle interval.
624 ++LRStart;
625 }
626 }
627}
628
Evan Cheng883d2602008-04-18 19:22:23 +0000629/// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
630/// fallthoughs to SuccMBB.
631static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
632 MachineBasicBlock *SuccMBB,
633 const TargetInstrInfo *tii_) {
634 if (MBB == SuccMBB)
635 return true;
636 MachineBasicBlock *TBB = 0, *FBB = 0;
637 std::vector<MachineOperand> Cond;
638 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
639 MBB->isSuccessor(SuccMBB);
640}
641
Bill Wendlingf2317782008-04-17 05:20:39 +0000642/// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
643/// extended by a dead copy. Mark the last use (if any) of the val# as kill as
644/// ends the live range there. If there isn't another use, then this live range
645/// is dead. Return true if live interval is removed.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000646bool
Evan Cheng3c88d742008-03-18 08:26:47 +0000647SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
648 MachineInstr *CopyMI) {
649 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
650 if (CopyIdx == 0) {
651 // FIXME: special case: function live in. It can be a general case if the
652 // first instruction index starts at > 0 value.
653 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
654 // Live-in to the function but dead. Remove it from entry live-in set.
Evan Chenga971dbd2008-04-24 09:06:33 +0000655 if (mf_->begin()->isLiveIn(li.reg))
656 mf_->begin()->removeLiveIn(li.reg);
Evan Chengff7a3e52008-04-16 18:48:43 +0000657 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
Evan Cheng3c88d742008-03-18 08:26:47 +0000658 removeRange(li, LR->start, LR->end, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000659 return removeIntervalIfEmpty(li, li_, tri_);
Evan Cheng3c88d742008-03-18 08:26:47 +0000660 }
661
662 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
663 if (LR == li.end())
664 // Livein but defined by a phi.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000665 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000666
667 unsigned RemoveStart = LR->start;
668 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
669 if (LR->end > RemoveEnd)
670 // More uses past this copy? Nothing to do.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000671 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000672
Evan Cheng883d2602008-04-18 19:22:23 +0000673 MachineBasicBlock *CopyMBB = CopyMI->getParent();
674 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
Evan Cheng3c88d742008-03-18 08:26:47 +0000675 unsigned LastUseIdx;
Evan Chengd2012d02008-04-10 23:48:35 +0000676 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
677 LastUseIdx);
Evan Cheng3c88d742008-03-18 08:26:47 +0000678 if (LastUse) {
Evan Cheng883d2602008-04-18 19:22:23 +0000679 MachineInstr *LastUseMI = LastUse->getParent();
680 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
681 // r1024 = op
682 // ...
683 // BB1:
684 // = r1024
685 //
686 // BB2:
687 // r1025<dead> = r1024<kill>
688 if (MBBStart < LR->end)
689 removeRange(li, MBBStart, LR->end, li_, tri_);
690 return false;
691 }
692
Evan Cheng3c88d742008-03-18 08:26:47 +0000693 // There are uses before the copy, just shorten the live range to the end
694 // of last use.
695 LastUse->setIsKill();
Evan Cheng3c88d742008-03-18 08:26:47 +0000696 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
697 unsigned SrcReg, DstReg;
698 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
699 DstReg == li.reg) {
700 // Last use is itself an identity code.
701 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
702 LastUseMI->getOperand(DeadIdx).setIsDead();
703 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000704 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000705 }
706
707 // Is it livein?
Evan Cheng3c88d742008-03-18 08:26:47 +0000708 if (LR->start <= MBBStart && LR->end > MBBStart) {
709 if (LR->start == 0) {
710 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
711 // Live-in to the function but dead. Remove it from entry live-in set.
712 mf_->begin()->removeLiveIn(li.reg);
713 }
Evan Cheng3c88d742008-03-18 08:26:47 +0000714 // FIXME: Shorten intervals in BBs that reaches this BB.
Evan Cheng3c88d742008-03-18 08:26:47 +0000715 }
716
Evan Cheng0c284322008-03-26 20:15:49 +0000717 if (LR->valno->def == RemoveStart)
718 // If the def MI defines the val#, propagate the dead marker.
719 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
720
721 removeRange(li, RemoveStart, LR->end, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000722 return removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000723}
724
Evan Cheng7e073ba2008-04-09 20:57:25 +0000725/// CanCoalesceWithImpDef - Returns true if the specified copy instruction
726/// from an implicit def to another register can be coalesced away.
727bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
728 LiveInterval &li,
729 LiveInterval &ImpLi) const{
730 if (!CopyMI->killsRegister(ImpLi.reg))
731 return false;
732 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
733 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
734 if (LR == li.end())
735 return false;
736 if (LR->valno->hasPHIKill)
737 return false;
738 if (LR->valno->def != CopyIdx)
739 return false;
740 // Make sure all of val# uses are copies.
741 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
742 UE = mri_->use_end(); UI != UE;) {
743 MachineInstr *UseMI = &*UI;
744 ++UI;
745 if (JoinedCopies.count(UseMI))
746 continue;
747 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
748 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000749 if (ULR == li.end() || ULR->valno != LR->valno)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000750 continue;
751 // If the use is not a use, then it's not safe to coalesce the move.
752 unsigned SrcReg, DstReg;
753 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg)) {
754 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
755 UseMI->getOperand(1).getReg() == li.reg)
756 continue;
757 return false;
758 }
759 }
760 return true;
761}
762
763
764/// RemoveCopiesFromValNo - The specified value# is defined by an implicit
765/// def and it is being removed. Turn all copies from this value# into
766/// identity copies so they will be removed.
767void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
768 VNInfo *VNI) {
Evan Chengd77d4f92008-05-28 17:40:10 +0000769 SmallVector<MachineInstr*, 4> ImpDefs;
Evan Chengd2012d02008-04-10 23:48:35 +0000770 MachineOperand *LastUse = NULL;
771 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
772 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
773 RE = mri_->reg_end(); RI != RE;) {
774 MachineOperand *MO = &RI.getOperand();
775 MachineInstr *MI = &*RI;
776 ++RI;
777 if (MO->isDef()) {
778 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Chengd77d4f92008-05-28 17:40:10 +0000779 ImpDefs.push_back(MI);
Evan Chengd2012d02008-04-10 23:48:35 +0000780 }
Evan Cheng7e073ba2008-04-09 20:57:25 +0000781 continue;
Evan Chengd2012d02008-04-10 23:48:35 +0000782 }
783 if (JoinedCopies.count(MI))
784 continue;
785 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
Evan Cheng7e073ba2008-04-09 20:57:25 +0000786 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000787 if (ULR == li.end() || ULR->valno != VNI)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000788 continue;
Evan Cheng7e073ba2008-04-09 20:57:25 +0000789 // If the use is a copy, turn it into an identity copy.
790 unsigned SrcReg, DstReg;
Evan Chengd2012d02008-04-10 23:48:35 +0000791 if (tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == li.reg) {
792 // Each use MI may have multiple uses of this register. Change them all.
793 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
794 MachineOperand &MO = MI->getOperand(i);
795 if (MO.isReg() && MO.getReg() == li.reg)
796 MO.setReg(DstReg);
797 }
798 JoinedCopies.insert(MI);
799 } else if (UseIdx > LastUseIdx) {
800 LastUseIdx = UseIdx;
801 LastUse = MO;
Evan Cheng172b70c2008-04-10 18:38:47 +0000802 }
Evan Chengd2012d02008-04-10 23:48:35 +0000803 }
804 if (LastUse)
805 LastUse->setIsKill();
806 else {
Evan Chengd77d4f92008-05-28 17:40:10 +0000807 // Remove dead implicit_def's.
808 while (!ImpDefs.empty()) {
809 MachineInstr *ImpDef = ImpDefs.back();
810 ImpDefs.pop_back();
811 li_->RemoveMachineInstrFromMaps(ImpDef);
812 ImpDef->eraseFromParent();
813 }
Evan Cheng7e073ba2008-04-09 20:57:25 +0000814 }
815}
816
817static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
818 const TargetRegisterClass *RC,
819 const TargetRegisterInfo* TRI) {
820 for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
821 unsigned SR = *SRs; ++SRs)
822 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
823 return SR;
824 return 0;
825}
826
Evan Chenge00f5de2008-06-19 01:39:21 +0000827/// isProfitableToCoalesceToSubRC - Given that register class of DstReg is
828/// a subset of the register class of SrcReg, return true if it's profitable
829/// to coalesce the two registers.
830bool
831SimpleRegisterCoalescing::isProfitableToCoalesceToSubRC(unsigned SrcReg,
832 unsigned DstReg,
833 MachineBasicBlock *MBB){
834 if (!CrossClassJoin)
835 return false;
836
837 // First let's make sure all uses are in the same MBB.
838 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(SrcReg),
839 RE = mri_->reg_end(); RI != RE; ++RI) {
840 MachineInstr &MI = *RI;
841 if (MI.getParent() != MBB)
842 return false;
843 }
844 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(DstReg),
845 RE = mri_->reg_end(); RI != RE; ++RI) {
846 MachineInstr &MI = *RI;
847 if (MI.getParent() != MBB)
848 return false;
849 }
850
851 // Then make sure the intervals are *short*.
852 LiveInterval &SrcInt = li_->getInterval(SrcReg);
853 LiveInterval &DstInt = li_->getInterval(DstReg);
Owen Andersona1566f22008-07-22 22:46:49 +0000854 unsigned SrcSize = li_->getApproximateInstructionCount(SrcInt);
855 unsigned DstSize = li_->getApproximateInstructionCount(DstInt);
Evan Chenge00f5de2008-06-19 01:39:21 +0000856 const TargetRegisterClass *RC = mri_->getRegClass(DstReg);
857 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
858 return (SrcSize + DstSize) <= Threshold;
859}
860
861
David Greene25133302007-06-08 17:18:56 +0000862/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
863/// which are the src/dst of the copy instruction CopyMI. This returns true
Evan Cheng0547bab2007-11-01 06:22:48 +0000864/// if the copy was successfully coalesced away. If it is not currently
865/// possible to coalesce this interval, but it may be possible if other
866/// things get coalesced, then it returns true by reference in 'Again'.
Evan Cheng70071432008-02-13 03:01:43 +0000867bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
Evan Cheng8fc9a102007-11-06 08:52:21 +0000868 MachineInstr *CopyMI = TheCopy.MI;
869
870 Again = false;
871 if (JoinedCopies.count(CopyMI))
872 return false; // Already done.
873
David Greene25133302007-06-08 17:18:56 +0000874 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
875
Evan Chengc8d044e2008-02-15 18:24:29 +0000876 unsigned SrcReg;
877 unsigned DstReg;
878 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
Evan Cheng7e073ba2008-04-09 20:57:25 +0000879 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
Evan Chengc8d044e2008-02-15 18:24:29 +0000880 unsigned SubIdx = 0;
881 if (isExtSubReg) {
882 DstReg = CopyMI->getOperand(0).getReg();
883 SrcReg = CopyMI->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000884 } else if (isInsSubReg) {
885 if (CopyMI->getOperand(2).getSubReg()) {
886 DOUT << "\tSource of insert_subreg is already coalesced "
887 << "to another register.\n";
888 return false; // Not coalescable.
889 }
890 DstReg = CopyMI->getOperand(0).getReg();
891 SrcReg = CopyMI->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000892 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
893 assert(0 && "Unrecognized copy instruction!");
894 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000895 }
896
David Greene25133302007-06-08 17:18:56 +0000897 // If they are already joined we continue.
Evan Chengc8d044e2008-02-15 18:24:29 +0000898 if (SrcReg == DstReg) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000899 DOUT << "\tCopy already coalesced.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000900 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000901 }
902
Evan Chengc8d044e2008-02-15 18:24:29 +0000903 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
904 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
David Greene25133302007-06-08 17:18:56 +0000905
906 // If they are both physical registers, we cannot join them.
907 if (SrcIsPhys && DstIsPhys) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000908 DOUT << "\tCan not coalesce physregs.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000909 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000910 }
911
912 // We only join virtual registers with allocatable physical registers.
Evan Chengc8d044e2008-02-15 18:24:29 +0000913 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
David Greene25133302007-06-08 17:18:56 +0000914 DOUT << "\tSrc reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000915 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000916 }
Evan Chengc8d044e2008-02-15 18:24:29 +0000917 if (DstIsPhys && !allocatableRegs_[DstReg]) {
David Greene25133302007-06-08 17:18:56 +0000918 DOUT << "\tDst reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000919 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000920 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000921
Evan Chenge00f5de2008-06-19 01:39:21 +0000922 // Should be non-null only when coalescing to a sub-register class.
923 const TargetRegisterClass *SubRC = NULL;
924 MachineBasicBlock *CopyMBB = CopyMI->getParent();
Evan Cheng32dfbea2007-10-12 08:50:34 +0000925 unsigned RealDstReg = 0;
Evan Cheng7e073ba2008-04-09 20:57:25 +0000926 unsigned RealSrcReg = 0;
927 if (isExtSubReg || isInsSubReg) {
928 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
929 if (SrcIsPhys && isExtSubReg) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000930 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
931 // coalesced with AX.
Evan Cheng621d1572008-04-17 00:06:42 +0000932 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
Evan Cheng639f4932008-04-17 07:58:04 +0000933 if (DstSubIdx) {
934 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
935 // coalesced to a larger register so the subreg indices cancel out.
936 if (DstSubIdx != SubIdx) {
937 DOUT << "\t Sub-register indices mismatch.\n";
938 return false; // Not coalescable.
939 }
940 } else
Evan Cheng621d1572008-04-17 00:06:42 +0000941 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
Evan Chengc8d044e2008-02-15 18:24:29 +0000942 SubIdx = 0;
Evan Cheng7e073ba2008-04-09 20:57:25 +0000943 } else if (DstIsPhys && isInsSubReg) {
944 // EAX = INSERT_SUBREG EAX, r1024, 0
Evan Cheng621d1572008-04-17 00:06:42 +0000945 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
Evan Cheng639f4932008-04-17 07:58:04 +0000946 if (SrcSubIdx) {
947 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
948 // coalesced to a larger register so the subreg indices cancel out.
949 if (SrcSubIdx != SubIdx) {
950 DOUT << "\t Sub-register indices mismatch.\n";
951 return false; // Not coalescable.
952 }
953 } else
954 DstReg = tri_->getSubReg(DstReg, SubIdx);
Evan Cheng7e073ba2008-04-09 20:57:25 +0000955 SubIdx = 0;
956 } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000957 // If this is a extract_subreg where dst is a physical register, e.g.
958 // cl = EXTRACT_SUBREG reg1024, 1
959 // then create and update the actual physical register allocated to RHS.
Evan Cheng7e073ba2008-04-09 20:57:25 +0000960 // Ditto for
961 // reg1024 = INSERT_SUBREG r1024, cl, 1
Evan Cheng639f4932008-04-17 07:58:04 +0000962 if (CopyMI->getOperand(1).getSubReg()) {
963 DOUT << "\tSrc of extract_ / insert_subreg already coalesced with reg"
964 << " of a super-class.\n";
965 return false; // Not coalescable.
966 }
Evan Cheng7e073ba2008-04-09 20:57:25 +0000967 const TargetRegisterClass *RC =
968 mri_->getRegClass(isExtSubReg ? SrcReg : DstReg);
969 if (isExtSubReg) {
970 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
971 assert(RealDstReg && "Invalid extra_subreg instruction!");
972 } else {
973 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
974 assert(RealSrcReg && "Invalid extra_subreg instruction!");
Evan Cheng32dfbea2007-10-12 08:50:34 +0000975 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000976
977 // For this type of EXTRACT_SUBREG, conservatively
978 // check if the live interval of the source register interfere with the
979 // actual super physical register we are trying to coalesce with.
Evan Cheng7e073ba2008-04-09 20:57:25 +0000980 unsigned PhysReg = isExtSubReg ? RealDstReg : RealSrcReg;
981 LiveInterval &RHS = li_->getInterval(isExtSubReg ? SrcReg : DstReg);
982 if (li_->hasInterval(PhysReg) &&
983 RHS.overlaps(li_->getInterval(PhysReg))) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000984 DOUT << "Interfere with register ";
Evan Cheng7e073ba2008-04-09 20:57:25 +0000985 DEBUG(li_->getInterval(PhysReg).print(DOUT, tri_));
Evan Cheng0547bab2007-11-01 06:22:48 +0000986 return false; // Not coalescable
Evan Cheng32dfbea2007-10-12 08:50:34 +0000987 }
Evan Cheng7e073ba2008-04-09 20:57:25 +0000988 for (const unsigned* SR = tri_->getSubRegisters(PhysReg); *SR; ++SR)
Evan Cheng32dfbea2007-10-12 08:50:34 +0000989 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
990 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000991 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
Evan Cheng0547bab2007-11-01 06:22:48 +0000992 return false; // Not coalescable
Evan Cheng32dfbea2007-10-12 08:50:34 +0000993 }
Evan Chengc8d044e2008-02-15 18:24:29 +0000994 SubIdx = 0;
Evan Cheng0547bab2007-11-01 06:22:48 +0000995 } else {
Evan Cheng639f4932008-04-17 07:58:04 +0000996 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
997 : CopyMI->getOperand(2).getSubReg();
998 if (OldSubIdx) {
Evan Chenge00f5de2008-06-19 01:39:21 +0000999 if (OldSubIdx == SubIdx &&
1000 !differingRegisterClasses(SrcReg, DstReg, SubRC))
Evan Cheng639f4932008-04-17 07:58:04 +00001001 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
1002 // coalesced to a larger register so the subreg indices cancel out.
Evan Cheng8509fcf2008-04-29 01:41:44 +00001003 // Also check if the other larger register is of the same register
1004 // class as the would be resulting register.
Evan Cheng639f4932008-04-17 07:58:04 +00001005 SubIdx = 0;
1006 else {
1007 DOUT << "\t Sub-register indices mismatch.\n";
1008 return false; // Not coalescable.
1009 }
1010 }
1011 if (SubIdx) {
1012 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
1013 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
Owen Andersona1566f22008-07-22 22:46:49 +00001014 unsigned LargeRegSize =
1015 li_->getApproximateInstructionCount(li_->getInterval(LargeReg));
1016 unsigned SmallRegSize =
1017 li_->getApproximateInstructionCount(li_->getInterval(SmallReg));
Evan Cheng639f4932008-04-17 07:58:04 +00001018 const TargetRegisterClass *RC = mri_->getRegClass(SmallReg);
1019 unsigned Threshold = allocatableRCRegs_[RC].count();
1020 // Be conservative. If both sides are virtual registers, do not coalesce
1021 // if this will cause a high use density interval to target a smaller
1022 // set of registers.
1023 if (SmallRegSize > Threshold || LargeRegSize > Threshold) {
Owen Andersondbb81372008-05-30 22:37:27 +00001024 if ((float)std::distance(mri_->use_begin(SmallReg),
1025 mri_->use_end()) / SmallRegSize <
1026 (float)std::distance(mri_->use_begin(LargeReg),
1027 mri_->use_end()) / LargeRegSize) {
Evan Cheng639f4932008-04-17 07:58:04 +00001028 Again = true; // May be possible to coalesce later.
1029 return false;
1030 }
Evan Cheng0547bab2007-11-01 06:22:48 +00001031 }
1032 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001033 }
Evan Chenge00f5de2008-06-19 01:39:21 +00001034 } else if (differingRegisterClasses(SrcReg, DstReg, SubRC)) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001035 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
1036 // with another? If it's the resulting destination register, then
1037 // the subidx must be propagated to uses (but only those defined
1038 // by the EXTRACT_SUBREG). If it's being coalesced into another
1039 // register, it should be safe because register is assumed to have
1040 // the register class of the super-register.
1041
Evan Chenge00f5de2008-06-19 01:39:21 +00001042 if (!SubRC || !isProfitableToCoalesceToSubRC(SrcReg, DstReg, CopyMBB)) {
1043 // If they are not of the same register class, we cannot join them.
1044 DOUT << "\tSrc/Dest are different register classes.\n";
1045 // Allow the coalescer to try again in case either side gets coalesced to
1046 // a physical register that's compatible with the other side. e.g.
1047 // r1024 = MOV32to32_ r1025
1048 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
1049 Again = true; // May be possible to coalesce later.
1050 return false;
1051 }
David Greene25133302007-06-08 17:18:56 +00001052 }
1053
Evan Chengc8d044e2008-02-15 18:24:29 +00001054 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1055 LiveInterval &DstInt = li_->getInterval(DstReg);
1056 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
David Greene25133302007-06-08 17:18:56 +00001057 "Register mapping is horribly broken!");
1058
Dan Gohman6f0d0242008-02-10 18:45:23 +00001059 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1060 DOUT << " and "; DstInt.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +00001061 DOUT << ": ";
1062
Evan Cheng3c88d742008-03-18 08:26:47 +00001063 // Check if it is necessary to propagate "isDead" property.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001064 if (!isExtSubReg && !isInsSubReg) {
1065 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1066 bool isDead = mopd->isDead();
David Greene25133302007-06-08 17:18:56 +00001067
Evan Cheng7e073ba2008-04-09 20:57:25 +00001068 // We need to be careful about coalescing a source physical register with a
1069 // virtual register. Once the coalescing is done, it cannot be broken and
1070 // these are not spillable! If the destination interval uses are far away,
1071 // think twice about coalescing them!
1072 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1073 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1074 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1075 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1076 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1077 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1078 if (TheCopy.isBackEdge)
1079 Threshold *= 2; // Favors back edge copies.
David Greene25133302007-06-08 17:18:56 +00001080
Evan Cheng7e073ba2008-04-09 20:57:25 +00001081 // If the virtual register live interval is long but it has low use desity,
1082 // do not join them, instead mark the physical register as its allocation
1083 // preference.
Owen Andersona1566f22008-07-22 22:46:49 +00001084 unsigned Length = li_->getApproximateInstructionCount(JoinVInt);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001085 if (Length > Threshold &&
Owen Andersondbb81372008-05-30 22:37:27 +00001086 (((float)std::distance(mri_->use_begin(JoinVReg),
1087 mri_->use_end()) / Length) < (1.0 / Threshold))) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001088 JoinVInt.preference = JoinPReg;
1089 ++numAborts;
1090 DOUT << "\tMay tie down a physical register, abort!\n";
1091 Again = true; // May be possible to coalesce later.
1092 return false;
1093 }
David Greene25133302007-06-08 17:18:56 +00001094 }
1095 }
1096
1097 // Okay, attempt to join these two intervals. On failure, this returns false.
1098 // Otherwise, if one of the intervals being joined is a physreg, this method
1099 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1100 // been modified, so we can use this information below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001101 bool Swapped = false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00001102 // If SrcInt is implicitly defined, it's safe to coalesce.
1103 bool isEmpty = SrcInt.empty();
Evan Cheng7e073ba2008-04-09 20:57:25 +00001104 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
Evan Chengdb9b1c32008-04-03 16:41:54 +00001105 // Only coalesce an empty interval (defined by implicit_def) with
Evan Cheng7e073ba2008-04-09 20:57:25 +00001106 // another interval which has a valno defined by the CopyMI and the CopyMI
1107 // is a kill of the implicit def.
Evan Chengdb9b1c32008-04-03 16:41:54 +00001108 DOUT << "Not profitable!\n";
1109 return false;
1110 }
1111
1112 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001113 // Coalescing failed.
David Greene25133302007-06-08 17:18:56 +00001114
1115 // If we can eliminate the copy without merging the live ranges, do so now.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001116 if (!isExtSubReg && !isInsSubReg &&
Evan Cheng70071432008-02-13 03:01:43 +00001117 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1118 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
Evan Cheng8fc9a102007-11-06 08:52:21 +00001119 JoinedCopies.insert(CopyMI);
David Greene25133302007-06-08 17:18:56 +00001120 return true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001121 }
Evan Cheng70071432008-02-13 03:01:43 +00001122
David Greene25133302007-06-08 17:18:56 +00001123 // Otherwise, we are unable to join the intervals.
1124 DOUT << "Interference!\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001125 Again = true; // May be possible to coalesce later.
David Greene25133302007-06-08 17:18:56 +00001126 return false;
1127 }
1128
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001129 LiveInterval *ResSrcInt = &SrcInt;
1130 LiveInterval *ResDstInt = &DstInt;
1131 if (Swapped) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001132 std::swap(SrcReg, DstReg);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001133 std::swap(ResSrcInt, ResDstInt);
1134 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001135 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
David Greene25133302007-06-08 17:18:56 +00001136 "LiveInterval::join didn't work right!");
1137
1138 // If we're about to merge live ranges into a physical register live range,
1139 // we have to update any aliased register's live ranges to indicate that they
1140 // have clobbered values for this range.
Evan Chengc8d044e2008-02-15 18:24:29 +00001141 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001142 // If this is a extract_subreg where dst is a physical register, e.g.
1143 // cl = EXTRACT_SUBREG reg1024, 1
1144 // then create and update the actual physical register allocated to RHS.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001145 if (RealDstReg || RealSrcReg) {
1146 LiveInterval &RealInt =
1147 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
Evan Chengf5c73592007-10-15 18:33:50 +00001148 SmallSet<const VNInfo*, 4> CopiedValNos;
1149 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1150 E = ResSrcInt->ranges.end(); I != E; ++I) {
Evan Chengff7a3e52008-04-16 18:48:43 +00001151 const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1152 assert(DstLR && "Invalid joined interval!");
Evan Chengf5c73592007-10-15 18:33:50 +00001153 const VNInfo *DstValNo = DstLR->valno;
1154 if (CopiedValNos.insert(DstValNo)) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001155 VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1156 li_->getVNInfoAllocator());
Evan Chengc3fc7d92007-11-29 09:49:23 +00001157 ValNo->hasPHIKill = DstValNo->hasPHIKill;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001158 RealInt.addKills(ValNo, DstValNo->kills);
1159 RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
Evan Chengf5c73592007-10-15 18:33:50 +00001160 }
Evan Cheng34729252007-10-14 10:08:34 +00001161 }
Evan Cheng7e073ba2008-04-09 20:57:25 +00001162
1163 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +00001164 }
1165
David Greene25133302007-06-08 17:18:56 +00001166 // Update the liveintervals of sub-registers.
Evan Chengc8d044e2008-02-15 18:24:29 +00001167 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
Evan Cheng32dfbea2007-10-12 08:50:34 +00001168 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
Evan Chengf3bb2e62007-09-05 21:46:51 +00001169 li_->getVNInfoAllocator());
David Greene25133302007-06-08 17:18:56 +00001170 }
1171
Evan Chengc8d044e2008-02-15 18:24:29 +00001172 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1173 // larger super-register.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001174 if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1175 if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001176 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
Evan Chengc8d044e2008-02-15 18:24:29 +00001177 std::swap(SrcReg, DstReg);
Evan Cheng32dfbea2007-10-12 08:50:34 +00001178 std::swap(ResSrcInt, ResDstInt);
1179 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001180 }
1181
Evan Chenge00f5de2008-06-19 01:39:21 +00001182 // Coalescing to a virtual register that is of a sub-register class of the
1183 // other. Make sure the resulting register is set to the right register class.
1184 if (SubRC) {
1185 mri_->setRegClass(DstReg, SubRC);
1186 ++numSubJoins;
1187 }
1188
Evan Cheng8fc9a102007-11-06 08:52:21 +00001189 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001190 // Add all copies that define val# in the source interval into the queue.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001191 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1192 e = ResSrcInt->vni_end(); i != e; ++i) {
1193 const VNInfo *vni = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001194 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1195 continue;
1196 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1197 unsigned NewSrcReg, NewDstReg;
1198 if (CopyMI &&
1199 JoinedCopies.count(CopyMI) == 0 &&
1200 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
Evan Chenge00f5de2008-06-19 01:39:21 +00001201 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMBB);
Evan Chengc8d044e2008-02-15 18:24:29 +00001202 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1203 isBackEdgeCopy(CopyMI, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001204 }
1205 }
1206 }
1207
Evan Chengc8d044e2008-02-15 18:24:29 +00001208 // Remember to delete the copy instruction.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001209 JoinedCopies.insert(CopyMI);
Evan Chengc8d044e2008-02-15 18:24:29 +00001210
Evan Cheng4ff3f1c2008-03-10 08:11:32 +00001211 // Some live range has been lengthened due to colaescing, eliminate the
1212 // unnecessary kills.
1213 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1214 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1215 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1216
Evan Chengc8d044e2008-02-15 18:24:29 +00001217 // SrcReg is guarateed to be the register whose live interval that is
1218 // being merged.
1219 li_->removeInterval(SrcReg);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001220 if (isInsSubReg)
1221 // Avoid:
1222 // r1024 = op
1223 // r1024 = implicit_def
1224 // ...
1225 // = r1024
1226 RemoveDeadImpDef(DstReg, *ResDstInt);
Evan Chengc8d044e2008-02-15 18:24:29 +00001227 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1228
Evan Chengdb9b1c32008-04-03 16:41:54 +00001229 if (isEmpty) {
1230 // Now the copy is being coalesced away, the val# previously defined
1231 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1232 // length interval. Remove the val#.
1233 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
Evan Chengff7a3e52008-04-16 18:48:43 +00001234 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001235 VNInfo *ImpVal = LR->valno;
1236 assert(ImpVal->def == CopyIdx);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001237 unsigned NextDef = LR->end;
1238 RemoveCopiesFromValNo(*ResDstInt, ImpVal);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001239 ResDstInt->removeValNo(ImpVal);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001240 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1241 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1242 // Special case: vr1024 = implicit_def
1243 // vr1024 = insert_subreg vr1024, vr1025, c
1244 // The insert_subreg becomes a "copy" that defines a val# which can itself
1245 // be coalesced away.
1246 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1247 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1248 LR->valno->copy = DefMI;
1249 }
Evan Chengdb9b1c32008-04-03 16:41:54 +00001250 }
1251
1252 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1253 DOUT << "\n";
1254
David Greene25133302007-06-08 17:18:56 +00001255 ++numJoins;
1256 return true;
1257}
1258
1259/// ComputeUltimateVN - Assuming we are going to join two live intervals,
1260/// compute what the resultant value numbers for each value in the input two
1261/// ranges will be. This is complicated by copies between the two which can
1262/// and will commonly cause multiple value numbers to be merged into one.
1263///
1264/// VN is the value number that we're trying to resolve. InstDefiningValue
1265/// keeps track of the new InstDefiningValue assignment for the result
1266/// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1267/// whether a value in this or other is a copy from the opposite set.
1268/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1269/// already been assigned.
1270///
1271/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1272/// contains the value number the copy is from.
1273///
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001274static unsigned ComputeUltimateVN(VNInfo *VNI,
1275 SmallVector<VNInfo*, 16> &NewVNInfo,
Evan Chengfadfb5b2007-08-31 21:23:06 +00001276 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1277 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
David Greene25133302007-06-08 17:18:56 +00001278 SmallVector<int, 16> &ThisValNoAssignments,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001279 SmallVector<int, 16> &OtherValNoAssignments) {
1280 unsigned VN = VNI->id;
1281
David Greene25133302007-06-08 17:18:56 +00001282 // If the VN has already been computed, just return it.
1283 if (ThisValNoAssignments[VN] >= 0)
1284 return ThisValNoAssignments[VN];
1285// assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001286
David Greene25133302007-06-08 17:18:56 +00001287 // If this val is not a copy from the other val, then it must be a new value
1288 // number in the destination.
Evan Chengfadfb5b2007-08-31 21:23:06 +00001289 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
Evan Chengc14b1442007-08-31 08:04:17 +00001290 if (I == ThisFromOther.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001291 NewVNInfo.push_back(VNI);
1292 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00001293 }
Evan Chengc14b1442007-08-31 08:04:17 +00001294 VNInfo *OtherValNo = I->second;
David Greene25133302007-06-08 17:18:56 +00001295
1296 // Otherwise, this *is* a copy from the RHS. If the other side has already
1297 // been computed, return it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001298 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1299 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
David Greene25133302007-06-08 17:18:56 +00001300
1301 // Mark this value number as currently being computed, then ask what the
1302 // ultimate value # of the other value is.
1303 ThisValNoAssignments[VN] = -2;
1304 unsigned UltimateVN =
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001305 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1306 OtherValNoAssignments, ThisValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001307 return ThisValNoAssignments[VN] = UltimateVN;
1308}
1309
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001310static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
David Greene25133302007-06-08 17:18:56 +00001311 return std::find(V.begin(), V.end(), Val) != V.end();
1312}
1313
Evan Cheng7e073ba2008-04-09 20:57:25 +00001314/// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1315/// the specified live interval is defined by a copy from the specified
1316/// register.
1317bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1318 LiveRange *LR,
1319 unsigned Reg) {
1320 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1321 if (SrcReg == Reg)
1322 return true;
1323 if (LR->valno->def == ~0U &&
1324 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1325 *tri_->getSuperRegisters(li.reg)) {
1326 // It's a sub-register live interval, we may not have precise information.
1327 // Re-compute it.
1328 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1329 unsigned SrcReg, DstReg;
Evan Cheng76a4d582008-07-17 19:48:53 +00001330 if (DefMI && tii_->isMoveInstr(*DefMI, SrcReg, DstReg) &&
Evan Cheng7e073ba2008-04-09 20:57:25 +00001331 DstReg == li.reg && SrcReg == Reg) {
1332 // Cache computed info.
1333 LR->valno->def = LR->start;
1334 LR->valno->copy = DefMI;
1335 return true;
1336 }
1337 }
1338 return false;
1339}
1340
David Greene25133302007-06-08 17:18:56 +00001341/// SimpleJoin - Attempt to joint the specified interval into this one. The
1342/// caller of this method must guarantee that the RHS only contains a single
1343/// value number and that the RHS is not defined by a copy from this
1344/// interval. This returns false if the intervals are not joinable, or it
1345/// joins them and returns true.
Bill Wendling2674d712008-01-04 08:59:18 +00001346bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
David Greene25133302007-06-08 17:18:56 +00001347 assert(RHS.containsOneValue());
1348
1349 // Some number (potentially more than one) value numbers in the current
1350 // interval may be defined as copies from the RHS. Scan the overlapping
1351 // portions of the LHS and RHS, keeping track of this and looking for
1352 // overlapping live ranges that are NOT defined as copies. If these exist, we
Gabor Greife510b3a2007-07-09 12:00:59 +00001353 // cannot coalesce.
David Greene25133302007-06-08 17:18:56 +00001354
1355 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1356 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1357
1358 if (LHSIt->start < RHSIt->start) {
1359 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1360 if (LHSIt != LHS.begin()) --LHSIt;
1361 } else if (RHSIt->start < LHSIt->start) {
1362 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1363 if (RHSIt != RHS.begin()) --RHSIt;
1364 }
1365
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001366 SmallVector<VNInfo*, 8> EliminatedLHSVals;
David Greene25133302007-06-08 17:18:56 +00001367
1368 while (1) {
1369 // Determine if these live intervals overlap.
1370 bool Overlaps = false;
1371 if (LHSIt->start <= RHSIt->start)
1372 Overlaps = LHSIt->end > RHSIt->start;
1373 else
1374 Overlaps = RHSIt->end > LHSIt->start;
1375
1376 // If the live intervals overlap, there are two interesting cases: if the
1377 // LHS interval is defined by a copy from the RHS, it's ok and we record
1378 // that the LHS value # is the same as the RHS. If it's not, then we cannot
Gabor Greife510b3a2007-07-09 12:00:59 +00001379 // coalesce these live ranges and we bail out.
David Greene25133302007-06-08 17:18:56 +00001380 if (Overlaps) {
1381 // If we haven't already recorded that this value # is safe, check it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001382 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001383 // Copy from the RHS?
Evan Cheng7e073ba2008-04-09 20:57:25 +00001384 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
David Greene25133302007-06-08 17:18:56 +00001385 return false; // Nope, bail out.
Evan Chengf4ea5102008-05-21 22:34:12 +00001386
1387 if (LHSIt->contains(RHSIt->valno->def))
1388 // Here is an interesting situation:
1389 // BB1:
1390 // vr1025 = copy vr1024
1391 // ..
1392 // BB2:
1393 // vr1024 = op
1394 // = vr1025
1395 // Even though vr1025 is copied from vr1024, it's not safe to
1396 // coalesced them since live range of vr1025 intersects the
1397 // def of vr1024. This happens because vr1025 is assigned the
1398 // value of the previous iteration of vr1024.
1399 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001400 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001401 }
1402
1403 // We know this entire LHS live range is okay, so skip it now.
1404 if (++LHSIt == LHSEnd) break;
1405 continue;
1406 }
1407
1408 if (LHSIt->end < RHSIt->end) {
1409 if (++LHSIt == LHSEnd) break;
1410 } else {
1411 // One interesting case to check here. It's possible that we have
1412 // something like "X3 = Y" which defines a new value number in the LHS,
1413 // and is the last use of this liverange of the RHS. In this case, we
Gabor Greife510b3a2007-07-09 12:00:59 +00001414 // want to notice this copy (so that it gets coalesced away) even though
David Greene25133302007-06-08 17:18:56 +00001415 // the live ranges don't actually overlap.
1416 if (LHSIt->start == RHSIt->end) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001417 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001418 // We already know that this value number is going to be merged in
Gabor Greife510b3a2007-07-09 12:00:59 +00001419 // if coalescing succeeds. Just skip the liverange.
David Greene25133302007-06-08 17:18:56 +00001420 if (++LHSIt == LHSEnd) break;
1421 } else {
1422 // Otherwise, if this is a copy from the RHS, mark it as being merged
1423 // in.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001424 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
Evan Chengf4ea5102008-05-21 22:34:12 +00001425 if (LHSIt->contains(RHSIt->valno->def))
1426 // Here is an interesting situation:
1427 // BB1:
1428 // vr1025 = copy vr1024
1429 // ..
1430 // BB2:
1431 // vr1024 = op
1432 // = vr1025
1433 // Even though vr1025 is copied from vr1024, it's not safe to
1434 // coalesced them since live range of vr1025 intersects the
1435 // def of vr1024. This happens because vr1025 is assigned the
1436 // value of the previous iteration of vr1024.
1437 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001438 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001439
1440 // We know this entire LHS live range is okay, so skip it now.
1441 if (++LHSIt == LHSEnd) break;
1442 }
1443 }
1444 }
1445
1446 if (++RHSIt == RHSEnd) break;
1447 }
1448 }
1449
Gabor Greife510b3a2007-07-09 12:00:59 +00001450 // If we got here, we know that the coalescing will be successful and that
David Greene25133302007-06-08 17:18:56 +00001451 // the value numbers in EliminatedLHSVals will all be merged together. Since
1452 // the most common case is that EliminatedLHSVals has a single number, we
1453 // optimize for it: if there is more than one value, we merge them all into
1454 // the lowest numbered one, then handle the interval as if we were merging
1455 // with one value number.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001456 VNInfo *LHSValNo;
David Greene25133302007-06-08 17:18:56 +00001457 if (EliminatedLHSVals.size() > 1) {
1458 // Loop through all the equal value numbers merging them into the smallest
1459 // one.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001460 VNInfo *Smallest = EliminatedLHSVals[0];
David Greene25133302007-06-08 17:18:56 +00001461 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001462 if (EliminatedLHSVals[i]->id < Smallest->id) {
David Greene25133302007-06-08 17:18:56 +00001463 // Merge the current notion of the smallest into the smaller one.
1464 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1465 Smallest = EliminatedLHSVals[i];
1466 } else {
1467 // Merge into the smallest.
1468 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1469 }
1470 }
1471 LHSValNo = Smallest;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001472 } else if (EliminatedLHSVals.empty()) {
1473 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1474 *tri_->getSuperRegisters(LHS.reg))
1475 // Imprecise sub-register information. Can't handle it.
1476 return false;
1477 assert(0 && "No copies from the RHS?");
David Greene25133302007-06-08 17:18:56 +00001478 } else {
David Greene25133302007-06-08 17:18:56 +00001479 LHSValNo = EliminatedLHSVals[0];
1480 }
1481
1482 // Okay, now that there is a single LHS value number that we're merging the
1483 // RHS into, update the value number info for the LHS to indicate that the
1484 // value number is defined where the RHS value number was.
Evan Chengf3bb2e62007-09-05 21:46:51 +00001485 const VNInfo *VNI = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00001486 LHSValNo->def = VNI->def;
1487 LHSValNo->copy = VNI->copy;
David Greene25133302007-06-08 17:18:56 +00001488
1489 // Okay, the final step is to loop over the RHS live intervals, adding them to
1490 // the LHS.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001491 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
Evan Chengf3bb2e62007-09-05 21:46:51 +00001492 LHS.addKills(LHSValNo, VNI->kills);
Evan Cheng430a7b02007-08-14 01:56:58 +00001493 LHS.MergeRangesInAsValue(RHS, LHSValNo);
David Greene25133302007-06-08 17:18:56 +00001494 LHS.weight += RHS.weight;
1495 if (RHS.preference && !LHS.preference)
1496 LHS.preference = RHS.preference;
1497
1498 return true;
1499}
1500
1501/// JoinIntervals - Attempt to join these two intervals. On failure, this
1502/// returns false. Otherwise, if one of the intervals being joined is a
1503/// physreg, this method always canonicalizes LHS to be it. The output
1504/// "RHS" will not have been modified, so we can use this information
1505/// below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001506bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1507 LiveInterval &RHS, bool &Swapped) {
David Greene25133302007-06-08 17:18:56 +00001508 // Compute the final value assignment, assuming that the live ranges can be
Gabor Greife510b3a2007-07-09 12:00:59 +00001509 // coalesced.
David Greene25133302007-06-08 17:18:56 +00001510 SmallVector<int, 16> LHSValNoAssignments;
1511 SmallVector<int, 16> RHSValNoAssignments;
Evan Chengfadfb5b2007-08-31 21:23:06 +00001512 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1513 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001514 SmallVector<VNInfo*, 16> NewVNInfo;
David Greene25133302007-06-08 17:18:56 +00001515
1516 // If a live interval is a physical register, conservatively check if any
1517 // of its sub-registers is overlapping the live interval of the virtual
1518 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001519 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1520 *tri_->getSubRegisters(LHS.reg)) {
1521 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
David Greene25133302007-06-08 17:18:56 +00001522 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1523 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001524 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
David Greene25133302007-06-08 17:18:56 +00001525 return false;
1526 }
Dan Gohman6f0d0242008-02-10 18:45:23 +00001527 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1528 *tri_->getSubRegisters(RHS.reg)) {
1529 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
David Greene25133302007-06-08 17:18:56 +00001530 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1531 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001532 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
David Greene25133302007-06-08 17:18:56 +00001533 return false;
1534 }
1535 }
1536
1537 // Compute ultimate value numbers for the LHS and RHS values.
1538 if (RHS.containsOneValue()) {
1539 // Copies from a liveinterval with a single value are simple to handle and
1540 // very common, handle the special case here. This is important, because
1541 // often RHS is small and LHS is large (e.g. a physreg).
1542
1543 // Find out if the RHS is defined as a copy from some value in the LHS.
Evan Cheng4f8ff162007-08-11 00:59:19 +00001544 int RHSVal0DefinedFromLHS = -1;
David Greene25133302007-06-08 17:18:56 +00001545 int RHSValID = -1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001546 VNInfo *RHSValNoInfo = NULL;
Evan Chengf3bb2e62007-09-05 21:46:51 +00001547 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00001548 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1549 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
David Greene25133302007-06-08 17:18:56 +00001550 // If RHS is not defined as a copy from the LHS, we can use simpler and
Gabor Greife510b3a2007-07-09 12:00:59 +00001551 // faster checks to see if the live ranges are coalescable. This joiner
David Greene25133302007-06-08 17:18:56 +00001552 // can't swap the LHS/RHS intervals though.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001553 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
David Greene25133302007-06-08 17:18:56 +00001554 return SimpleJoin(LHS, RHS);
1555 } else {
Evan Chengc14b1442007-08-31 08:04:17 +00001556 RHSValNoInfo = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00001557 }
1558 } else {
1559 // It was defined as a copy from the LHS, find out what value # it is.
Evan Chengc14b1442007-08-31 08:04:17 +00001560 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001561 RHSValID = RHSValNoInfo->id;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001562 RHSVal0DefinedFromLHS = RHSValID;
David Greene25133302007-06-08 17:18:56 +00001563 }
1564
1565 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1566 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001567 NewVNInfo.resize(LHS.getNumValNums(), NULL);
David Greene25133302007-06-08 17:18:56 +00001568
1569 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1570 // should now get updated.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001571 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1572 i != e; ++i) {
1573 VNInfo *VNI = *i;
1574 unsigned VN = VNI->id;
Evan Chengc8d044e2008-02-15 18:24:29 +00001575 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1576 if (LHSSrcReg != RHS.reg) {
David Greene25133302007-06-08 17:18:56 +00001577 // If this is not a copy from the RHS, its value number will be
Gabor Greife510b3a2007-07-09 12:00:59 +00001578 // unmodified by the coalescing.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001579 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00001580 LHSValNoAssignments[VN] = VN;
1581 } else if (RHSValID == -1) {
1582 // Otherwise, it is a copy from the RHS, and we don't already have a
1583 // value# for it. Keep the current value number, but remember it.
1584 LHSValNoAssignments[VN] = RHSValID = VN;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001585 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00001586 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00001587 } else {
1588 // Otherwise, use the specified value #.
1589 LHSValNoAssignments[VN] = RHSValID;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001590 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1591 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00001592 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001593 }
David Greene25133302007-06-08 17:18:56 +00001594 }
1595 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001596 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00001597 LHSValNoAssignments[VN] = VN;
1598 }
1599 }
1600
1601 assert(RHSValID != -1 && "Didn't find value #?");
1602 RHSValNoAssignments[0] = RHSValID;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001603 if (RHSVal0DefinedFromLHS != -1) {
Evan Cheng34301352007-09-01 02:03:17 +00001604 // This path doesn't go through ComputeUltimateVN so just set
1605 // it to anything.
1606 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001607 }
David Greene25133302007-06-08 17:18:56 +00001608 } else {
1609 // Loop over the value numbers of the LHS, seeing if any are defined from
1610 // the RHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001611 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1612 i != e; ++i) {
1613 VNInfo *VNI = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001614 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00001615 continue;
1616
1617 // DstReg is known to be a register in the LHS interval. If the src is
1618 // from the RHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00001619 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
David Greene25133302007-06-08 17:18:56 +00001620 continue;
1621
1622 // Figure out the value # from the RHS.
Bill Wendling2674d712008-01-04 08:59:18 +00001623 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00001624 }
1625
1626 // Loop over the value numbers of the RHS, seeing if any are defined from
1627 // the LHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001628 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1629 i != e; ++i) {
1630 VNInfo *VNI = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001631 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00001632 continue;
1633
1634 // DstReg is known to be a register in the RHS interval. If the src is
1635 // from the LHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00001636 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
David Greene25133302007-06-08 17:18:56 +00001637 continue;
1638
1639 // Figure out the value # from the LHS.
Bill Wendling2674d712008-01-04 08:59:18 +00001640 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00001641 }
1642
1643 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1644 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001645 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
David Greene25133302007-06-08 17:18:56 +00001646
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001647 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1648 i != e; ++i) {
1649 VNInfo *VNI = *i;
1650 unsigned VN = VNI->id;
1651 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +00001652 continue;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001653 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00001654 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001655 LHSValNoAssignments, RHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001656 }
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001657 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1658 i != e; ++i) {
1659 VNInfo *VNI = *i;
1660 unsigned VN = VNI->id;
1661 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +00001662 continue;
1663 // If this value number isn't a copy from the LHS, it's a new number.
Evan Chengc14b1442007-08-31 08:04:17 +00001664 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001665 NewVNInfo.push_back(VNI);
1666 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00001667 continue;
1668 }
1669
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001670 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00001671 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001672 RHSValNoAssignments, LHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001673 }
1674 }
1675
1676 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
Gabor Greife510b3a2007-07-09 12:00:59 +00001677 // interval lists to see if these intervals are coalescable.
David Greene25133302007-06-08 17:18:56 +00001678 LiveInterval::const_iterator I = LHS.begin();
1679 LiveInterval::const_iterator IE = LHS.end();
1680 LiveInterval::const_iterator J = RHS.begin();
1681 LiveInterval::const_iterator JE = RHS.end();
1682
1683 // Skip ahead until the first place of potential sharing.
1684 if (I->start < J->start) {
1685 I = std::upper_bound(I, IE, J->start);
1686 if (I != LHS.begin()) --I;
1687 } else if (J->start < I->start) {
1688 J = std::upper_bound(J, JE, I->start);
1689 if (J != RHS.begin()) --J;
1690 }
1691
1692 while (1) {
1693 // Determine if these two live ranges overlap.
1694 bool Overlaps;
1695 if (I->start < J->start) {
1696 Overlaps = I->end > J->start;
1697 } else {
1698 Overlaps = J->end > I->start;
1699 }
1700
1701 // If so, check value # info to determine if they are really different.
1702 if (Overlaps) {
1703 // If the live range overlap will map to the same value number in the
Gabor Greife510b3a2007-07-09 12:00:59 +00001704 // result liverange, we can still coalesce them. If not, we can't.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001705 if (LHSValNoAssignments[I->valno->id] !=
1706 RHSValNoAssignments[J->valno->id])
David Greene25133302007-06-08 17:18:56 +00001707 return false;
1708 }
1709
1710 if (I->end < J->end) {
1711 ++I;
1712 if (I == IE) break;
1713 } else {
1714 ++J;
1715 if (J == JE) break;
1716 }
1717 }
1718
Evan Cheng34729252007-10-14 10:08:34 +00001719 // Update kill info. Some live ranges are extended due to copy coalescing.
1720 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1721 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1722 VNInfo *VNI = I->first;
1723 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1724 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +00001725 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +00001726 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1727 }
1728
1729 // Update kill info. Some live ranges are extended due to copy coalescing.
1730 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1731 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1732 VNInfo *VNI = I->first;
1733 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1734 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +00001735 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +00001736 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1737 }
1738
Gabor Greife510b3a2007-07-09 12:00:59 +00001739 // If we get here, we know that we can coalesce the live ranges. Ask the
1740 // intervals to coalesce themselves now.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001741 if ((RHS.ranges.size() > LHS.ranges.size() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00001742 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1743 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001744 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001745 Swapped = true;
1746 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001747 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001748 Swapped = false;
1749 }
David Greene25133302007-06-08 17:18:56 +00001750 return true;
1751}
1752
1753namespace {
1754 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1755 // depth of the basic block (the unsigned), and then on the MBB number.
1756 struct DepthMBBCompare {
1757 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1758 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1759 if (LHS.first > RHS.first) return true; // Deeper loops first
1760 return LHS.first == RHS.first &&
1761 LHS.second->getNumber() < RHS.second->getNumber();
1762 }
1763 };
1764}
1765
Evan Cheng8fc9a102007-11-06 08:52:21 +00001766/// getRepIntervalSize - Returns the size of the interval that represents the
1767/// specified register.
1768template<class SF>
1769unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1770 return Rc->getRepIntervalSize(Reg);
1771}
1772
1773/// CopyRecSort::operator - Join priority queue sorting function.
1774///
1775bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1776 // Inner loops first.
1777 if (left.LoopDepth > right.LoopDepth)
1778 return false;
Evan Chengc8d044e2008-02-15 18:24:29 +00001779 else if (left.LoopDepth == right.LoopDepth)
Evan Cheng8fc9a102007-11-06 08:52:21 +00001780 if (left.isBackEdge && !right.isBackEdge)
1781 return false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001782 return true;
1783}
1784
Gabor Greife510b3a2007-07-09 12:00:59 +00001785void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
Evan Cheng8b0b8742007-10-16 08:04:24 +00001786 std::vector<CopyRec> &TryAgain) {
David Greene25133302007-06-08 17:18:56 +00001787 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Evan Cheng8fc9a102007-11-06 08:52:21 +00001788
Evan Cheng8b0b8742007-10-16 08:04:24 +00001789 std::vector<CopyRec> VirtCopies;
1790 std::vector<CopyRec> PhysCopies;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001791 std::vector<CopyRec> ImpDefCopies;
Evan Cheng22f07ff2007-12-11 02:09:15 +00001792 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
David Greene25133302007-06-08 17:18:56 +00001793 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1794 MII != E;) {
1795 MachineInstr *Inst = MII++;
1796
Evan Cheng32dfbea2007-10-12 08:50:34 +00001797 // If this isn't a copy nor a extract_subreg, we can't join intervals.
David Greene25133302007-06-08 17:18:56 +00001798 unsigned SrcReg, DstReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +00001799 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1800 DstReg = Inst->getOperand(0).getReg();
1801 SrcReg = Inst->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +00001802 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1803 DstReg = Inst->getOperand(0).getReg();
1804 SrcReg = Inst->getOperand(2).getReg();
Evan Cheng32dfbea2007-10-12 08:50:34 +00001805 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1806 continue;
Evan Cheng8b0b8742007-10-16 08:04:24 +00001807
Evan Chengc8d044e2008-02-15 18:24:29 +00001808 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1809 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng8fc9a102007-11-06 08:52:21 +00001810 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001811 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001812 } else {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001813 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1814 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
1815 else if (SrcIsPhys || DstIsPhys)
Evan Chengc8d044e2008-02-15 18:24:29 +00001816 PhysCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001817 else
Evan Chengc8d044e2008-02-15 18:24:29 +00001818 VirtCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001819 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00001820 }
1821
Evan Cheng8fc9a102007-11-06 08:52:21 +00001822 if (NewHeuristic)
1823 return;
1824
Evan Cheng7e073ba2008-04-09 20:57:25 +00001825 // Try coalescing implicit copies first, followed by copies to / from
1826 // physical registers, then finally copies from virtual registers to
1827 // virtual registers.
1828 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1829 CopyRec &TheCopy = ImpDefCopies[i];
1830 bool Again = false;
1831 if (!JoinCopy(TheCopy, Again))
1832 if (Again)
1833 TryAgain.push_back(TheCopy);
1834 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00001835 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1836 CopyRec &TheCopy = PhysCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00001837 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001838 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00001839 if (Again)
1840 TryAgain.push_back(TheCopy);
Evan Cheng8b0b8742007-10-16 08:04:24 +00001841 }
1842 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1843 CopyRec &TheCopy = VirtCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00001844 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001845 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00001846 if (Again)
1847 TryAgain.push_back(TheCopy);
David Greene25133302007-06-08 17:18:56 +00001848 }
1849}
1850
1851void SimpleRegisterCoalescing::joinIntervals() {
1852 DOUT << "********** JOINING INTERVALS ***********\n";
1853
Evan Cheng8fc9a102007-11-06 08:52:21 +00001854 if (NewHeuristic)
1855 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1856
David Greene25133302007-06-08 17:18:56 +00001857 std::vector<CopyRec> TryAgainList;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001858 if (loopInfo->begin() == loopInfo->end()) {
David Greene25133302007-06-08 17:18:56 +00001859 // If there are no loops in the function, join intervals in function order.
1860 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1861 I != E; ++I)
Evan Cheng8b0b8742007-10-16 08:04:24 +00001862 CopyCoalesceInMBB(I, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00001863 } else {
1864 // Otherwise, join intervals in inner loops before other intervals.
1865 // Unfortunately we can't just iterate over loop hierarchy here because
1866 // there may be more MBB's than BB's. Collect MBB's for sorting.
1867
1868 // Join intervals in the function prolog first. We want to join physical
1869 // registers with virtual registers before the intervals got too long.
1870 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
Evan Cheng22f07ff2007-12-11 02:09:15 +00001871 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1872 MachineBasicBlock *MBB = I;
1873 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1874 }
David Greene25133302007-06-08 17:18:56 +00001875
1876 // Sort by loop depth.
1877 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1878
1879 // Finally, join intervals in loop nest order.
1880 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Evan Cheng8b0b8742007-10-16 08:04:24 +00001881 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00001882 }
1883
1884 // Joining intervals can allow other intervals to be joined. Iteratively join
1885 // until we make no progress.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001886 if (NewHeuristic) {
1887 SmallVector<CopyRec, 16> TryAgain;
1888 bool ProgressMade = true;
1889 while (ProgressMade) {
1890 ProgressMade = false;
1891 while (!JoinQueue->empty()) {
1892 CopyRec R = JoinQueue->pop();
Evan Cheng0547bab2007-11-01 06:22:48 +00001893 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001894 bool Success = JoinCopy(R, Again);
1895 if (Success)
Evan Cheng0547bab2007-11-01 06:22:48 +00001896 ProgressMade = true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001897 else if (Again)
1898 TryAgain.push_back(R);
1899 }
1900
1901 if (ProgressMade) {
1902 while (!TryAgain.empty()) {
1903 JoinQueue->push(TryAgain.back());
1904 TryAgain.pop_back();
1905 }
1906 }
1907 }
1908 } else {
1909 bool ProgressMade = true;
1910 while (ProgressMade) {
1911 ProgressMade = false;
1912
1913 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1914 CopyRec &TheCopy = TryAgainList[i];
1915 if (TheCopy.MI) {
1916 bool Again = false;
1917 bool Success = JoinCopy(TheCopy, Again);
1918 if (Success || !Again) {
1919 TheCopy.MI = 0; // Mark this one as done.
1920 ProgressMade = true;
1921 }
Evan Cheng0547bab2007-11-01 06:22:48 +00001922 }
David Greene25133302007-06-08 17:18:56 +00001923 }
1924 }
1925 }
1926
Evan Cheng8fc9a102007-11-06 08:52:21 +00001927 if (NewHeuristic)
Evan Chengc8d044e2008-02-15 18:24:29 +00001928 delete JoinQueue;
David Greene25133302007-06-08 17:18:56 +00001929}
1930
1931/// Return true if the two specified registers belong to different register
Evan Chenge00f5de2008-06-19 01:39:21 +00001932/// classes. The registers may be either phys or virt regs. In the
1933/// case where both registers are virtual registers, it would also returns
1934/// true by reference the RegB register class in SubRC if it is a subset of
1935/// RegA's register class.
1936bool
1937SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA, unsigned RegB,
1938 const TargetRegisterClass *&SubRC) const {
David Greene25133302007-06-08 17:18:56 +00001939
1940 // Get the register classes for the first reg.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001941 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1942 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
David Greene25133302007-06-08 17:18:56 +00001943 "Shouldn't consider two physregs!");
Evan Chengc8d044e2008-02-15 18:24:29 +00001944 return !mri_->getRegClass(RegB)->contains(RegA);
David Greene25133302007-06-08 17:18:56 +00001945 }
1946
1947 // Compare against the regclass for the second reg.
Evan Chenge00f5de2008-06-19 01:39:21 +00001948 const TargetRegisterClass *RegClassA = mri_->getRegClass(RegA);
1949 if (TargetRegisterInfo::isVirtualRegister(RegB)) {
1950 const TargetRegisterClass *RegClassB = mri_->getRegClass(RegB);
1951 if (RegClassA == RegClassB)
1952 return false;
1953 SubRC = (RegClassA->hasSubClass(RegClassB)) ? RegClassB : NULL;
1954 return true;
1955 }
1956 return !RegClassA->contains(RegB);
David Greene25133302007-06-08 17:18:56 +00001957}
1958
1959/// lastRegisterUse - Returns the last use of the specific register between
Evan Chengc8d044e2008-02-15 18:24:29 +00001960/// cycles Start and End or NULL if there are no uses.
1961MachineOperand *
Chris Lattner84bc5422007-12-31 04:13:23 +00001962SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
Evan Chengc8d044e2008-02-15 18:24:29 +00001963 unsigned Reg, unsigned &UseIdx) const{
1964 UseIdx = 0;
1965 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1966 MachineOperand *LastUse = NULL;
1967 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1968 E = mri_->use_end(); I != E; ++I) {
1969 MachineOperand &Use = I.getOperand();
1970 MachineInstr *UseMI = Use.getParent();
Evan Chenga2fb6342008-03-25 02:02:19 +00001971 unsigned SrcReg, DstReg;
1972 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
1973 // Ignore identity copies.
1974 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +00001975 unsigned Idx = li_->getInstructionIndex(UseMI);
1976 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1977 LastUse = &Use;
1978 UseIdx = Idx;
1979 }
1980 }
1981 return LastUse;
1982 }
1983
David Greene25133302007-06-08 17:18:56 +00001984 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1985 int s = Start;
1986 while (e >= s) {
1987 // Skip deleted instructions
1988 MachineInstr *MI = li_->getInstructionFromIndex(e);
1989 while ((e - InstrSlots::NUM) >= s && !MI) {
1990 e -= InstrSlots::NUM;
1991 MI = li_->getInstructionFromIndex(e);
1992 }
1993 if (e < s || MI == NULL)
1994 return NULL;
1995
Evan Chenga2fb6342008-03-25 02:02:19 +00001996 // Ignore identity copies.
1997 unsigned SrcReg, DstReg;
1998 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
1999 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
2000 MachineOperand &Use = MI->getOperand(i);
2001 if (Use.isRegister() && Use.isUse() && Use.getReg() &&
2002 tri_->regsOverlap(Use.getReg(), Reg)) {
2003 UseIdx = e;
2004 return &Use;
2005 }
David Greene25133302007-06-08 17:18:56 +00002006 }
David Greene25133302007-06-08 17:18:56 +00002007
2008 e -= InstrSlots::NUM;
2009 }
2010
2011 return NULL;
2012}
2013
2014
David Greene25133302007-06-08 17:18:56 +00002015void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +00002016 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +00002017 cerr << tri_->getName(reg);
David Greene25133302007-06-08 17:18:56 +00002018 else
2019 cerr << "%reg" << reg;
2020}
2021
2022void SimpleRegisterCoalescing::releaseMemory() {
Evan Cheng8fc9a102007-11-06 08:52:21 +00002023 JoinedCopies.clear();
David Greene25133302007-06-08 17:18:56 +00002024}
2025
2026static bool isZeroLengthInterval(LiveInterval *li) {
2027 for (LiveInterval::Ranges::const_iterator
2028 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
2029 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
2030 return false;
2031 return true;
2032}
2033
Evan Chengdb9b1c32008-04-03 16:41:54 +00002034/// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
2035/// turn the copy into an implicit def.
2036bool
2037SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
2038 MachineBasicBlock *MBB,
2039 unsigned DstReg, unsigned SrcReg) {
2040 MachineInstr *CopyMI = &*I;
2041 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
2042 if (!li_->hasInterval(SrcReg))
2043 return false;
2044 LiveInterval &SrcInt = li_->getInterval(SrcReg);
2045 if (!SrcInt.empty())
2046 return false;
Evan Chengf20d9432008-04-09 01:30:15 +00002047 if (!li_->hasInterval(DstReg))
2048 return false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00002049 LiveInterval &DstInt = li_->getInterval(DstReg);
Evan Chengff7a3e52008-04-16 18:48:43 +00002050 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
Evan Chengdb9b1c32008-04-03 16:41:54 +00002051 DstInt.removeValNo(DstLR->valno);
2052 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
2053 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
2054 CopyMI->RemoveOperand(i);
2055 bool NoUse = mri_->use_begin(SrcReg) == mri_->use_end();
2056 if (NoUse) {
2057 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
2058 E = mri_->reg_end(); I != E; ) {
2059 assert(I.getOperand().isDef());
2060 MachineInstr *DefMI = &*I;
2061 ++I;
2062 // The implicit_def source has no other uses, delete it.
2063 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
2064 li_->RemoveMachineInstrFromMaps(DefMI);
2065 DefMI->eraseFromParent();
Evan Chengdb9b1c32008-04-03 16:41:54 +00002066 }
2067 }
2068 ++I;
2069 return true;
2070}
2071
2072
David Greene25133302007-06-08 17:18:56 +00002073bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
2074 mf_ = &fn;
Evan Cheng70071432008-02-13 03:01:43 +00002075 mri_ = &fn.getRegInfo();
David Greene25133302007-06-08 17:18:56 +00002076 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +00002077 tri_ = tm_->getRegisterInfo();
David Greene25133302007-06-08 17:18:56 +00002078 tii_ = tm_->getInstrInfo();
2079 li_ = &getAnalysis<LiveIntervals>();
Evan Cheng22f07ff2007-12-11 02:09:15 +00002080 loopInfo = &getAnalysis<MachineLoopInfo>();
David Greene25133302007-06-08 17:18:56 +00002081
2082 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
2083 << "********** Function: "
2084 << ((Value*)mf_->getFunction())->getName() << '\n';
2085
Dan Gohman6f0d0242008-02-10 18:45:23 +00002086 allocatableRegs_ = tri_->getAllocatableSet(fn);
2087 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
2088 E = tri_->regclass_end(); I != E; ++I)
Bill Wendling2674d712008-01-04 08:59:18 +00002089 allocatableRCRegs_.insert(std::make_pair(*I,
Dan Gohman6f0d0242008-02-10 18:45:23 +00002090 tri_->getAllocatableSet(fn, *I)));
David Greene25133302007-06-08 17:18:56 +00002091
Gabor Greife510b3a2007-07-09 12:00:59 +00002092 // Join (coalesce) intervals if requested.
David Greene25133302007-06-08 17:18:56 +00002093 if (EnableJoining) {
2094 joinIntervals();
2095 DOUT << "********** INTERVALS POST JOINING **********\n";
Bill Wendling2674d712008-01-04 08:59:18 +00002096 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
Dan Gohman6f0d0242008-02-10 18:45:23 +00002097 I->second.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +00002098 DOUT << "\n";
2099 }
2100 }
2101
Evan Chengc8d044e2008-02-15 18:24:29 +00002102 // Perform a final pass over the instructions and compute spill weights
2103 // and remove identity moves.
David Greene25133302007-06-08 17:18:56 +00002104 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2105 mbbi != mbbe; ++mbbi) {
2106 MachineBasicBlock* mbb = mbbi;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002107 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
David Greene25133302007-06-08 17:18:56 +00002108
2109 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2110 mii != mie; ) {
Evan Chenga971dbd2008-04-24 09:06:33 +00002111 MachineInstr *MI = mii;
2112 unsigned SrcReg, DstReg;
2113 if (JoinedCopies.count(MI)) {
2114 // Delete all coalesced copies.
2115 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg)) {
2116 assert((MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2117 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2118 "Unrecognized copy instruction");
2119 DstReg = MI->getOperand(0).getReg();
2120 }
2121 if (MI->registerDefIsDead(DstReg)) {
2122 LiveInterval &li = li_->getInterval(DstReg);
2123 if (!ShortenDeadCopySrcLiveRange(li, MI))
2124 ShortenDeadCopyLiveRange(li, MI);
2125 }
2126 li_->RemoveMachineInstrFromMaps(MI);
2127 mii = mbbi->erase(mii);
2128 ++numPeep;
2129 continue;
2130 }
2131
2132 // If the move will be an identity move delete it
2133 bool isMove = tii_->isMoveInstr(*mii, SrcReg, DstReg);
2134 if (isMove && SrcReg == DstReg) {
2135 if (li_->hasInterval(SrcReg)) {
2136 LiveInterval &RegInt = li_->getInterval(SrcReg);
Evan Cheng3c88d742008-03-18 08:26:47 +00002137 // If def of this move instruction is dead, remove its live range
2138 // from the dstination register's live interval.
Evan Chenga971dbd2008-04-24 09:06:33 +00002139 if (mii->registerDefIsDead(DstReg)) {
Evan Cheng9c1e06e2008-04-16 20:24:25 +00002140 if (!ShortenDeadCopySrcLiveRange(RegInt, mii))
2141 ShortenDeadCopyLiveRange(RegInt, mii);
Evan Cheng3c88d742008-03-18 08:26:47 +00002142 }
2143 }
David Greene25133302007-06-08 17:18:56 +00002144 li_->RemoveMachineInstrFromMaps(mii);
2145 mii = mbbi->erase(mii);
2146 ++numPeep;
Evan Chenga971dbd2008-04-24 09:06:33 +00002147 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, DstReg, SrcReg)) {
David Greene25133302007-06-08 17:18:56 +00002148 SmallSet<unsigned, 4> UniqueUses;
2149 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
2150 const MachineOperand &mop = mii->getOperand(i);
2151 if (mop.isRegister() && mop.getReg() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00002152 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
Evan Chengc8d044e2008-02-15 18:24:29 +00002153 unsigned reg = mop.getReg();
David Greene25133302007-06-08 17:18:56 +00002154 // Multiple uses of reg by the same instruction. It should not
2155 // contribute to spill weight again.
2156 if (UniqueUses.count(reg) != 0)
2157 continue;
2158 LiveInterval &RegInt = li_->getInterval(reg);
Evan Cheng81a03822007-11-17 00:40:40 +00002159 RegInt.weight +=
Evan Chengc3417602008-06-21 06:45:54 +00002160 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
David Greene25133302007-06-08 17:18:56 +00002161 UniqueUses.insert(reg);
2162 }
2163 }
2164 ++mii;
2165 }
2166 }
2167 }
2168
2169 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2170 LiveInterval &LI = I->second;
Dan Gohman6f0d0242008-02-10 18:45:23 +00002171 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
David Greene25133302007-06-08 17:18:56 +00002172 // If the live interval length is essentially zero, i.e. in every live
2173 // range the use follows def immediately, it doesn't make sense to spill
2174 // it and hope it will be easier to allocate for this li.
2175 if (isZeroLengthInterval(&LI))
2176 LI.weight = HUGE_VALF;
Evan Cheng5ef3a042007-12-06 00:01:56 +00002177 else {
2178 bool isLoad = false;
Evan Cheng63a18c42008-02-09 08:36:28 +00002179 if (li_->isReMaterializable(LI, isLoad)) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00002180 // If all of the definitions of the interval are re-materializable,
2181 // it is a preferred candidate for spilling. If non of the defs are
2182 // loads, then it's potentially very cheap to re-materialize.
2183 // FIXME: this gets much more complicated once we support non-trivial
2184 // re-materialization.
2185 if (isLoad)
2186 LI.weight *= 0.9F;
2187 else
2188 LI.weight *= 0.5F;
2189 }
2190 }
David Greene25133302007-06-08 17:18:56 +00002191
2192 // Slightly prefer live interval that has been assigned a preferred reg.
2193 if (LI.preference)
2194 LI.weight *= 1.01F;
2195
2196 // Divide the weight of the interval by its size. This encourages
2197 // spilling of intervals that are large and have few uses, and
2198 // discourages spilling of small intervals with many uses.
Owen Andersona1566f22008-07-22 22:46:49 +00002199 LI.weight /= li_->getApproximateInstructionCount(LI);
David Greene25133302007-06-08 17:18:56 +00002200 }
2201 }
2202
2203 DEBUG(dump());
2204 return true;
2205}
2206
2207/// print - Implement the dump method.
2208void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2209 li_->print(O, m);
2210}
David Greene2c17c4d2007-09-06 16:18:45 +00002211
2212RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2213 return new SimpleRegisterCoalescing();
2214}
2215
2216// Make sure that anything that uses RegisterCoalescer pulls in this file...
2217DEFINING_FILE_FOR(SimpleRegisterCoalescing)