blob: 9bff72e37cc8ef329dfea237cb1993044c66ea55 [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/LiveVariables.h"
21#include "llvm/CodeGen/MachineFrameInfo.h"
22#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000023#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
David Greene25133302007-06-08 17:18:56 +000025#include "llvm/CodeGen/Passes.h"
David Greene2c17c4d2007-09-06 16:18:45 +000026#include "llvm/CodeGen/RegisterCoalescer.h"
David Greene25133302007-06-08 17:18:56 +000027#include "llvm/Target/TargetInstrInfo.h"
28#include "llvm/Target/TargetMachine.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/ADT/SmallSet.h"
32#include "llvm/ADT/Statistic.h"
33#include "llvm/ADT/STLExtras.h"
34#include <algorithm>
35#include <cmath>
36using namespace llvm;
37
38STATISTIC(numJoins , "Number of interval 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;
45namespace {
46 static cl::opt<bool>
47 EnableJoining("join-liveintervals",
Gabor Greife510b3a2007-07-09 12:00:59 +000048 cl::desc("Coalesce copies (default=true)"),
David Greene25133302007-06-08 17:18:56 +000049 cl::init(true));
50
Evan Cheng8fc9a102007-11-06 08:52:21 +000051 static cl::opt<bool>
52 NewHeuristic("new-coalescer-heuristic",
53 cl::desc("Use new coalescer heuristic"),
54 cl::init(false));
55
David Greene25133302007-06-08 17:18:56 +000056 RegisterPass<SimpleRegisterCoalescing>
Chris Lattnere76fad22007-08-05 18:45:33 +000057 X("simple-register-coalescing", "Simple Register Coalescing");
David Greene2c17c4d2007-09-06 16:18:45 +000058
59 // Declare that we implement the RegisterCoalescer interface
60 RegisterAnalysisGroup<RegisterCoalescer, true/*The Default*/> V(X);
David Greene25133302007-06-08 17:18:56 +000061}
62
63const PassInfo *llvm::SimpleRegisterCoalescingID = X.getPassInfo();
64
65void SimpleRegisterCoalescing::getAnalysisUsage(AnalysisUsage &AU) const {
David Greene25133302007-06-08 17:18:56 +000066 AU.addPreserved<LiveIntervals>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000067 AU.addPreserved<MachineLoopInfo>();
68 AU.addPreservedID(MachineDominatorsID);
David Greene25133302007-06-08 17:18:56 +000069 AU.addPreservedID(PHIEliminationID);
70 AU.addPreservedID(TwoAddressInstructionPassID);
71 AU.addRequired<LiveVariables>();
72 AU.addRequired<LiveIntervals>();
Evan Cheng22f07ff2007-12-11 02:09:15 +000073 AU.addRequired<MachineLoopInfo>();
David Greene25133302007-06-08 17:18:56 +000074 MachineFunctionPass::getAnalysisUsage(AU);
75}
76
Gabor Greife510b3a2007-07-09 12:00:59 +000077/// AdjustCopiesBackFrom - We found a non-trivially-coalescable copy with IntA
David Greene25133302007-06-08 17:18:56 +000078/// being the source and IntB being the dest, thus this defines a value number
79/// in IntB. If the source value number (in IntA) is defined by a copy from B,
80/// see if we can merge these two pieces of B into a single value number,
81/// eliminating a copy. For example:
82///
83/// A3 = B0
84/// ...
85/// B1 = A3 <- this copy
86///
87/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
88/// value number to be replaced with B0 (which simplifies the B liveinterval).
89///
90/// This returns true if an interval was modified.
91///
Bill Wendling2674d712008-01-04 08:59:18 +000092bool SimpleRegisterCoalescing::AdjustCopiesBackFrom(LiveInterval &IntA,
93 LiveInterval &IntB,
94 MachineInstr *CopyMI) {
David Greene25133302007-06-08 17:18:56 +000095 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
96
97 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
98 // the example above.
99 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000100 if (BLR == IntB.end()) // Should never happen!
101 return false;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000102 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000103
104 // Get the location that B is defined at. Two options: either this value has
105 // an unknown definition point or it is defined at CopyIdx. If unknown, we
106 // can't process it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000107 if (!BValNo->copy) return false;
108 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
David Greene25133302007-06-08 17:18:56 +0000109
Evan Cheng70071432008-02-13 03:01:43 +0000110 // AValNo is the value number in A that defines the copy, A3 in the example.
111 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
Evan Chengff7a3e52008-04-16 18:48:43 +0000112 if (ALR == IntA.end()) // Should never happen!
113 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000114 VNInfo *AValNo = ALR->valno;
David Greene25133302007-06-08 17:18:56 +0000115
Evan Cheng70071432008-02-13 03:01:43 +0000116 // If AValNo is defined as a copy from IntB, we can potentially process this.
David Greene25133302007-06-08 17:18:56 +0000117 // Get the instruction that defines this value number.
Evan Chengc8d044e2008-02-15 18:24:29 +0000118 unsigned SrcReg = li_->getVNInfoSourceReg(AValNo);
David Greene25133302007-06-08 17:18:56 +0000119 if (!SrcReg) return false; // Not defined by a copy.
120
121 // If the value number is not defined by a copy instruction, ignore it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000122
David Greene25133302007-06-08 17:18:56 +0000123 // If the source register comes from an interval other than IntB, we can't
124 // handle this.
Evan Chengc8d044e2008-02-15 18:24:29 +0000125 if (SrcReg != IntB.reg) return false;
David Greene25133302007-06-08 17:18:56 +0000126
127 // Get the LiveRange in IntB that this value number starts with.
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000128 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNo->def-1);
Evan Chengff7a3e52008-04-16 18:48:43 +0000129 if (ValLR == IntB.end()) // Should never happen!
130 return false;
David Greene25133302007-06-08 17:18:56 +0000131
132 // Make sure that the end of the live range is inside the same block as
133 // CopyMI.
134 MachineInstr *ValLREndInst = li_->getInstructionFromIndex(ValLR->end-1);
135 if (!ValLREndInst ||
136 ValLREndInst->getParent() != CopyMI->getParent()) return false;
137
138 // Okay, we now know that ValLR ends in the same block that the CopyMI
139 // live-range starts. If there are no intervening live ranges between them in
140 // IntB, we can merge them.
141 if (ValLR+1 != BLR) return false;
Evan Chengdc5294f2007-08-14 23:19:28 +0000142
143 // If a live interval is a physical register, conservatively check if any
144 // of its sub-registers is overlapping the live interval of the virtual
145 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000146 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg) &&
147 *tri_->getSubRegisters(IntB.reg)) {
148 for (const unsigned* SR = tri_->getSubRegisters(IntB.reg); *SR; ++SR)
Evan Chengdc5294f2007-08-14 23:19:28 +0000149 if (li_->hasInterval(*SR) && IntA.overlaps(li_->getInterval(*SR))) {
150 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000151 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
Evan Chengdc5294f2007-08-14 23:19:28 +0000152 return false;
153 }
154 }
David Greene25133302007-06-08 17:18:56 +0000155
Dan Gohman6f0d0242008-02-10 18:45:23 +0000156 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000157
Evan Chenga8d94f12007-08-07 23:49:57 +0000158 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
David Greene25133302007-06-08 17:18:56 +0000159 // We are about to delete CopyMI, so need to remove it as the 'instruction
Evan Chenga8d94f12007-08-07 23:49:57 +0000160 // that defines this value #'. Update the the valnum with the new defining
161 // instruction #.
Evan Chengc8d044e2008-02-15 18:24:29 +0000162 BValNo->def = FillerStart;
163 BValNo->copy = NULL;
David Greene25133302007-06-08 17:18:56 +0000164
165 // Okay, we can merge them. We need to insert a new liverange:
166 // [ValLR.end, BLR.begin) of either value number, then we merge the
167 // two value numbers.
David Greene25133302007-06-08 17:18:56 +0000168 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
169
170 // If the IntB live range is assigned to a physical register, and if that
171 // physreg has aliases,
Dan Gohman6f0d0242008-02-10 18:45:23 +0000172 if (TargetRegisterInfo::isPhysicalRegister(IntB.reg)) {
David Greene25133302007-06-08 17:18:56 +0000173 // Update the liveintervals of sub-registers.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000174 for (const unsigned *AS = tri_->getSubRegisters(IntB.reg); *AS; ++AS) {
David Greene25133302007-06-08 17:18:56 +0000175 LiveInterval &AliasLI = li_->getInterval(*AS);
176 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
Evan Chengf3bb2e62007-09-05 21:46:51 +0000177 AliasLI.getNextValue(FillerStart, 0, li_->getVNInfoAllocator())));
David Greene25133302007-06-08 17:18:56 +0000178 }
179 }
180
181 // Okay, merge "B1" into the same value number as "B0".
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000182 if (BValNo != ValLR->valno)
183 IntB.MergeValueNumberInto(BValNo, ValLR->valno);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000184 DOUT << " result = "; IntB.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +0000185 DOUT << "\n";
186
187 // If the source instruction was killing the source register before the
188 // merge, unset the isKill marker given the live range has been extended.
189 int UIdx = ValLREndInst->findRegisterUseOperandIdx(IntB.reg, true);
190 if (UIdx != -1)
Chris Lattnerf7382302007-12-30 21:56:09 +0000191 ValLREndInst->getOperand(UIdx).setIsKill(false);
Evan Cheng70071432008-02-13 03:01:43 +0000192
193 ++numExtends;
194 return true;
195}
196
Evan Cheng559f4222008-02-16 02:32:17 +0000197/// HasOtherReachingDefs - Return true if there are definitions of IntB
198/// other than BValNo val# that can reach uses of AValno val# of IntA.
199bool SimpleRegisterCoalescing::HasOtherReachingDefs(LiveInterval &IntA,
200 LiveInterval &IntB,
201 VNInfo *AValNo,
202 VNInfo *BValNo) {
203 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
204 AI != AE; ++AI) {
205 if (AI->valno != AValNo) continue;
206 LiveInterval::Ranges::iterator BI =
207 std::upper_bound(IntB.ranges.begin(), IntB.ranges.end(), AI->start);
208 if (BI != IntB.ranges.begin())
209 --BI;
210 for (; BI != IntB.ranges.end() && AI->end >= BI->start; ++BI) {
211 if (BI->valno == BValNo)
212 continue;
213 if (BI->start <= AI->start && BI->end > AI->start)
214 return true;
215 if (BI->start > AI->start && BI->start < AI->end)
216 return true;
217 }
218 }
219 return false;
220}
221
Evan Cheng70071432008-02-13 03:01:43 +0000222/// RemoveCopyByCommutingDef - We found a non-trivially-coalescable copy with IntA
223/// being the source and IntB being the dest, thus this defines a value number
224/// in IntB. If the source value number (in IntA) is defined by a commutable
225/// instruction and its other operand is coalesced to the copy dest register,
226/// see if we can transform the copy into a noop by commuting the definition. For
227/// example,
228///
229/// A3 = op A2 B0<kill>
230/// ...
231/// B1 = A3 <- this copy
232/// ...
233/// = op A3 <- more uses
234///
235/// ==>
236///
237/// B2 = op B0 A2<kill>
238/// ...
239/// B1 = B2 <- now an identify copy
240/// ...
241/// = op B2 <- more uses
242///
243/// This returns true if an interval was modified.
244///
245bool SimpleRegisterCoalescing::RemoveCopyByCommutingDef(LiveInterval &IntA,
246 LiveInterval &IntB,
247 MachineInstr *CopyMI) {
Evan Cheng70071432008-02-13 03:01:43 +0000248 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
249
Evan Chenga9407f52008-02-18 18:56:31 +0000250 // FIXME: For now, only eliminate the copy by commuting its def when the
251 // source register is a virtual register. We want to guard against cases
252 // where the copy is a back edge copy and commuting the def lengthen the
253 // live interval of the source register to the entire loop.
254 if (TargetRegisterInfo::isPhysicalRegister(IntA.reg))
Evan Cheng96cfff02008-02-18 08:40:53 +0000255 return false;
256
Evan Chengc8d044e2008-02-15 18:24:29 +0000257 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
Evan Cheng70071432008-02-13 03:01:43 +0000258 // the example above.
259 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000260 if (BLR == IntB.end()) // Should never happen!
261 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000262 VNInfo *BValNo = BLR->valno;
David Greene25133302007-06-08 17:18:56 +0000263
Evan Cheng70071432008-02-13 03:01:43 +0000264 // Get the location that B is defined at. Two options: either this value has
265 // an unknown definition point or it is defined at CopyIdx. If unknown, we
266 // can't process it.
Evan Chengc8d044e2008-02-15 18:24:29 +0000267 if (!BValNo->copy) return false;
Evan Cheng70071432008-02-13 03:01:43 +0000268 assert(BValNo->def == CopyIdx && "Copy doesn't define the value?");
269
270 // AValNo is the value number in A that defines the copy, A3 in the example.
271 LiveInterval::iterator ALR = IntA.FindLiveRangeContaining(CopyIdx-1);
Evan Chengff7a3e52008-04-16 18:48:43 +0000272 if (ALR == IntA.end()) // Should never happen!
273 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000274 VNInfo *AValNo = ALR->valno;
Evan Chenge35a6d12008-02-13 08:41:08 +0000275 // If other defs can reach uses of this def, then it's not safe to perform
276 // the optimization.
277 if (AValNo->def == ~0U || AValNo->def == ~1U || AValNo->hasPHIKill)
Evan Cheng70071432008-02-13 03:01:43 +0000278 return false;
279 MachineInstr *DefMI = li_->getInstructionFromIndex(AValNo->def);
280 const TargetInstrDesc &TID = DefMI->getDesc();
Evan Chengc8d044e2008-02-15 18:24:29 +0000281 unsigned NewDstIdx;
282 if (!TID.isCommutable() ||
283 !tii_->CommuteChangesDestination(DefMI, NewDstIdx))
Evan Cheng70071432008-02-13 03:01:43 +0000284 return false;
285
Evan Chengc8d044e2008-02-15 18:24:29 +0000286 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
287 unsigned NewReg = NewDstMO.getReg();
288 if (NewReg != IntB.reg || !NewDstMO.isKill())
Evan Cheng70071432008-02-13 03:01:43 +0000289 return false;
290
291 // Make sure there are no other definitions of IntB that would reach the
292 // uses which the new definition can reach.
Evan Cheng559f4222008-02-16 02:32:17 +0000293 if (HasOtherReachingDefs(IntA, IntB, AValNo, BValNo))
294 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000295
Evan Chenged70cbb32008-03-26 19:03:01 +0000296 // If some of the uses of IntA.reg is already coalesced away, return false.
297 // It's not possible to determine whether it's safe to perform the coalescing.
298 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
299 UE = mri_->use_end(); UI != UE; ++UI) {
300 MachineInstr *UseMI = &*UI;
301 unsigned UseIdx = li_->getInstructionIndex(UseMI);
302 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000303 if (ULR == IntA.end())
304 continue;
Evan Chenged70cbb32008-03-26 19:03:01 +0000305 if (ULR->valno == AValNo && JoinedCopies.count(UseMI))
306 return false;
307 }
308
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000309 // At this point we have decided that it is legal to do this
310 // transformation. Start by commuting the instruction.
Evan Cheng70071432008-02-13 03:01:43 +0000311 MachineBasicBlock *MBB = DefMI->getParent();
312 MachineInstr *NewMI = tii_->commuteInstruction(DefMI);
Evan Cheng559f4222008-02-16 02:32:17 +0000313 if (!NewMI)
314 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000315 if (NewMI != DefMI) {
316 li_->ReplaceMachineInstrInMaps(DefMI, NewMI);
317 MBB->insert(DefMI, NewMI);
318 MBB->erase(DefMI);
319 }
Evan Cheng6130f662008-03-05 00:59:57 +0000320 unsigned OpIdx = NewMI->findRegisterUseOperandIdx(IntA.reg, false);
Evan Cheng70071432008-02-13 03:01:43 +0000321 NewMI->getOperand(OpIdx).setIsKill();
322
Evan Cheng70071432008-02-13 03:01:43 +0000323 bool BHasPHIKill = BValNo->hasPHIKill;
324 SmallVector<VNInfo*, 4> BDeadValNos;
325 SmallVector<unsigned, 4> BKills;
326 std::map<unsigned, unsigned> BExtend;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000327
328 // If ALR and BLR overlaps and end of BLR extends beyond end of ALR, e.g.
329 // A = or A, B
330 // ...
331 // B = A
332 // ...
333 // C = A<kill>
334 // ...
335 // = B
336 //
337 // then do not add kills of A to the newly created B interval.
338 bool Extended = BLR->end > ALR->end && ALR->end != ALR->start;
339 if (Extended)
340 BExtend[ALR->end] = BLR->end;
341
342 // Update uses of IntA of the specific Val# with IntB.
Evan Cheng70071432008-02-13 03:01:43 +0000343 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(IntA.reg),
344 UE = mri_->use_end(); UI != UE;) {
345 MachineOperand &UseMO = UI.getOperand();
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000346 MachineInstr *UseMI = &*UI;
Evan Cheng70071432008-02-13 03:01:43 +0000347 ++UI;
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000348 if (JoinedCopies.count(UseMI))
Evan Chenged70cbb32008-03-26 19:03:01 +0000349 continue;
Evan Cheng70071432008-02-13 03:01:43 +0000350 unsigned UseIdx = li_->getInstructionIndex(UseMI);
351 LiveInterval::iterator ULR = IntA.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000352 if (ULR == IntA.end() || ULR->valno != AValNo)
Evan Cheng70071432008-02-13 03:01:43 +0000353 continue;
354 UseMO.setReg(NewReg);
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000355 if (UseMI == CopyMI)
356 continue;
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000357 if (UseMO.isKill()) {
358 if (Extended)
359 UseMO.setIsKill(false);
360 else
361 BKills.push_back(li_->getUseIndex(UseIdx)+1);
362 }
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000363 unsigned SrcReg, DstReg;
364 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg))
365 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +0000366 if (DstReg == IntB.reg) {
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000367 // This copy will become a noop. If it's defining a new val#,
368 // remove that val# as well. However this live range is being
369 // extended to the end of the existing live range defined by the copy.
370 unsigned DefIdx = li_->getDefIndex(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000371 const LiveRange *DLR = IntB.getLiveRangeContaining(DefIdx);
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000372 BHasPHIKill |= DLR->valno->hasPHIKill;
373 assert(DLR->valno->def == DefIdx);
374 BDeadValNos.push_back(DLR->valno);
375 BExtend[DLR->start] = DLR->end;
376 JoinedCopies.insert(UseMI);
377 // If this is a kill but it's going to be removed, the last use
378 // of the same val# is the new kill.
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000379 if (UseMO.isKill())
Evan Chengcdbcfcc2008-02-13 09:56:03 +0000380 BKills.pop_back();
Evan Cheng70071432008-02-13 03:01:43 +0000381 }
382 }
383
384 // We need to insert a new liverange: [ALR.start, LastUse). It may be we can
385 // simply extend BLR if CopyMI doesn't end the range.
386 DOUT << "\nExtending: "; IntB.print(DOUT, tri_);
387
388 IntB.removeValNo(BValNo);
389 for (unsigned i = 0, e = BDeadValNos.size(); i != e; ++i)
390 IntB.removeValNo(BDeadValNos[i]);
Evan Cheng82a6d232008-03-19 02:26:36 +0000391 VNInfo *ValNo = IntB.getNextValue(AValNo->def, 0, li_->getVNInfoAllocator());
Evan Cheng70071432008-02-13 03:01:43 +0000392 for (LiveInterval::iterator AI = IntA.begin(), AE = IntA.end();
393 AI != AE; ++AI) {
394 if (AI->valno != AValNo) continue;
395 unsigned End = AI->end;
396 std::map<unsigned, unsigned>::iterator EI = BExtend.find(End);
397 if (EI != BExtend.end())
398 End = EI->second;
399 IntB.addRange(LiveRange(AI->start, End, ValNo));
400 }
401 IntB.addKills(ValNo, BKills);
402 ValNo->hasPHIKill = BHasPHIKill;
403
404 DOUT << " result = "; IntB.print(DOUT, tri_);
405 DOUT << "\n";
406
407 DOUT << "\nShortening: "; IntA.print(DOUT, tri_);
408 IntA.removeValNo(AValNo);
409 DOUT << " result = "; IntA.print(DOUT, tri_);
410 DOUT << "\n";
411
412 ++numCommutes;
David Greene25133302007-06-08 17:18:56 +0000413 return true;
414}
415
Evan Cheng8fc9a102007-11-06 08:52:21 +0000416/// isBackEdgeCopy - Returns true if CopyMI is a back edge copy.
417///
418bool SimpleRegisterCoalescing::isBackEdgeCopy(MachineInstr *CopyMI,
Evan Cheng7e073ba2008-04-09 20:57:25 +0000419 unsigned DstReg) const {
Evan Cheng8fc9a102007-11-06 08:52:21 +0000420 MachineBasicBlock *MBB = CopyMI->getParent();
Evan Cheng22f07ff2007-12-11 02:09:15 +0000421 const MachineLoop *L = loopInfo->getLoopFor(MBB);
Evan Cheng8fc9a102007-11-06 08:52:21 +0000422 if (!L)
423 return false;
Evan Cheng22f07ff2007-12-11 02:09:15 +0000424 if (MBB != L->getLoopLatch())
Evan Cheng8fc9a102007-11-06 08:52:21 +0000425 return false;
426
Evan Cheng8fc9a102007-11-06 08:52:21 +0000427 LiveInterval &LI = li_->getInterval(DstReg);
428 unsigned DefIdx = li_->getInstructionIndex(CopyMI);
429 LiveInterval::const_iterator DstLR =
430 LI.FindLiveRangeContaining(li_->getDefIndex(DefIdx));
431 if (DstLR == LI.end())
432 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000433 unsigned KillIdx = li_->getInstructionIndex(&MBB->back()) + InstrSlots::NUM;
434 if (DstLR->valno->kills.size() == 1 &&
435 DstLR->valno->kills[0] == KillIdx && DstLR->valno->hasPHIKill)
Evan Cheng8fc9a102007-11-06 08:52:21 +0000436 return true;
437 return false;
438}
439
Evan Chengc8d044e2008-02-15 18:24:29 +0000440/// UpdateRegDefsUses - Replace all defs and uses of SrcReg to DstReg and
441/// update the subregister number if it is not zero. If DstReg is a
442/// physical register and the existing subregister number of the def / use
443/// being updated is not zero, make sure to set it to the correct physical
444/// subregister.
445void
446SimpleRegisterCoalescing::UpdateRegDefsUses(unsigned SrcReg, unsigned DstReg,
447 unsigned SubIdx) {
448 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
449 if (DstIsPhys && SubIdx) {
450 // Figure out the real physical register we are updating with.
451 DstReg = tri_->getSubReg(DstReg, SubIdx);
452 SubIdx = 0;
453 }
454
455 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
456 E = mri_->reg_end(); I != E; ) {
457 MachineOperand &O = I.getOperand();
Evan Cheng70366b92008-03-21 19:09:30 +0000458 MachineInstr *UseMI = &*I;
Evan Chengc8d044e2008-02-15 18:24:29 +0000459 ++I;
Evan Cheng621d1572008-04-17 00:06:42 +0000460 unsigned OldSubIdx = O.getSubReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000461 if (DstIsPhys) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000462 unsigned UseDstReg = DstReg;
Evan Cheng621d1572008-04-17 00:06:42 +0000463 if (OldSubIdx)
464 UseDstReg = tri_->getSubReg(DstReg, OldSubIdx);
Evan Chengc8d044e2008-02-15 18:24:29 +0000465 O.setReg(UseDstReg);
466 O.setSubReg(0);
467 } else {
Evan Chengc886c462008-02-26 08:03:41 +0000468 // Sub-register indexes goes from small to large. e.g.
469 // RAX: 0 -> AL, 1 -> AH, 2 -> AX, 3 -> EAX
470 // EAX: 0 -> AL, 1 -> AH, 2 -> AX
471 // So RAX's sub-register 2 is AX, RAX's sub-regsiter 3 is EAX, whose
472 // sub-register 2 is also AX.
473 if (SubIdx && OldSubIdx && SubIdx != OldSubIdx)
474 assert(OldSubIdx < SubIdx && "Conflicting sub-register index!");
475 else if (SubIdx)
Evan Chengc8d044e2008-02-15 18:24:29 +0000476 O.setSubReg(SubIdx);
Evan Cheng70366b92008-03-21 19:09:30 +0000477 // Remove would-be duplicated kill marker.
478 if (O.isKill() && UseMI->killsRegister(DstReg))
479 O.setIsKill(false);
Evan Chengc8d044e2008-02-15 18:24:29 +0000480 O.setReg(DstReg);
481 }
482 }
483}
484
Evan Cheng7e073ba2008-04-09 20:57:25 +0000485/// RemoveDeadImpDef - Remove implicit_def instructions which are "re-defining"
486/// registers due to insert_subreg coalescing. e.g.
487/// r1024 = op
488/// r1025 = implicit_def
489/// r1025 = insert_subreg r1025, r1024
490/// = op r1025
491/// =>
492/// r1025 = op
493/// r1025 = implicit_def
494/// r1025 = insert_subreg r1025, r1025
495/// = op r1025
496void
497SimpleRegisterCoalescing::RemoveDeadImpDef(unsigned Reg, LiveInterval &LI) {
498 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(Reg),
499 E = mri_->reg_end(); I != E; ) {
500 MachineOperand &O = I.getOperand();
501 MachineInstr *DefMI = &*I;
502 ++I;
503 if (!O.isDef())
504 continue;
505 if (DefMI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
506 continue;
507 if (!LI.liveBeforeAndAt(li_->getInstructionIndex(DefMI)))
508 continue;
509 li_->RemoveMachineInstrFromMaps(DefMI);
510 DefMI->eraseFromParent();
511 }
512}
513
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000514/// RemoveUnnecessaryKills - Remove kill markers that are no longer accurate
515/// due to live range lengthening as the result of coalescing.
516void SimpleRegisterCoalescing::RemoveUnnecessaryKills(unsigned Reg,
517 LiveInterval &LI) {
518 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
519 UE = mri_->use_end(); UI != UE; ++UI) {
520 MachineOperand &UseMO = UI.getOperand();
521 if (UseMO.isKill()) {
522 MachineInstr *UseMI = UseMO.getParent();
523 unsigned SReg, DReg;
524 if (!tii_->isMoveInstr(*UseMI, SReg, DReg))
525 continue;
526 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
527 if (JoinedCopies.count(UseMI))
528 continue;
Evan Chengff7a3e52008-04-16 18:48:43 +0000529 const LiveRange *UI = LI.getLiveRangeContaining(UseIdx);
Evan Cheng4ff3f1c2008-03-10 08:11:32 +0000530 if (!LI.isKill(UI->valno, UseIdx+1))
531 UseMO.setIsKill(false);
532 }
533 }
534}
535
Evan Cheng3c88d742008-03-18 08:26:47 +0000536/// removeRange - Wrapper for LiveInterval::removeRange. This removes a range
537/// from a physical register live interval as well as from the live intervals
538/// of its sub-registers.
539static void removeRange(LiveInterval &li, unsigned Start, unsigned End,
540 LiveIntervals *li_, const TargetRegisterInfo *tri_) {
541 li.removeRange(Start, End, true);
542 if (TargetRegisterInfo::isPhysicalRegister(li.reg)) {
543 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
544 if (!li_->hasInterval(*SR))
545 continue;
546 LiveInterval &sli = li_->getInterval(*SR);
547 unsigned RemoveEnd = Start;
548 while (RemoveEnd != End) {
549 LiveInterval::iterator LR = sli.FindLiveRangeContaining(Start);
550 if (LR == sli.end())
551 break;
552 RemoveEnd = (LR->end < End) ? LR->end : End;
553 sli.removeRange(Start, RemoveEnd, true);
554 Start = RemoveEnd;
555 }
556 }
557 }
558}
559
560/// removeIntervalIfEmpty - Check if the live interval of a physical register
561/// is empty, if so remove it and also remove the empty intervals of its
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000562/// sub-registers. Return true if live interval is removed.
563static bool removeIntervalIfEmpty(LiveInterval &li, LiveIntervals *li_,
Evan Cheng3c88d742008-03-18 08:26:47 +0000564 const TargetRegisterInfo *tri_) {
565 if (li.empty()) {
Evan Cheng3c88d742008-03-18 08:26:47 +0000566 if (TargetRegisterInfo::isPhysicalRegister(li.reg))
567 for (const unsigned* SR = tri_->getSubRegisters(li.reg); *SR; ++SR) {
568 if (!li_->hasInterval(*SR))
569 continue;
570 LiveInterval &sli = li_->getInterval(*SR);
571 if (sli.empty())
572 li_->removeInterval(*SR);
573 }
Evan Chengd94950c2008-04-16 01:22:28 +0000574 li_->removeInterval(li.reg);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000575 return true;
Evan Cheng3c88d742008-03-18 08:26:47 +0000576 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000577 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000578}
579
580/// ShortenDeadCopyLiveRange - Shorten a live range defined by a dead copy.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000581/// Return true if live interval is removed.
582bool SimpleRegisterCoalescing::ShortenDeadCopyLiveRange(LiveInterval &li,
Evan Chengecb2a8b2008-03-05 22:09:42 +0000583 MachineInstr *CopyMI) {
584 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
585 LiveInterval::iterator MLR =
586 li.FindLiveRangeContaining(li_->getDefIndex(CopyIdx));
Evan Cheng3c88d742008-03-18 08:26:47 +0000587 if (MLR == li.end())
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000588 return false; // Already removed by ShortenDeadCopySrcLiveRange.
Evan Chengecb2a8b2008-03-05 22:09:42 +0000589 unsigned RemoveStart = MLR->start;
590 unsigned RemoveEnd = MLR->end;
Evan Cheng3c88d742008-03-18 08:26:47 +0000591 // Remove the liverange that's defined by this.
592 if (RemoveEnd == li_->getDefIndex(CopyIdx)+1) {
593 removeRange(li, RemoveStart, RemoveEnd, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000594 return removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000595 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000596 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000597}
598
Evan Cheng0c284322008-03-26 20:15:49 +0000599/// PropagateDeadness - Propagate the dead marker to the instruction which
600/// defines the val#.
601static void PropagateDeadness(LiveInterval &li, MachineInstr *CopyMI,
602 unsigned &LRStart, LiveIntervals *li_,
603 const TargetRegisterInfo* tri_) {
604 MachineInstr *DefMI =
605 li_->getInstructionFromIndex(li_->getDefIndex(LRStart));
606 if (DefMI && DefMI != CopyMI) {
607 int DeadIdx = DefMI->findRegisterDefOperandIdx(li.reg, false, tri_);
608 if (DeadIdx != -1) {
609 DefMI->getOperand(DeadIdx).setIsDead();
610 // A dead def should have a single cycle interval.
611 ++LRStart;
612 }
613 }
614}
615
Evan Cheng883d2602008-04-18 19:22:23 +0000616/// isSameOrFallThroughBB - Return true if MBB == SuccMBB or MBB simply
617/// fallthoughs to SuccMBB.
618static bool isSameOrFallThroughBB(MachineBasicBlock *MBB,
619 MachineBasicBlock *SuccMBB,
620 const TargetInstrInfo *tii_) {
621 if (MBB == SuccMBB)
622 return true;
623 MachineBasicBlock *TBB = 0, *FBB = 0;
624 std::vector<MachineOperand> Cond;
625 return !tii_->AnalyzeBranch(*MBB, TBB, FBB, Cond) && !TBB && !FBB &&
626 MBB->isSuccessor(SuccMBB);
627}
628
Bill Wendlingf2317782008-04-17 05:20:39 +0000629/// ShortenDeadCopySrcLiveRange - Shorten a live range as it's artificially
630/// extended by a dead copy. Mark the last use (if any) of the val# as kill as
631/// ends the live range there. If there isn't another use, then this live range
632/// is dead. Return true if live interval is removed.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000633bool
Evan Cheng3c88d742008-03-18 08:26:47 +0000634SimpleRegisterCoalescing::ShortenDeadCopySrcLiveRange(LiveInterval &li,
635 MachineInstr *CopyMI) {
636 unsigned CopyIdx = li_->getInstructionIndex(CopyMI);
637 if (CopyIdx == 0) {
638 // FIXME: special case: function live in. It can be a general case if the
639 // first instruction index starts at > 0 value.
640 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
641 // Live-in to the function but dead. Remove it from entry live-in set.
642 mf_->begin()->removeLiveIn(li.reg);
Evan Chengff7a3e52008-04-16 18:48:43 +0000643 const LiveRange *LR = li.getLiveRangeContaining(CopyIdx);
Evan Cheng3c88d742008-03-18 08:26:47 +0000644 removeRange(li, LR->start, LR->end, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000645 return removeIntervalIfEmpty(li, li_, tri_);
Evan Cheng3c88d742008-03-18 08:26:47 +0000646 }
647
648 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx-1);
649 if (LR == li.end())
650 // Livein but defined by a phi.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000651 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000652
653 unsigned RemoveStart = LR->start;
654 unsigned RemoveEnd = li_->getDefIndex(CopyIdx)+1;
655 if (LR->end > RemoveEnd)
656 // More uses past this copy? Nothing to do.
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000657 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000658
Evan Cheng883d2602008-04-18 19:22:23 +0000659 MachineBasicBlock *CopyMBB = CopyMI->getParent();
660 unsigned MBBStart = li_->getMBBStartIdx(CopyMBB);
Evan Cheng3c88d742008-03-18 08:26:47 +0000661 unsigned LastUseIdx;
Evan Chengd2012d02008-04-10 23:48:35 +0000662 MachineOperand *LastUse = lastRegisterUse(LR->start, CopyIdx-1, li.reg,
663 LastUseIdx);
Evan Cheng3c88d742008-03-18 08:26:47 +0000664 if (LastUse) {
Evan Cheng883d2602008-04-18 19:22:23 +0000665 MachineInstr *LastUseMI = LastUse->getParent();
666 if (!isSameOrFallThroughBB(LastUseMI->getParent(), CopyMBB, tii_)) {
667 // r1024 = op
668 // ...
669 // BB1:
670 // = r1024
671 //
672 // BB2:
673 // r1025<dead> = r1024<kill>
674 if (MBBStart < LR->end)
675 removeRange(li, MBBStart, LR->end, li_, tri_);
676 return false;
677 }
678
Evan Cheng3c88d742008-03-18 08:26:47 +0000679 // There are uses before the copy, just shorten the live range to the end
680 // of last use.
681 LastUse->setIsKill();
Evan Cheng3c88d742008-03-18 08:26:47 +0000682 removeRange(li, li_->getDefIndex(LastUseIdx), LR->end, li_, tri_);
683 unsigned SrcReg, DstReg;
684 if (tii_->isMoveInstr(*LastUseMI, SrcReg, DstReg) &&
685 DstReg == li.reg) {
686 // Last use is itself an identity code.
687 int DeadIdx = LastUseMI->findRegisterDefOperandIdx(li.reg, false, tri_);
688 LastUseMI->getOperand(DeadIdx).setIsDead();
689 }
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000690 return false;
Evan Cheng3c88d742008-03-18 08:26:47 +0000691 }
692
693 // Is it livein?
Evan Cheng3c88d742008-03-18 08:26:47 +0000694 if (LR->start <= MBBStart && LR->end > MBBStart) {
695 if (LR->start == 0) {
696 assert(TargetRegisterInfo::isPhysicalRegister(li.reg));
697 // Live-in to the function but dead. Remove it from entry live-in set.
698 mf_->begin()->removeLiveIn(li.reg);
699 }
Evan Cheng3c88d742008-03-18 08:26:47 +0000700 // FIXME: Shorten intervals in BBs that reaches this BB.
Evan Cheng3c88d742008-03-18 08:26:47 +0000701 }
702
Evan Cheng0c284322008-03-26 20:15:49 +0000703 if (LR->valno->def == RemoveStart)
704 // If the def MI defines the val#, propagate the dead marker.
705 PropagateDeadness(li, CopyMI, RemoveStart, li_, tri_);
706
707 removeRange(li, RemoveStart, LR->end, li_, tri_);
Evan Cheng9c1e06e2008-04-16 20:24:25 +0000708 return removeIntervalIfEmpty(li, li_, tri_);
Evan Chengecb2a8b2008-03-05 22:09:42 +0000709}
710
Evan Cheng7e073ba2008-04-09 20:57:25 +0000711/// CanCoalesceWithImpDef - Returns true if the specified copy instruction
712/// from an implicit def to another register can be coalesced away.
713bool SimpleRegisterCoalescing::CanCoalesceWithImpDef(MachineInstr *CopyMI,
714 LiveInterval &li,
715 LiveInterval &ImpLi) const{
716 if (!CopyMI->killsRegister(ImpLi.reg))
717 return false;
718 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
719 LiveInterval::iterator LR = li.FindLiveRangeContaining(CopyIdx);
720 if (LR == li.end())
721 return false;
722 if (LR->valno->hasPHIKill)
723 return false;
724 if (LR->valno->def != CopyIdx)
725 return false;
726 // Make sure all of val# uses are copies.
727 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(li.reg),
728 UE = mri_->use_end(); UI != UE;) {
729 MachineInstr *UseMI = &*UI;
730 ++UI;
731 if (JoinedCopies.count(UseMI))
732 continue;
733 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(UseMI));
734 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000735 if (ULR == li.end() || ULR->valno != LR->valno)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000736 continue;
737 // If the use is not a use, then it's not safe to coalesce the move.
738 unsigned SrcReg, DstReg;
739 if (!tii_->isMoveInstr(*UseMI, SrcReg, DstReg)) {
740 if (UseMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG &&
741 UseMI->getOperand(1).getReg() == li.reg)
742 continue;
743 return false;
744 }
745 }
746 return true;
747}
748
749
750/// RemoveCopiesFromValNo - The specified value# is defined by an implicit
751/// def and it is being removed. Turn all copies from this value# into
752/// identity copies so they will be removed.
753void SimpleRegisterCoalescing::RemoveCopiesFromValNo(LiveInterval &li,
754 VNInfo *VNI) {
Evan Chengd2012d02008-04-10 23:48:35 +0000755 MachineInstr *ImpDef = NULL;
756 MachineOperand *LastUse = NULL;
757 unsigned LastUseIdx = li_->getUseIndex(VNI->def);
758 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg),
759 RE = mri_->reg_end(); RI != RE;) {
760 MachineOperand *MO = &RI.getOperand();
761 MachineInstr *MI = &*RI;
762 ++RI;
763 if (MO->isDef()) {
764 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
765 assert(!ImpDef && "Multiple implicit_def defining same register?");
766 ImpDef = MI;
767 }
Evan Cheng7e073ba2008-04-09 20:57:25 +0000768 continue;
Evan Chengd2012d02008-04-10 23:48:35 +0000769 }
770 if (JoinedCopies.count(MI))
771 continue;
772 unsigned UseIdx = li_->getUseIndex(li_->getInstructionIndex(MI));
Evan Cheng7e073ba2008-04-09 20:57:25 +0000773 LiveInterval::iterator ULR = li.FindLiveRangeContaining(UseIdx);
Evan Chengff7a3e52008-04-16 18:48:43 +0000774 if (ULR == li.end() || ULR->valno != VNI)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000775 continue;
Evan Cheng7e073ba2008-04-09 20:57:25 +0000776 // If the use is a copy, turn it into an identity copy.
777 unsigned SrcReg, DstReg;
Evan Chengd2012d02008-04-10 23:48:35 +0000778 if (tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == li.reg) {
779 // Each use MI may have multiple uses of this register. Change them all.
780 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
781 MachineOperand &MO = MI->getOperand(i);
782 if (MO.isReg() && MO.getReg() == li.reg)
783 MO.setReg(DstReg);
784 }
785 JoinedCopies.insert(MI);
786 } else if (UseIdx > LastUseIdx) {
787 LastUseIdx = UseIdx;
788 LastUse = MO;
Evan Cheng172b70c2008-04-10 18:38:47 +0000789 }
Evan Chengd2012d02008-04-10 23:48:35 +0000790 }
791 if (LastUse)
792 LastUse->setIsKill();
793 else {
794 // Remove dead implicit_def.
795 li_->RemoveMachineInstrFromMaps(ImpDef);
796 ImpDef->eraseFromParent();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000797 }
798}
799
800static unsigned getMatchingSuperReg(unsigned Reg, unsigned SubIdx,
801 const TargetRegisterClass *RC,
802 const TargetRegisterInfo* TRI) {
803 for (const unsigned *SRs = TRI->getSuperRegisters(Reg);
804 unsigned SR = *SRs; ++SRs)
805 if (Reg == TRI->getSubReg(SR, SubIdx) && RC->contains(SR))
806 return SR;
807 return 0;
808}
809
David Greene25133302007-06-08 17:18:56 +0000810/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
811/// which are the src/dst of the copy instruction CopyMI. This returns true
Evan Cheng0547bab2007-11-01 06:22:48 +0000812/// if the copy was successfully coalesced away. If it is not currently
813/// possible to coalesce this interval, but it may be possible if other
814/// things get coalesced, then it returns true by reference in 'Again'.
Evan Cheng70071432008-02-13 03:01:43 +0000815bool SimpleRegisterCoalescing::JoinCopy(CopyRec &TheCopy, bool &Again) {
Evan Cheng8fc9a102007-11-06 08:52:21 +0000816 MachineInstr *CopyMI = TheCopy.MI;
817
818 Again = false;
819 if (JoinedCopies.count(CopyMI))
820 return false; // Already done.
821
David Greene25133302007-06-08 17:18:56 +0000822 DOUT << li_->getInstructionIndex(CopyMI) << '\t' << *CopyMI;
823
Evan Chengc8d044e2008-02-15 18:24:29 +0000824 unsigned SrcReg;
825 unsigned DstReg;
826 bool isExtSubReg = CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG;
Evan Cheng7e073ba2008-04-09 20:57:25 +0000827 bool isInsSubReg = CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG;
Evan Chengc8d044e2008-02-15 18:24:29 +0000828 unsigned SubIdx = 0;
829 if (isExtSubReg) {
830 DstReg = CopyMI->getOperand(0).getReg();
831 SrcReg = CopyMI->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000832 } else if (isInsSubReg) {
833 if (CopyMI->getOperand(2).getSubReg()) {
834 DOUT << "\tSource of insert_subreg is already coalesced "
835 << "to another register.\n";
836 return false; // Not coalescable.
837 }
838 DstReg = CopyMI->getOperand(0).getReg();
839 SrcReg = CopyMI->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000840 } else if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
841 assert(0 && "Unrecognized copy instruction!");
842 return false;
Evan Cheng70071432008-02-13 03:01:43 +0000843 }
844
David Greene25133302007-06-08 17:18:56 +0000845 // If they are already joined we continue.
Evan Chengc8d044e2008-02-15 18:24:29 +0000846 if (SrcReg == DstReg) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000847 DOUT << "\tCopy already coalesced.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000848 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000849 }
850
Evan Chengc8d044e2008-02-15 18:24:29 +0000851 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
852 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
David Greene25133302007-06-08 17:18:56 +0000853
854 // If they are both physical registers, we cannot join them.
855 if (SrcIsPhys && DstIsPhys) {
Gabor Greife510b3a2007-07-09 12:00:59 +0000856 DOUT << "\tCan not coalesce physregs.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000857 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000858 }
859
860 // We only join virtual registers with allocatable physical registers.
Evan Chengc8d044e2008-02-15 18:24:29 +0000861 if (SrcIsPhys && !allocatableRegs_[SrcReg]) {
David Greene25133302007-06-08 17:18:56 +0000862 DOUT << "\tSrc reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000863 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000864 }
Evan Chengc8d044e2008-02-15 18:24:29 +0000865 if (DstIsPhys && !allocatableRegs_[DstReg]) {
David Greene25133302007-06-08 17:18:56 +0000866 DOUT << "\tDst reg is unallocatable physreg.\n";
Evan Cheng0547bab2007-11-01 06:22:48 +0000867 return false; // Not coalescable.
David Greene25133302007-06-08 17:18:56 +0000868 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000869
Evan Cheng32dfbea2007-10-12 08:50:34 +0000870 unsigned RealDstReg = 0;
Evan Cheng7e073ba2008-04-09 20:57:25 +0000871 unsigned RealSrcReg = 0;
872 if (isExtSubReg || isInsSubReg) {
873 SubIdx = CopyMI->getOperand(isExtSubReg ? 2 : 3).getImm();
874 if (SrcIsPhys && isExtSubReg) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000875 // r1024 = EXTRACT_SUBREG EAX, 0 then r1024 is really going to be
876 // coalesced with AX.
Evan Cheng621d1572008-04-17 00:06:42 +0000877 unsigned DstSubIdx = CopyMI->getOperand(0).getSubReg();
Evan Cheng639f4932008-04-17 07:58:04 +0000878 if (DstSubIdx) {
879 // r1024<2> = EXTRACT_SUBREG EAX, 2. Then r1024 has already been
880 // coalesced to a larger register so the subreg indices cancel out.
881 if (DstSubIdx != SubIdx) {
882 DOUT << "\t Sub-register indices mismatch.\n";
883 return false; // Not coalescable.
884 }
885 } else
Evan Cheng621d1572008-04-17 00:06:42 +0000886 SrcReg = tri_->getSubReg(SrcReg, SubIdx);
Evan Chengc8d044e2008-02-15 18:24:29 +0000887 SubIdx = 0;
Evan Cheng7e073ba2008-04-09 20:57:25 +0000888 } else if (DstIsPhys && isInsSubReg) {
889 // EAX = INSERT_SUBREG EAX, r1024, 0
Evan Cheng621d1572008-04-17 00:06:42 +0000890 unsigned SrcSubIdx = CopyMI->getOperand(2).getSubReg();
Evan Cheng639f4932008-04-17 07:58:04 +0000891 if (SrcSubIdx) {
892 // EAX = INSERT_SUBREG EAX, r1024<2>, 2 Then r1024 has already been
893 // coalesced to a larger register so the subreg indices cancel out.
894 if (SrcSubIdx != SubIdx) {
895 DOUT << "\t Sub-register indices mismatch.\n";
896 return false; // Not coalescable.
897 }
898 } else
899 DstReg = tri_->getSubReg(DstReg, SubIdx);
Evan Cheng7e073ba2008-04-09 20:57:25 +0000900 SubIdx = 0;
901 } else if ((DstIsPhys && isExtSubReg) || (SrcIsPhys && isInsSubReg)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000902 // If this is a extract_subreg where dst is a physical register, e.g.
903 // cl = EXTRACT_SUBREG reg1024, 1
904 // then create and update the actual physical register allocated to RHS.
Evan Cheng7e073ba2008-04-09 20:57:25 +0000905 // Ditto for
906 // reg1024 = INSERT_SUBREG r1024, cl, 1
Evan Cheng639f4932008-04-17 07:58:04 +0000907 if (CopyMI->getOperand(1).getSubReg()) {
908 DOUT << "\tSrc of extract_ / insert_subreg already coalesced with reg"
909 << " of a super-class.\n";
910 return false; // Not coalescable.
911 }
Evan Cheng7e073ba2008-04-09 20:57:25 +0000912 const TargetRegisterClass *RC =
913 mri_->getRegClass(isExtSubReg ? SrcReg : DstReg);
914 if (isExtSubReg) {
915 RealDstReg = getMatchingSuperReg(DstReg, SubIdx, RC, tri_);
916 assert(RealDstReg && "Invalid extra_subreg instruction!");
917 } else {
918 RealSrcReg = getMatchingSuperReg(SrcReg, SubIdx, RC, tri_);
919 assert(RealSrcReg && "Invalid extra_subreg instruction!");
Evan Cheng32dfbea2007-10-12 08:50:34 +0000920 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000921
922 // For this type of EXTRACT_SUBREG, conservatively
923 // check if the live interval of the source register interfere with the
924 // actual super physical register we are trying to coalesce with.
Evan Cheng7e073ba2008-04-09 20:57:25 +0000925 unsigned PhysReg = isExtSubReg ? RealDstReg : RealSrcReg;
926 LiveInterval &RHS = li_->getInterval(isExtSubReg ? SrcReg : DstReg);
927 if (li_->hasInterval(PhysReg) &&
928 RHS.overlaps(li_->getInterval(PhysReg))) {
Evan Cheng32dfbea2007-10-12 08:50:34 +0000929 DOUT << "Interfere with register ";
Evan Cheng7e073ba2008-04-09 20:57:25 +0000930 DEBUG(li_->getInterval(PhysReg).print(DOUT, tri_));
Evan Cheng0547bab2007-11-01 06:22:48 +0000931 return false; // Not coalescable
Evan Cheng32dfbea2007-10-12 08:50:34 +0000932 }
Evan Cheng7e073ba2008-04-09 20:57:25 +0000933 for (const unsigned* SR = tri_->getSubRegisters(PhysReg); *SR; ++SR)
Evan Cheng32dfbea2007-10-12 08:50:34 +0000934 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
935 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000936 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
Evan Cheng0547bab2007-11-01 06:22:48 +0000937 return false; // Not coalescable
Evan Cheng32dfbea2007-10-12 08:50:34 +0000938 }
Evan Chengc8d044e2008-02-15 18:24:29 +0000939 SubIdx = 0;
Evan Cheng0547bab2007-11-01 06:22:48 +0000940 } else {
Evan Cheng639f4932008-04-17 07:58:04 +0000941 unsigned OldSubIdx = isExtSubReg ? CopyMI->getOperand(0).getSubReg()
942 : CopyMI->getOperand(2).getSubReg();
943 if (OldSubIdx) {
944 if (OldSubIdx == SubIdx)
945 // r1024<2> = EXTRACT_SUBREG r1025, 2. Then r1024 has already been
946 // coalesced to a larger register so the subreg indices cancel out.
947 SubIdx = 0;
948 else {
949 DOUT << "\t Sub-register indices mismatch.\n";
950 return false; // Not coalescable.
951 }
952 }
953 if (SubIdx) {
954 unsigned LargeReg = isExtSubReg ? SrcReg : DstReg;
955 unsigned SmallReg = isExtSubReg ? DstReg : SrcReg;
956 unsigned LargeRegSize =
957 li_->getInterval(LargeReg).getSize() / InstrSlots::NUM;
958 unsigned SmallRegSize =
959 li_->getInterval(SmallReg).getSize() / InstrSlots::NUM;
960 const TargetRegisterClass *RC = mri_->getRegClass(SmallReg);
961 unsigned Threshold = allocatableRCRegs_[RC].count();
962 // Be conservative. If both sides are virtual registers, do not coalesce
963 // if this will cause a high use density interval to target a smaller
964 // set of registers.
965 if (SmallRegSize > Threshold || LargeRegSize > Threshold) {
966 LiveVariables::VarInfo &svi = lv_->getVarInfo(LargeReg);
967 LiveVariables::VarInfo &dvi = lv_->getVarInfo(SmallReg);
968 if ((float)dvi.NumUses / SmallRegSize <
969 (float)svi.NumUses / LargeRegSize) {
970 Again = true; // May be possible to coalesce later.
971 return false;
972 }
Evan Cheng0547bab2007-11-01 06:22:48 +0000973 }
974 }
Evan Cheng32dfbea2007-10-12 08:50:34 +0000975 }
Evan Chengc8d044e2008-02-15 18:24:29 +0000976 } else if (differingRegisterClasses(SrcReg, DstReg)) {
977 // FIXME: What if the resul of a EXTRACT_SUBREG is then coalesced
978 // with another? If it's the resulting destination register, then
979 // the subidx must be propagated to uses (but only those defined
980 // by the EXTRACT_SUBREG). If it's being coalesced into another
981 // register, it should be safe because register is assumed to have
982 // the register class of the super-register.
983
Evan Cheng32dfbea2007-10-12 08:50:34 +0000984 // If they are not of the same register class, we cannot join them.
David Greene25133302007-06-08 17:18:56 +0000985 DOUT << "\tSrc/Dest are different register classes.\n";
Evan Cheng32dfbea2007-10-12 08:50:34 +0000986 // Allow the coalescer to try again in case either side gets coalesced to
987 // a physical register that's compatible with the other side. e.g.
988 // r1024 = MOV32to32_ r1025
989 // but later r1024 is assigned EAX then r1025 may be coalesced with EAX.
Evan Cheng0547bab2007-11-01 06:22:48 +0000990 Again = true; // May be possible to coalesce later.
Evan Cheng32dfbea2007-10-12 08:50:34 +0000991 return false;
David Greene25133302007-06-08 17:18:56 +0000992 }
993
Evan Chengc8d044e2008-02-15 18:24:29 +0000994 LiveInterval &SrcInt = li_->getInterval(SrcReg);
995 LiveInterval &DstInt = li_->getInterval(DstReg);
996 assert(SrcInt.reg == SrcReg && DstInt.reg == DstReg &&
David Greene25133302007-06-08 17:18:56 +0000997 "Register mapping is horribly broken!");
998
Dan Gohman6f0d0242008-02-10 18:45:23 +0000999 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, tri_);
1000 DOUT << " and "; DstInt.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +00001001 DOUT << ": ";
1002
Evan Cheng3c88d742008-03-18 08:26:47 +00001003 // Check if it is necessary to propagate "isDead" property.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001004 if (!isExtSubReg && !isInsSubReg) {
1005 MachineOperand *mopd = CopyMI->findRegisterDefOperand(DstReg, false);
1006 bool isDead = mopd->isDead();
David Greene25133302007-06-08 17:18:56 +00001007
Evan Cheng7e073ba2008-04-09 20:57:25 +00001008 // We need to be careful about coalescing a source physical register with a
1009 // virtual register. Once the coalescing is done, it cannot be broken and
1010 // these are not spillable! If the destination interval uses are far away,
1011 // think twice about coalescing them!
1012 if (!isDead && (SrcIsPhys || DstIsPhys)) {
1013 LiveInterval &JoinVInt = SrcIsPhys ? DstInt : SrcInt;
1014 unsigned JoinVReg = SrcIsPhys ? DstReg : SrcReg;
1015 unsigned JoinPReg = SrcIsPhys ? SrcReg : DstReg;
1016 const TargetRegisterClass *RC = mri_->getRegClass(JoinVReg);
1017 unsigned Threshold = allocatableRCRegs_[RC].count() * 2;
1018 if (TheCopy.isBackEdge)
1019 Threshold *= 2; // Favors back edge copies.
David Greene25133302007-06-08 17:18:56 +00001020
Evan Cheng7e073ba2008-04-09 20:57:25 +00001021 // If the virtual register live interval is long but it has low use desity,
1022 // do not join them, instead mark the physical register as its allocation
1023 // preference.
1024 unsigned Length = JoinVInt.getSize() / InstrSlots::NUM;
1025 LiveVariables::VarInfo &vi = lv_->getVarInfo(JoinVReg);
1026 if (Length > Threshold &&
1027 (((float)vi.NumUses / Length) < (1.0 / Threshold))) {
1028 JoinVInt.preference = JoinPReg;
1029 ++numAborts;
1030 DOUT << "\tMay tie down a physical register, abort!\n";
1031 Again = true; // May be possible to coalesce later.
1032 return false;
1033 }
David Greene25133302007-06-08 17:18:56 +00001034 }
1035 }
1036
1037 // Okay, attempt to join these two intervals. On failure, this returns false.
1038 // Otherwise, if one of the intervals being joined is a physreg, this method
1039 // always canonicalizes DstInt to be it. The output "SrcInt" will not have
1040 // been modified, so we can use this information below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001041 bool Swapped = false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00001042 // If SrcInt is implicitly defined, it's safe to coalesce.
1043 bool isEmpty = SrcInt.empty();
Evan Cheng7e073ba2008-04-09 20:57:25 +00001044 if (isEmpty && !CanCoalesceWithImpDef(CopyMI, DstInt, SrcInt)) {
Evan Chengdb9b1c32008-04-03 16:41:54 +00001045 // Only coalesce an empty interval (defined by implicit_def) with
Evan Cheng7e073ba2008-04-09 20:57:25 +00001046 // another interval which has a valno defined by the CopyMI and the CopyMI
1047 // is a kill of the implicit def.
Evan Chengdb9b1c32008-04-03 16:41:54 +00001048 DOUT << "Not profitable!\n";
1049 return false;
1050 }
1051
1052 if (!isEmpty && !JoinIntervals(DstInt, SrcInt, Swapped)) {
Gabor Greife510b3a2007-07-09 12:00:59 +00001053 // Coalescing failed.
David Greene25133302007-06-08 17:18:56 +00001054
1055 // If we can eliminate the copy without merging the live ranges, do so now.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001056 if (!isExtSubReg && !isInsSubReg &&
Evan Cheng70071432008-02-13 03:01:43 +00001057 (AdjustCopiesBackFrom(SrcInt, DstInt, CopyMI) ||
1058 RemoveCopyByCommutingDef(SrcInt, DstInt, CopyMI))) {
Evan Cheng8fc9a102007-11-06 08:52:21 +00001059 JoinedCopies.insert(CopyMI);
David Greene25133302007-06-08 17:18:56 +00001060 return true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001061 }
Evan Cheng70071432008-02-13 03:01:43 +00001062
David Greene25133302007-06-08 17:18:56 +00001063 // Otherwise, we are unable to join the intervals.
1064 DOUT << "Interference!\n";
Evan Cheng0547bab2007-11-01 06:22:48 +00001065 Again = true; // May be possible to coalesce later.
David Greene25133302007-06-08 17:18:56 +00001066 return false;
1067 }
1068
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001069 LiveInterval *ResSrcInt = &SrcInt;
1070 LiveInterval *ResDstInt = &DstInt;
1071 if (Swapped) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001072 std::swap(SrcReg, DstReg);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001073 std::swap(ResSrcInt, ResDstInt);
1074 }
Evan Chengc8d044e2008-02-15 18:24:29 +00001075 assert(TargetRegisterInfo::isVirtualRegister(SrcReg) &&
David Greene25133302007-06-08 17:18:56 +00001076 "LiveInterval::join didn't work right!");
1077
1078 // If we're about to merge live ranges into a physical register live range,
1079 // we have to update any aliased register's live ranges to indicate that they
1080 // have clobbered values for this range.
Evan Chengc8d044e2008-02-15 18:24:29 +00001081 if (TargetRegisterInfo::isPhysicalRegister(DstReg)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001082 // If this is a extract_subreg where dst is a physical register, e.g.
1083 // cl = EXTRACT_SUBREG reg1024, 1
1084 // then create and update the actual physical register allocated to RHS.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001085 if (RealDstReg || RealSrcReg) {
1086 LiveInterval &RealInt =
1087 li_->getOrCreateInterval(RealDstReg ? RealDstReg : RealSrcReg);
Evan Chengf5c73592007-10-15 18:33:50 +00001088 SmallSet<const VNInfo*, 4> CopiedValNos;
1089 for (LiveInterval::Ranges::const_iterator I = ResSrcInt->ranges.begin(),
1090 E = ResSrcInt->ranges.end(); I != E; ++I) {
Evan Chengff7a3e52008-04-16 18:48:43 +00001091 const LiveRange *DstLR = ResDstInt->getLiveRangeContaining(I->start);
1092 assert(DstLR && "Invalid joined interval!");
Evan Chengf5c73592007-10-15 18:33:50 +00001093 const VNInfo *DstValNo = DstLR->valno;
1094 if (CopiedValNos.insert(DstValNo)) {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001095 VNInfo *ValNo = RealInt.getNextValue(DstValNo->def, DstValNo->copy,
1096 li_->getVNInfoAllocator());
Evan Chengc3fc7d92007-11-29 09:49:23 +00001097 ValNo->hasPHIKill = DstValNo->hasPHIKill;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001098 RealInt.addKills(ValNo, DstValNo->kills);
1099 RealInt.MergeValueInAsValue(*ResDstInt, DstValNo, ValNo);
Evan Chengf5c73592007-10-15 18:33:50 +00001100 }
Evan Cheng34729252007-10-14 10:08:34 +00001101 }
Evan Cheng7e073ba2008-04-09 20:57:25 +00001102
1103 DstReg = RealDstReg ? RealDstReg : RealSrcReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +00001104 }
1105
David Greene25133302007-06-08 17:18:56 +00001106 // Update the liveintervals of sub-registers.
Evan Chengc8d044e2008-02-15 18:24:29 +00001107 for (const unsigned *AS = tri_->getSubRegisters(DstReg); *AS; ++AS)
Evan Cheng32dfbea2007-10-12 08:50:34 +00001108 li_->getOrCreateInterval(*AS).MergeInClobberRanges(*ResSrcInt,
Evan Chengf3bb2e62007-09-05 21:46:51 +00001109 li_->getVNInfoAllocator());
David Greene25133302007-06-08 17:18:56 +00001110 } else {
1111 // Merge use info if the destination is a virtual register.
Evan Chengc8d044e2008-02-15 18:24:29 +00001112 LiveVariables::VarInfo& dVI = lv_->getVarInfo(DstReg);
1113 LiveVariables::VarInfo& sVI = lv_->getVarInfo(SrcReg);
David Greene25133302007-06-08 17:18:56 +00001114 dVI.NumUses += sVI.NumUses;
1115 }
1116
Evan Chengc8d044e2008-02-15 18:24:29 +00001117 // If this is a EXTRACT_SUBREG, make sure the result of coalescing is the
1118 // larger super-register.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001119 if ((isExtSubReg || isInsSubReg) && !SrcIsPhys && !DstIsPhys) {
1120 if ((isExtSubReg && !Swapped) || (isInsSubReg && Swapped)) {
Evan Cheng32dfbea2007-10-12 08:50:34 +00001121 ResSrcInt->Copy(*ResDstInt, li_->getVNInfoAllocator());
Evan Chengc8d044e2008-02-15 18:24:29 +00001122 std::swap(SrcReg, DstReg);
Evan Cheng32dfbea2007-10-12 08:50:34 +00001123 std::swap(ResSrcInt, ResDstInt);
1124 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00001125 }
1126
Evan Cheng8fc9a102007-11-06 08:52:21 +00001127 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001128 // Add all copies that define val# in the source interval into the queue.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001129 for (LiveInterval::const_vni_iterator i = ResSrcInt->vni_begin(),
1130 e = ResSrcInt->vni_end(); i != e; ++i) {
1131 const VNInfo *vni = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001132 if (!vni->def || vni->def == ~1U || vni->def == ~0U)
1133 continue;
1134 MachineInstr *CopyMI = li_->getInstructionFromIndex(vni->def);
1135 unsigned NewSrcReg, NewDstReg;
1136 if (CopyMI &&
1137 JoinedCopies.count(CopyMI) == 0 &&
1138 tii_->isMoveInstr(*CopyMI, NewSrcReg, NewDstReg)) {
1139 unsigned LoopDepth = loopInfo->getLoopDepth(CopyMI->getParent());
1140 JoinQueue->push(CopyRec(CopyMI, LoopDepth,
1141 isBackEdgeCopy(CopyMI, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001142 }
1143 }
1144 }
1145
Evan Chengc8d044e2008-02-15 18:24:29 +00001146 // Remember to delete the copy instruction.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001147 JoinedCopies.insert(CopyMI);
Evan Chengc8d044e2008-02-15 18:24:29 +00001148
Evan Cheng4ff3f1c2008-03-10 08:11:32 +00001149 // Some live range has been lengthened due to colaescing, eliminate the
1150 // unnecessary kills.
1151 RemoveUnnecessaryKills(SrcReg, *ResDstInt);
1152 if (TargetRegisterInfo::isVirtualRegister(DstReg))
1153 RemoveUnnecessaryKills(DstReg, *ResDstInt);
1154
Evan Chengc8d044e2008-02-15 18:24:29 +00001155 // SrcReg is guarateed to be the register whose live interval that is
1156 // being merged.
1157 li_->removeInterval(SrcReg);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001158 if (isInsSubReg)
1159 // Avoid:
1160 // r1024 = op
1161 // r1024 = implicit_def
1162 // ...
1163 // = r1024
1164 RemoveDeadImpDef(DstReg, *ResDstInt);
Evan Chengc8d044e2008-02-15 18:24:29 +00001165 UpdateRegDefsUses(SrcReg, DstReg, SubIdx);
1166
Evan Chengdb9b1c32008-04-03 16:41:54 +00001167 if (isEmpty) {
1168 // Now the copy is being coalesced away, the val# previously defined
1169 // by the copy is being defined by an IMPLICIT_DEF which defines a zero
1170 // length interval. Remove the val#.
1171 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
Evan Chengff7a3e52008-04-16 18:48:43 +00001172 const LiveRange *LR = ResDstInt->getLiveRangeContaining(CopyIdx);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001173 VNInfo *ImpVal = LR->valno;
1174 assert(ImpVal->def == CopyIdx);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001175 unsigned NextDef = LR->end;
1176 RemoveCopiesFromValNo(*ResDstInt, ImpVal);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001177 ResDstInt->removeValNo(ImpVal);
Evan Cheng7e073ba2008-04-09 20:57:25 +00001178 LR = ResDstInt->FindLiveRangeContaining(NextDef);
1179 if (LR != ResDstInt->end() && LR->valno->def == NextDef) {
1180 // Special case: vr1024 = implicit_def
1181 // vr1024 = insert_subreg vr1024, vr1025, c
1182 // The insert_subreg becomes a "copy" that defines a val# which can itself
1183 // be coalesced away.
1184 MachineInstr *DefMI = li_->getInstructionFromIndex(NextDef);
1185 if (DefMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
1186 LR->valno->copy = DefMI;
1187 }
Evan Chengdb9b1c32008-04-03 16:41:54 +00001188 }
1189
1190 DOUT << "\n\t\tJoined. Result = "; ResDstInt->print(DOUT, tri_);
1191 DOUT << "\n";
1192
David Greene25133302007-06-08 17:18:56 +00001193 ++numJoins;
1194 return true;
1195}
1196
1197/// ComputeUltimateVN - Assuming we are going to join two live intervals,
1198/// compute what the resultant value numbers for each value in the input two
1199/// ranges will be. This is complicated by copies between the two which can
1200/// and will commonly cause multiple value numbers to be merged into one.
1201///
1202/// VN is the value number that we're trying to resolve. InstDefiningValue
1203/// keeps track of the new InstDefiningValue assignment for the result
1204/// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
1205/// whether a value in this or other is a copy from the opposite set.
1206/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
1207/// already been assigned.
1208///
1209/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
1210/// contains the value number the copy is from.
1211///
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001212static unsigned ComputeUltimateVN(VNInfo *VNI,
1213 SmallVector<VNInfo*, 16> &NewVNInfo,
Evan Chengfadfb5b2007-08-31 21:23:06 +00001214 DenseMap<VNInfo*, VNInfo*> &ThisFromOther,
1215 DenseMap<VNInfo*, VNInfo*> &OtherFromThis,
David Greene25133302007-06-08 17:18:56 +00001216 SmallVector<int, 16> &ThisValNoAssignments,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001217 SmallVector<int, 16> &OtherValNoAssignments) {
1218 unsigned VN = VNI->id;
1219
David Greene25133302007-06-08 17:18:56 +00001220 // If the VN has already been computed, just return it.
1221 if (ThisValNoAssignments[VN] >= 0)
1222 return ThisValNoAssignments[VN];
1223// assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001224
David Greene25133302007-06-08 17:18:56 +00001225 // If this val is not a copy from the other val, then it must be a new value
1226 // number in the destination.
Evan Chengfadfb5b2007-08-31 21:23:06 +00001227 DenseMap<VNInfo*, VNInfo*>::iterator I = ThisFromOther.find(VNI);
Evan Chengc14b1442007-08-31 08:04:17 +00001228 if (I == ThisFromOther.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001229 NewVNInfo.push_back(VNI);
1230 return ThisValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00001231 }
Evan Chengc14b1442007-08-31 08:04:17 +00001232 VNInfo *OtherValNo = I->second;
David Greene25133302007-06-08 17:18:56 +00001233
1234 // Otherwise, this *is* a copy from the RHS. If the other side has already
1235 // been computed, return it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001236 if (OtherValNoAssignments[OtherValNo->id] >= 0)
1237 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo->id];
David Greene25133302007-06-08 17:18:56 +00001238
1239 // Mark this value number as currently being computed, then ask what the
1240 // ultimate value # of the other value is.
1241 ThisValNoAssignments[VN] = -2;
1242 unsigned UltimateVN =
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001243 ComputeUltimateVN(OtherValNo, NewVNInfo, OtherFromThis, ThisFromOther,
1244 OtherValNoAssignments, ThisValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001245 return ThisValNoAssignments[VN] = UltimateVN;
1246}
1247
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001248static bool InVector(VNInfo *Val, const SmallVector<VNInfo*, 8> &V) {
David Greene25133302007-06-08 17:18:56 +00001249 return std::find(V.begin(), V.end(), Val) != V.end();
1250}
1251
Evan Cheng7e073ba2008-04-09 20:57:25 +00001252/// RangeIsDefinedByCopyFromReg - Return true if the specified live range of
1253/// the specified live interval is defined by a copy from the specified
1254/// register.
1255bool SimpleRegisterCoalescing::RangeIsDefinedByCopyFromReg(LiveInterval &li,
1256 LiveRange *LR,
1257 unsigned Reg) {
1258 unsigned SrcReg = li_->getVNInfoSourceReg(LR->valno);
1259 if (SrcReg == Reg)
1260 return true;
1261 if (LR->valno->def == ~0U &&
1262 TargetRegisterInfo::isPhysicalRegister(li.reg) &&
1263 *tri_->getSuperRegisters(li.reg)) {
1264 // It's a sub-register live interval, we may not have precise information.
1265 // Re-compute it.
1266 MachineInstr *DefMI = li_->getInstructionFromIndex(LR->start);
1267 unsigned SrcReg, DstReg;
1268 if (tii_->isMoveInstr(*DefMI, SrcReg, DstReg) &&
1269 DstReg == li.reg && SrcReg == Reg) {
1270 // Cache computed info.
1271 LR->valno->def = LR->start;
1272 LR->valno->copy = DefMI;
1273 return true;
1274 }
1275 }
1276 return false;
1277}
1278
David Greene25133302007-06-08 17:18:56 +00001279/// SimpleJoin - Attempt to joint the specified interval into this one. The
1280/// caller of this method must guarantee that the RHS only contains a single
1281/// value number and that the RHS is not defined by a copy from this
1282/// interval. This returns false if the intervals are not joinable, or it
1283/// joins them and returns true.
Bill Wendling2674d712008-01-04 08:59:18 +00001284bool SimpleRegisterCoalescing::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS){
David Greene25133302007-06-08 17:18:56 +00001285 assert(RHS.containsOneValue());
1286
1287 // Some number (potentially more than one) value numbers in the current
1288 // interval may be defined as copies from the RHS. Scan the overlapping
1289 // portions of the LHS and RHS, keeping track of this and looking for
1290 // overlapping live ranges that are NOT defined as copies. If these exist, we
Gabor Greife510b3a2007-07-09 12:00:59 +00001291 // cannot coalesce.
David Greene25133302007-06-08 17:18:56 +00001292
1293 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
1294 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
1295
1296 if (LHSIt->start < RHSIt->start) {
1297 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
1298 if (LHSIt != LHS.begin()) --LHSIt;
1299 } else if (RHSIt->start < LHSIt->start) {
1300 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1301 if (RHSIt != RHS.begin()) --RHSIt;
1302 }
1303
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001304 SmallVector<VNInfo*, 8> EliminatedLHSVals;
David Greene25133302007-06-08 17:18:56 +00001305
1306 while (1) {
1307 // Determine if these live intervals overlap.
1308 bool Overlaps = false;
1309 if (LHSIt->start <= RHSIt->start)
1310 Overlaps = LHSIt->end > RHSIt->start;
1311 else
1312 Overlaps = RHSIt->end > LHSIt->start;
1313
1314 // If the live intervals overlap, there are two interesting cases: if the
1315 // LHS interval is defined by a copy from the RHS, it's ok and we record
1316 // that the LHS value # is the same as the RHS. If it's not, then we cannot
Gabor Greife510b3a2007-07-09 12:00:59 +00001317 // coalesce these live ranges and we bail out.
David Greene25133302007-06-08 17:18:56 +00001318 if (Overlaps) {
1319 // If we haven't already recorded that this value # is safe, check it.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001320 if (!InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001321 // Copy from the RHS?
Evan Cheng7e073ba2008-04-09 20:57:25 +00001322 if (!RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg))
David Greene25133302007-06-08 17:18:56 +00001323 return false; // Nope, bail out.
1324
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001325 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001326 }
1327
1328 // We know this entire LHS live range is okay, so skip it now.
1329 if (++LHSIt == LHSEnd) break;
1330 continue;
1331 }
1332
1333 if (LHSIt->end < RHSIt->end) {
1334 if (++LHSIt == LHSEnd) break;
1335 } else {
1336 // One interesting case to check here. It's possible that we have
1337 // something like "X3 = Y" which defines a new value number in the LHS,
1338 // and is the last use of this liverange of the RHS. In this case, we
Gabor Greife510b3a2007-07-09 12:00:59 +00001339 // want to notice this copy (so that it gets coalesced away) even though
David Greene25133302007-06-08 17:18:56 +00001340 // the live ranges don't actually overlap.
1341 if (LHSIt->start == RHSIt->end) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001342 if (InVector(LHSIt->valno, EliminatedLHSVals)) {
David Greene25133302007-06-08 17:18:56 +00001343 // We already know that this value number is going to be merged in
Gabor Greife510b3a2007-07-09 12:00:59 +00001344 // if coalescing succeeds. Just skip the liverange.
David Greene25133302007-06-08 17:18:56 +00001345 if (++LHSIt == LHSEnd) break;
1346 } else {
1347 // Otherwise, if this is a copy from the RHS, mark it as being merged
1348 // in.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001349 if (RangeIsDefinedByCopyFromReg(LHS, LHSIt, RHS.reg)) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001350 EliminatedLHSVals.push_back(LHSIt->valno);
David Greene25133302007-06-08 17:18:56 +00001351
1352 // We know this entire LHS live range is okay, so skip it now.
1353 if (++LHSIt == LHSEnd) break;
1354 }
1355 }
1356 }
1357
1358 if (++RHSIt == RHSEnd) break;
1359 }
1360 }
1361
Gabor Greife510b3a2007-07-09 12:00:59 +00001362 // If we got here, we know that the coalescing will be successful and that
David Greene25133302007-06-08 17:18:56 +00001363 // the value numbers in EliminatedLHSVals will all be merged together. Since
1364 // the most common case is that EliminatedLHSVals has a single number, we
1365 // optimize for it: if there is more than one value, we merge them all into
1366 // the lowest numbered one, then handle the interval as if we were merging
1367 // with one value number.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001368 VNInfo *LHSValNo;
David Greene25133302007-06-08 17:18:56 +00001369 if (EliminatedLHSVals.size() > 1) {
1370 // Loop through all the equal value numbers merging them into the smallest
1371 // one.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001372 VNInfo *Smallest = EliminatedLHSVals[0];
David Greene25133302007-06-08 17:18:56 +00001373 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001374 if (EliminatedLHSVals[i]->id < Smallest->id) {
David Greene25133302007-06-08 17:18:56 +00001375 // Merge the current notion of the smallest into the smaller one.
1376 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1377 Smallest = EliminatedLHSVals[i];
1378 } else {
1379 // Merge into the smallest.
1380 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1381 }
1382 }
1383 LHSValNo = Smallest;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001384 } else if (EliminatedLHSVals.empty()) {
1385 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1386 *tri_->getSuperRegisters(LHS.reg))
1387 // Imprecise sub-register information. Can't handle it.
1388 return false;
1389 assert(0 && "No copies from the RHS?");
David Greene25133302007-06-08 17:18:56 +00001390 } else {
David Greene25133302007-06-08 17:18:56 +00001391 LHSValNo = EliminatedLHSVals[0];
1392 }
1393
1394 // Okay, now that there is a single LHS value number that we're merging the
1395 // RHS into, update the value number info for the LHS to indicate that the
1396 // value number is defined where the RHS value number was.
Evan Chengf3bb2e62007-09-05 21:46:51 +00001397 const VNInfo *VNI = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00001398 LHSValNo->def = VNI->def;
1399 LHSValNo->copy = VNI->copy;
David Greene25133302007-06-08 17:18:56 +00001400
1401 // Okay, the final step is to loop over the RHS live intervals, adding them to
1402 // the LHS.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001403 LHSValNo->hasPHIKill |= VNI->hasPHIKill;
Evan Chengf3bb2e62007-09-05 21:46:51 +00001404 LHS.addKills(LHSValNo, VNI->kills);
Evan Cheng430a7b02007-08-14 01:56:58 +00001405 LHS.MergeRangesInAsValue(RHS, LHSValNo);
David Greene25133302007-06-08 17:18:56 +00001406 LHS.weight += RHS.weight;
1407 if (RHS.preference && !LHS.preference)
1408 LHS.preference = RHS.preference;
1409
1410 return true;
1411}
1412
1413/// JoinIntervals - Attempt to join these two intervals. On failure, this
1414/// returns false. Otherwise, if one of the intervals being joined is a
1415/// physreg, this method always canonicalizes LHS to be it. The output
1416/// "RHS" will not have been modified, so we can use this information
1417/// below to update aliases.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001418bool SimpleRegisterCoalescing::JoinIntervals(LiveInterval &LHS,
1419 LiveInterval &RHS, bool &Swapped) {
David Greene25133302007-06-08 17:18:56 +00001420 // Compute the final value assignment, assuming that the live ranges can be
Gabor Greife510b3a2007-07-09 12:00:59 +00001421 // coalesced.
David Greene25133302007-06-08 17:18:56 +00001422 SmallVector<int, 16> LHSValNoAssignments;
1423 SmallVector<int, 16> RHSValNoAssignments;
Evan Chengfadfb5b2007-08-31 21:23:06 +00001424 DenseMap<VNInfo*, VNInfo*> LHSValsDefinedFromRHS;
1425 DenseMap<VNInfo*, VNInfo*> RHSValsDefinedFromLHS;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001426 SmallVector<VNInfo*, 16> NewVNInfo;
David Greene25133302007-06-08 17:18:56 +00001427
1428 // If a live interval is a physical register, conservatively check if any
1429 // of its sub-registers is overlapping the live interval of the virtual
1430 // register. If so, do not coalesce.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001431 if (TargetRegisterInfo::isPhysicalRegister(LHS.reg) &&
1432 *tri_->getSubRegisters(LHS.reg)) {
1433 for (const unsigned* SR = tri_->getSubRegisters(LHS.reg); *SR; ++SR)
David Greene25133302007-06-08 17:18:56 +00001434 if (li_->hasInterval(*SR) && RHS.overlaps(li_->getInterval(*SR))) {
1435 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001436 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
David Greene25133302007-06-08 17:18:56 +00001437 return false;
1438 }
Dan Gohman6f0d0242008-02-10 18:45:23 +00001439 } else if (TargetRegisterInfo::isPhysicalRegister(RHS.reg) &&
1440 *tri_->getSubRegisters(RHS.reg)) {
1441 for (const unsigned* SR = tri_->getSubRegisters(RHS.reg); *SR; ++SR)
David Greene25133302007-06-08 17:18:56 +00001442 if (li_->hasInterval(*SR) && LHS.overlaps(li_->getInterval(*SR))) {
1443 DOUT << "Interfere with sub-register ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001444 DEBUG(li_->getInterval(*SR).print(DOUT, tri_));
David Greene25133302007-06-08 17:18:56 +00001445 return false;
1446 }
1447 }
1448
1449 // Compute ultimate value numbers for the LHS and RHS values.
1450 if (RHS.containsOneValue()) {
1451 // Copies from a liveinterval with a single value are simple to handle and
1452 // very common, handle the special case here. This is important, because
1453 // often RHS is small and LHS is large (e.g. a physreg).
1454
1455 // Find out if the RHS is defined as a copy from some value in the LHS.
Evan Cheng4f8ff162007-08-11 00:59:19 +00001456 int RHSVal0DefinedFromLHS = -1;
David Greene25133302007-06-08 17:18:56 +00001457 int RHSValID = -1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001458 VNInfo *RHSValNoInfo = NULL;
Evan Chengf3bb2e62007-09-05 21:46:51 +00001459 VNInfo *RHSValNoInfo0 = RHS.getValNumInfo(0);
Evan Chengc8d044e2008-02-15 18:24:29 +00001460 unsigned RHSSrcReg = li_->getVNInfoSourceReg(RHSValNoInfo0);
1461 if ((RHSSrcReg == 0 || RHSSrcReg != LHS.reg)) {
David Greene25133302007-06-08 17:18:56 +00001462 // If RHS is not defined as a copy from the LHS, we can use simpler and
Gabor Greife510b3a2007-07-09 12:00:59 +00001463 // faster checks to see if the live ranges are coalescable. This joiner
David Greene25133302007-06-08 17:18:56 +00001464 // can't swap the LHS/RHS intervals though.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001465 if (!TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
David Greene25133302007-06-08 17:18:56 +00001466 return SimpleJoin(LHS, RHS);
1467 } else {
Evan Chengc14b1442007-08-31 08:04:17 +00001468 RHSValNoInfo = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00001469 }
1470 } else {
1471 // It was defined as a copy from the LHS, find out what value # it is.
Evan Chengc14b1442007-08-31 08:04:17 +00001472 RHSValNoInfo = LHS.getLiveRangeContaining(RHSValNoInfo0->def-1)->valno;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001473 RHSValID = RHSValNoInfo->id;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001474 RHSVal0DefinedFromLHS = RHSValID;
David Greene25133302007-06-08 17:18:56 +00001475 }
1476
1477 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1478 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001479 NewVNInfo.resize(LHS.getNumValNums(), NULL);
David Greene25133302007-06-08 17:18:56 +00001480
1481 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1482 // should now get updated.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001483 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1484 i != e; ++i) {
1485 VNInfo *VNI = *i;
1486 unsigned VN = VNI->id;
Evan Chengc8d044e2008-02-15 18:24:29 +00001487 if (unsigned LHSSrcReg = li_->getVNInfoSourceReg(VNI)) {
1488 if (LHSSrcReg != RHS.reg) {
David Greene25133302007-06-08 17:18:56 +00001489 // If this is not a copy from the RHS, its value number will be
Gabor Greife510b3a2007-07-09 12:00:59 +00001490 // unmodified by the coalescing.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001491 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00001492 LHSValNoAssignments[VN] = VN;
1493 } else if (RHSValID == -1) {
1494 // Otherwise, it is a copy from the RHS, and we don't already have a
1495 // value# for it. Keep the current value number, but remember it.
1496 LHSValNoAssignments[VN] = RHSValID = VN;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001497 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00001498 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
David Greene25133302007-06-08 17:18:56 +00001499 } else {
1500 // Otherwise, use the specified value #.
1501 LHSValNoAssignments[VN] = RHSValID;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001502 if (VN == (unsigned)RHSValID) { // Else this val# is dead.
1503 NewVNInfo[VN] = RHSValNoInfo;
Evan Chengc14b1442007-08-31 08:04:17 +00001504 LHSValsDefinedFromRHS[VNI] = RHSValNoInfo0;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001505 }
David Greene25133302007-06-08 17:18:56 +00001506 }
1507 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001508 NewVNInfo[VN] = VNI;
David Greene25133302007-06-08 17:18:56 +00001509 LHSValNoAssignments[VN] = VN;
1510 }
1511 }
1512
1513 assert(RHSValID != -1 && "Didn't find value #?");
1514 RHSValNoAssignments[0] = RHSValID;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001515 if (RHSVal0DefinedFromLHS != -1) {
Evan Cheng34301352007-09-01 02:03:17 +00001516 // This path doesn't go through ComputeUltimateVN so just set
1517 // it to anything.
1518 RHSValsDefinedFromLHS[RHSValNoInfo0] = (VNInfo*)1;
Evan Cheng4f8ff162007-08-11 00:59:19 +00001519 }
David Greene25133302007-06-08 17:18:56 +00001520 } else {
1521 // Loop over the value numbers of the LHS, seeing if any are defined from
1522 // the RHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001523 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1524 i != e; ++i) {
1525 VNInfo *VNI = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001526 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00001527 continue;
1528
1529 // DstReg is known to be a register in the LHS interval. If the src is
1530 // from the RHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00001531 if (li_->getVNInfoSourceReg(VNI) != RHS.reg)
David Greene25133302007-06-08 17:18:56 +00001532 continue;
1533
1534 // Figure out the value # from the RHS.
Bill Wendling2674d712008-01-04 08:59:18 +00001535 LHSValsDefinedFromRHS[VNI]=RHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00001536 }
1537
1538 // Loop over the value numbers of the RHS, seeing if any are defined from
1539 // the LHS.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001540 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1541 i != e; ++i) {
1542 VNInfo *VNI = *i;
Evan Chengc8d044e2008-02-15 18:24:29 +00001543 if (VNI->def == ~1U || VNI->copy == 0) // Src not defined by a copy?
David Greene25133302007-06-08 17:18:56 +00001544 continue;
1545
1546 // DstReg is known to be a register in the RHS interval. If the src is
1547 // from the LHS interval, we can use its value #.
Evan Chengc8d044e2008-02-15 18:24:29 +00001548 if (li_->getVNInfoSourceReg(VNI) != LHS.reg)
David Greene25133302007-06-08 17:18:56 +00001549 continue;
1550
1551 // Figure out the value # from the LHS.
Bill Wendling2674d712008-01-04 08:59:18 +00001552 RHSValsDefinedFromLHS[VNI]=LHS.getLiveRangeContaining(VNI->def-1)->valno;
David Greene25133302007-06-08 17:18:56 +00001553 }
1554
1555 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1556 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001557 NewVNInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
David Greene25133302007-06-08 17:18:56 +00001558
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001559 for (LiveInterval::vni_iterator i = LHS.vni_begin(), e = LHS.vni_end();
1560 i != e; ++i) {
1561 VNInfo *VNI = *i;
1562 unsigned VN = VNI->id;
1563 if (LHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +00001564 continue;
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001565 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00001566 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001567 LHSValNoAssignments, RHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001568 }
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001569 for (LiveInterval::vni_iterator i = RHS.vni_begin(), e = RHS.vni_end();
1570 i != e; ++i) {
1571 VNInfo *VNI = *i;
1572 unsigned VN = VNI->id;
1573 if (RHSValNoAssignments[VN] >= 0 || VNI->def == ~1U)
David Greene25133302007-06-08 17:18:56 +00001574 continue;
1575 // If this value number isn't a copy from the LHS, it's a new number.
Evan Chengc14b1442007-08-31 08:04:17 +00001576 if (RHSValsDefinedFromLHS.find(VNI) == RHSValsDefinedFromLHS.end()) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001577 NewVNInfo.push_back(VNI);
1578 RHSValNoAssignments[VN] = NewVNInfo.size()-1;
David Greene25133302007-06-08 17:18:56 +00001579 continue;
1580 }
1581
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001582 ComputeUltimateVN(VNI, NewVNInfo,
David Greene25133302007-06-08 17:18:56 +00001583 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001584 RHSValNoAssignments, LHSValNoAssignments);
David Greene25133302007-06-08 17:18:56 +00001585 }
1586 }
1587
1588 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
Gabor Greife510b3a2007-07-09 12:00:59 +00001589 // interval lists to see if these intervals are coalescable.
David Greene25133302007-06-08 17:18:56 +00001590 LiveInterval::const_iterator I = LHS.begin();
1591 LiveInterval::const_iterator IE = LHS.end();
1592 LiveInterval::const_iterator J = RHS.begin();
1593 LiveInterval::const_iterator JE = RHS.end();
1594
1595 // Skip ahead until the first place of potential sharing.
1596 if (I->start < J->start) {
1597 I = std::upper_bound(I, IE, J->start);
1598 if (I != LHS.begin()) --I;
1599 } else if (J->start < I->start) {
1600 J = std::upper_bound(J, JE, I->start);
1601 if (J != RHS.begin()) --J;
1602 }
1603
1604 while (1) {
1605 // Determine if these two live ranges overlap.
1606 bool Overlaps;
1607 if (I->start < J->start) {
1608 Overlaps = I->end > J->start;
1609 } else {
1610 Overlaps = J->end > I->start;
1611 }
1612
1613 // If so, check value # info to determine if they are really different.
1614 if (Overlaps) {
1615 // If the live range overlap will map to the same value number in the
Gabor Greife510b3a2007-07-09 12:00:59 +00001616 // result liverange, we can still coalesce them. If not, we can't.
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001617 if (LHSValNoAssignments[I->valno->id] !=
1618 RHSValNoAssignments[J->valno->id])
David Greene25133302007-06-08 17:18:56 +00001619 return false;
1620 }
1621
1622 if (I->end < J->end) {
1623 ++I;
1624 if (I == IE) break;
1625 } else {
1626 ++J;
1627 if (J == JE) break;
1628 }
1629 }
1630
Evan Cheng34729252007-10-14 10:08:34 +00001631 // Update kill info. Some live ranges are extended due to copy coalescing.
1632 for (DenseMap<VNInfo*, VNInfo*>::iterator I = LHSValsDefinedFromRHS.begin(),
1633 E = LHSValsDefinedFromRHS.end(); I != E; ++I) {
1634 VNInfo *VNI = I->first;
1635 unsigned LHSValID = LHSValNoAssignments[VNI->id];
1636 LiveInterval::removeKill(NewVNInfo[LHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +00001637 NewVNInfo[LHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +00001638 RHS.addKills(NewVNInfo[LHSValID], VNI->kills);
1639 }
1640
1641 // Update kill info. Some live ranges are extended due to copy coalescing.
1642 for (DenseMap<VNInfo*, VNInfo*>::iterator I = RHSValsDefinedFromLHS.begin(),
1643 E = RHSValsDefinedFromLHS.end(); I != E; ++I) {
1644 VNInfo *VNI = I->first;
1645 unsigned RHSValID = RHSValNoAssignments[VNI->id];
1646 LiveInterval::removeKill(NewVNInfo[RHSValID], VNI->def);
Evan Chengc3fc7d92007-11-29 09:49:23 +00001647 NewVNInfo[RHSValID]->hasPHIKill |= VNI->hasPHIKill;
Evan Cheng34729252007-10-14 10:08:34 +00001648 LHS.addKills(NewVNInfo[RHSValID], VNI->kills);
1649 }
1650
Gabor Greife510b3a2007-07-09 12:00:59 +00001651 // If we get here, we know that we can coalesce the live ranges. Ask the
1652 // intervals to coalesce themselves now.
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001653 if ((RHS.ranges.size() > LHS.ranges.size() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00001654 TargetRegisterInfo::isVirtualRegister(LHS.reg)) ||
1655 TargetRegisterInfo::isPhysicalRegister(RHS.reg)) {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001656 RHS.join(LHS, &RHSValNoAssignments[0], &LHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001657 Swapped = true;
1658 } else {
Evan Cheng7ecb38b2007-08-29 20:45:00 +00001659 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0], NewVNInfo);
Evan Cheng1a66f0a2007-08-28 08:28:51 +00001660 Swapped = false;
1661 }
David Greene25133302007-06-08 17:18:56 +00001662 return true;
1663}
1664
1665namespace {
1666 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1667 // depth of the basic block (the unsigned), and then on the MBB number.
1668 struct DepthMBBCompare {
1669 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1670 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1671 if (LHS.first > RHS.first) return true; // Deeper loops first
1672 return LHS.first == RHS.first &&
1673 LHS.second->getNumber() < RHS.second->getNumber();
1674 }
1675 };
1676}
1677
Evan Cheng8fc9a102007-11-06 08:52:21 +00001678/// getRepIntervalSize - Returns the size of the interval that represents the
1679/// specified register.
1680template<class SF>
1681unsigned JoinPriorityQueue<SF>::getRepIntervalSize(unsigned Reg) {
1682 return Rc->getRepIntervalSize(Reg);
1683}
1684
1685/// CopyRecSort::operator - Join priority queue sorting function.
1686///
1687bool CopyRecSort::operator()(CopyRec left, CopyRec right) const {
1688 // Inner loops first.
1689 if (left.LoopDepth > right.LoopDepth)
1690 return false;
Evan Chengc8d044e2008-02-15 18:24:29 +00001691 else if (left.LoopDepth == right.LoopDepth)
Evan Cheng8fc9a102007-11-06 08:52:21 +00001692 if (left.isBackEdge && !right.isBackEdge)
1693 return false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001694 return true;
1695}
1696
Gabor Greife510b3a2007-07-09 12:00:59 +00001697void SimpleRegisterCoalescing::CopyCoalesceInMBB(MachineBasicBlock *MBB,
Evan Cheng8b0b8742007-10-16 08:04:24 +00001698 std::vector<CopyRec> &TryAgain) {
David Greene25133302007-06-08 17:18:56 +00001699 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Evan Cheng8fc9a102007-11-06 08:52:21 +00001700
Evan Cheng8b0b8742007-10-16 08:04:24 +00001701 std::vector<CopyRec> VirtCopies;
1702 std::vector<CopyRec> PhysCopies;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001703 std::vector<CopyRec> ImpDefCopies;
Evan Cheng22f07ff2007-12-11 02:09:15 +00001704 unsigned LoopDepth = loopInfo->getLoopDepth(MBB);
David Greene25133302007-06-08 17:18:56 +00001705 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1706 MII != E;) {
1707 MachineInstr *Inst = MII++;
1708
Evan Cheng32dfbea2007-10-12 08:50:34 +00001709 // If this isn't a copy nor a extract_subreg, we can't join intervals.
David Greene25133302007-06-08 17:18:56 +00001710 unsigned SrcReg, DstReg;
Evan Cheng32dfbea2007-10-12 08:50:34 +00001711 if (Inst->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1712 DstReg = Inst->getOperand(0).getReg();
1713 SrcReg = Inst->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +00001714 } else if (Inst->getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
1715 DstReg = Inst->getOperand(0).getReg();
1716 SrcReg = Inst->getOperand(2).getReg();
Evan Cheng32dfbea2007-10-12 08:50:34 +00001717 } else if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg))
1718 continue;
Evan Cheng8b0b8742007-10-16 08:04:24 +00001719
Evan Chengc8d044e2008-02-15 18:24:29 +00001720 bool SrcIsPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
1721 bool DstIsPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
Evan Cheng8fc9a102007-11-06 08:52:21 +00001722 if (NewHeuristic) {
Evan Chengc8d044e2008-02-15 18:24:29 +00001723 JoinQueue->push(CopyRec(Inst, LoopDepth, isBackEdgeCopy(Inst, DstReg)));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001724 } else {
Evan Cheng7e073ba2008-04-09 20:57:25 +00001725 if (li_->hasInterval(SrcReg) && li_->getInterval(SrcReg).empty())
1726 ImpDefCopies.push_back(CopyRec(Inst, 0, false));
1727 else if (SrcIsPhys || DstIsPhys)
Evan Chengc8d044e2008-02-15 18:24:29 +00001728 PhysCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001729 else
Evan Chengc8d044e2008-02-15 18:24:29 +00001730 VirtCopies.push_back(CopyRec(Inst, 0, false));
Evan Cheng8fc9a102007-11-06 08:52:21 +00001731 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00001732 }
1733
Evan Cheng8fc9a102007-11-06 08:52:21 +00001734 if (NewHeuristic)
1735 return;
1736
Evan Cheng7e073ba2008-04-09 20:57:25 +00001737 // Try coalescing implicit copies first, followed by copies to / from
1738 // physical registers, then finally copies from virtual registers to
1739 // virtual registers.
1740 for (unsigned i = 0, e = ImpDefCopies.size(); i != e; ++i) {
1741 CopyRec &TheCopy = ImpDefCopies[i];
1742 bool Again = false;
1743 if (!JoinCopy(TheCopy, Again))
1744 if (Again)
1745 TryAgain.push_back(TheCopy);
1746 }
Evan Cheng8b0b8742007-10-16 08:04:24 +00001747 for (unsigned i = 0, e = PhysCopies.size(); i != e; ++i) {
1748 CopyRec &TheCopy = PhysCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00001749 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001750 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00001751 if (Again)
1752 TryAgain.push_back(TheCopy);
Evan Cheng8b0b8742007-10-16 08:04:24 +00001753 }
1754 for (unsigned i = 0, e = VirtCopies.size(); i != e; ++i) {
1755 CopyRec &TheCopy = VirtCopies[i];
Evan Cheng0547bab2007-11-01 06:22:48 +00001756 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001757 if (!JoinCopy(TheCopy, Again))
Evan Cheng0547bab2007-11-01 06:22:48 +00001758 if (Again)
1759 TryAgain.push_back(TheCopy);
David Greene25133302007-06-08 17:18:56 +00001760 }
1761}
1762
1763void SimpleRegisterCoalescing::joinIntervals() {
1764 DOUT << "********** JOINING INTERVALS ***********\n";
1765
Evan Cheng8fc9a102007-11-06 08:52:21 +00001766 if (NewHeuristic)
1767 JoinQueue = new JoinPriorityQueue<CopyRecSort>(this);
1768
David Greene25133302007-06-08 17:18:56 +00001769 std::vector<CopyRec> TryAgainList;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001770 if (loopInfo->begin() == loopInfo->end()) {
David Greene25133302007-06-08 17:18:56 +00001771 // If there are no loops in the function, join intervals in function order.
1772 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1773 I != E; ++I)
Evan Cheng8b0b8742007-10-16 08:04:24 +00001774 CopyCoalesceInMBB(I, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00001775 } else {
1776 // Otherwise, join intervals in inner loops before other intervals.
1777 // Unfortunately we can't just iterate over loop hierarchy here because
1778 // there may be more MBB's than BB's. Collect MBB's for sorting.
1779
1780 // Join intervals in the function prolog first. We want to join physical
1781 // registers with virtual registers before the intervals got too long.
1782 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
Evan Cheng22f07ff2007-12-11 02:09:15 +00001783 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();I != E;++I){
1784 MachineBasicBlock *MBB = I;
1785 MBBs.push_back(std::make_pair(loopInfo->getLoopDepth(MBB), I));
1786 }
David Greene25133302007-06-08 17:18:56 +00001787
1788 // Sort by loop depth.
1789 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1790
1791 // Finally, join intervals in loop nest order.
1792 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Evan Cheng8b0b8742007-10-16 08:04:24 +00001793 CopyCoalesceInMBB(MBBs[i].second, TryAgainList);
David Greene25133302007-06-08 17:18:56 +00001794 }
1795
1796 // Joining intervals can allow other intervals to be joined. Iteratively join
1797 // until we make no progress.
Evan Cheng8fc9a102007-11-06 08:52:21 +00001798 if (NewHeuristic) {
1799 SmallVector<CopyRec, 16> TryAgain;
1800 bool ProgressMade = true;
1801 while (ProgressMade) {
1802 ProgressMade = false;
1803 while (!JoinQueue->empty()) {
1804 CopyRec R = JoinQueue->pop();
Evan Cheng0547bab2007-11-01 06:22:48 +00001805 bool Again = false;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001806 bool Success = JoinCopy(R, Again);
1807 if (Success)
Evan Cheng0547bab2007-11-01 06:22:48 +00001808 ProgressMade = true;
Evan Cheng8fc9a102007-11-06 08:52:21 +00001809 else if (Again)
1810 TryAgain.push_back(R);
1811 }
1812
1813 if (ProgressMade) {
1814 while (!TryAgain.empty()) {
1815 JoinQueue->push(TryAgain.back());
1816 TryAgain.pop_back();
1817 }
1818 }
1819 }
1820 } else {
1821 bool ProgressMade = true;
1822 while (ProgressMade) {
1823 ProgressMade = false;
1824
1825 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1826 CopyRec &TheCopy = TryAgainList[i];
1827 if (TheCopy.MI) {
1828 bool Again = false;
1829 bool Success = JoinCopy(TheCopy, Again);
1830 if (Success || !Again) {
1831 TheCopy.MI = 0; // Mark this one as done.
1832 ProgressMade = true;
1833 }
Evan Cheng0547bab2007-11-01 06:22:48 +00001834 }
David Greene25133302007-06-08 17:18:56 +00001835 }
1836 }
1837 }
1838
Evan Cheng8fc9a102007-11-06 08:52:21 +00001839 if (NewHeuristic)
Evan Chengc8d044e2008-02-15 18:24:29 +00001840 delete JoinQueue;
David Greene25133302007-06-08 17:18:56 +00001841}
1842
1843/// Return true if the two specified registers belong to different register
1844/// classes. The registers may be either phys or virt regs.
1845bool SimpleRegisterCoalescing::differingRegisterClasses(unsigned RegA,
Evan Cheng32dfbea2007-10-12 08:50:34 +00001846 unsigned RegB) const {
David Greene25133302007-06-08 17:18:56 +00001847
1848 // Get the register classes for the first reg.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001849 if (TargetRegisterInfo::isPhysicalRegister(RegA)) {
1850 assert(TargetRegisterInfo::isVirtualRegister(RegB) &&
David Greene25133302007-06-08 17:18:56 +00001851 "Shouldn't consider two physregs!");
Evan Chengc8d044e2008-02-15 18:24:29 +00001852 return !mri_->getRegClass(RegB)->contains(RegA);
David Greene25133302007-06-08 17:18:56 +00001853 }
1854
1855 // Compare against the regclass for the second reg.
Evan Chengc8d044e2008-02-15 18:24:29 +00001856 const TargetRegisterClass *RegClass = mri_->getRegClass(RegA);
Dan Gohman6f0d0242008-02-10 18:45:23 +00001857 if (TargetRegisterInfo::isVirtualRegister(RegB))
Evan Chengc8d044e2008-02-15 18:24:29 +00001858 return RegClass != mri_->getRegClass(RegB);
David Greene25133302007-06-08 17:18:56 +00001859 else
1860 return !RegClass->contains(RegB);
1861}
1862
1863/// lastRegisterUse - Returns the last use of the specific register between
Evan Chengc8d044e2008-02-15 18:24:29 +00001864/// cycles Start and End or NULL if there are no uses.
1865MachineOperand *
Chris Lattner84bc5422007-12-31 04:13:23 +00001866SimpleRegisterCoalescing::lastRegisterUse(unsigned Start, unsigned End,
Evan Chengc8d044e2008-02-15 18:24:29 +00001867 unsigned Reg, unsigned &UseIdx) const{
1868 UseIdx = 0;
1869 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1870 MachineOperand *LastUse = NULL;
1871 for (MachineRegisterInfo::use_iterator I = mri_->use_begin(Reg),
1872 E = mri_->use_end(); I != E; ++I) {
1873 MachineOperand &Use = I.getOperand();
1874 MachineInstr *UseMI = Use.getParent();
Evan Chenga2fb6342008-03-25 02:02:19 +00001875 unsigned SrcReg, DstReg;
1876 if (tii_->isMoveInstr(*UseMI, SrcReg, DstReg) && SrcReg == DstReg)
1877 // Ignore identity copies.
1878 continue;
Evan Chengc8d044e2008-02-15 18:24:29 +00001879 unsigned Idx = li_->getInstructionIndex(UseMI);
1880 if (Idx >= Start && Idx < End && Idx >= UseIdx) {
1881 LastUse = &Use;
1882 UseIdx = Idx;
1883 }
1884 }
1885 return LastUse;
1886 }
1887
David Greene25133302007-06-08 17:18:56 +00001888 int e = (End-1) / InstrSlots::NUM * InstrSlots::NUM;
1889 int s = Start;
1890 while (e >= s) {
1891 // Skip deleted instructions
1892 MachineInstr *MI = li_->getInstructionFromIndex(e);
1893 while ((e - InstrSlots::NUM) >= s && !MI) {
1894 e -= InstrSlots::NUM;
1895 MI = li_->getInstructionFromIndex(e);
1896 }
1897 if (e < s || MI == NULL)
1898 return NULL;
1899
Evan Chenga2fb6342008-03-25 02:02:19 +00001900 // Ignore identity copies.
1901 unsigned SrcReg, DstReg;
1902 if (!(tii_->isMoveInstr(*MI, SrcReg, DstReg) && SrcReg == DstReg))
1903 for (unsigned i = 0, NumOps = MI->getNumOperands(); i != NumOps; ++i) {
1904 MachineOperand &Use = MI->getOperand(i);
1905 if (Use.isRegister() && Use.isUse() && Use.getReg() &&
1906 tri_->regsOverlap(Use.getReg(), Reg)) {
1907 UseIdx = e;
1908 return &Use;
1909 }
David Greene25133302007-06-08 17:18:56 +00001910 }
David Greene25133302007-06-08 17:18:56 +00001911
1912 e -= InstrSlots::NUM;
1913 }
1914
1915 return NULL;
1916}
1917
1918
David Greene25133302007-06-08 17:18:56 +00001919void SimpleRegisterCoalescing::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +00001920 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +00001921 cerr << tri_->getName(reg);
David Greene25133302007-06-08 17:18:56 +00001922 else
1923 cerr << "%reg" << reg;
1924}
1925
1926void SimpleRegisterCoalescing::releaseMemory() {
Evan Cheng8fc9a102007-11-06 08:52:21 +00001927 JoinedCopies.clear();
David Greene25133302007-06-08 17:18:56 +00001928}
1929
1930static bool isZeroLengthInterval(LiveInterval *li) {
1931 for (LiveInterval::Ranges::const_iterator
1932 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
1933 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
1934 return false;
1935 return true;
1936}
1937
Evan Chengdb9b1c32008-04-03 16:41:54 +00001938/// TurnCopyIntoImpDef - If source of the specified copy is an implicit def,
1939/// turn the copy into an implicit def.
1940bool
1941SimpleRegisterCoalescing::TurnCopyIntoImpDef(MachineBasicBlock::iterator &I,
1942 MachineBasicBlock *MBB,
1943 unsigned DstReg, unsigned SrcReg) {
1944 MachineInstr *CopyMI = &*I;
1945 unsigned CopyIdx = li_->getDefIndex(li_->getInstructionIndex(CopyMI));
1946 if (!li_->hasInterval(SrcReg))
1947 return false;
1948 LiveInterval &SrcInt = li_->getInterval(SrcReg);
1949 if (!SrcInt.empty())
1950 return false;
Evan Chengf20d9432008-04-09 01:30:15 +00001951 if (!li_->hasInterval(DstReg))
1952 return false;
Evan Chengdb9b1c32008-04-03 16:41:54 +00001953 LiveInterval &DstInt = li_->getInterval(DstReg);
Evan Chengff7a3e52008-04-16 18:48:43 +00001954 const LiveRange *DstLR = DstInt.getLiveRangeContaining(CopyIdx);
Evan Chengdb9b1c32008-04-03 16:41:54 +00001955 DstInt.removeValNo(DstLR->valno);
1956 CopyMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
1957 for (int i = CopyMI->getNumOperands() - 1, e = 0; i > e; --i)
1958 CopyMI->RemoveOperand(i);
1959 bool NoUse = mri_->use_begin(SrcReg) == mri_->use_end();
1960 if (NoUse) {
1961 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(SrcReg),
1962 E = mri_->reg_end(); I != E; ) {
1963 assert(I.getOperand().isDef());
1964 MachineInstr *DefMI = &*I;
1965 ++I;
1966 // The implicit_def source has no other uses, delete it.
1967 assert(DefMI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF);
1968 li_->RemoveMachineInstrFromMaps(DefMI);
1969 DefMI->eraseFromParent();
Evan Chengdb9b1c32008-04-03 16:41:54 +00001970 }
1971 }
1972 ++I;
1973 return true;
1974}
1975
1976
David Greene25133302007-06-08 17:18:56 +00001977bool SimpleRegisterCoalescing::runOnMachineFunction(MachineFunction &fn) {
1978 mf_ = &fn;
Evan Cheng70071432008-02-13 03:01:43 +00001979 mri_ = &fn.getRegInfo();
David Greene25133302007-06-08 17:18:56 +00001980 tm_ = &fn.getTarget();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001981 tri_ = tm_->getRegisterInfo();
David Greene25133302007-06-08 17:18:56 +00001982 tii_ = tm_->getInstrInfo();
1983 li_ = &getAnalysis<LiveIntervals>();
1984 lv_ = &getAnalysis<LiveVariables>();
Evan Cheng22f07ff2007-12-11 02:09:15 +00001985 loopInfo = &getAnalysis<MachineLoopInfo>();
David Greene25133302007-06-08 17:18:56 +00001986
1987 DOUT << "********** SIMPLE REGISTER COALESCING **********\n"
1988 << "********** Function: "
1989 << ((Value*)mf_->getFunction())->getName() << '\n';
1990
Dan Gohman6f0d0242008-02-10 18:45:23 +00001991 allocatableRegs_ = tri_->getAllocatableSet(fn);
1992 for (TargetRegisterInfo::regclass_iterator I = tri_->regclass_begin(),
1993 E = tri_->regclass_end(); I != E; ++I)
Bill Wendling2674d712008-01-04 08:59:18 +00001994 allocatableRCRegs_.insert(std::make_pair(*I,
Dan Gohman6f0d0242008-02-10 18:45:23 +00001995 tri_->getAllocatableSet(fn, *I)));
David Greene25133302007-06-08 17:18:56 +00001996
Gabor Greife510b3a2007-07-09 12:00:59 +00001997 // Join (coalesce) intervals if requested.
David Greene25133302007-06-08 17:18:56 +00001998 if (EnableJoining) {
1999 joinIntervals();
2000 DOUT << "********** INTERVALS POST JOINING **********\n";
Bill Wendling2674d712008-01-04 08:59:18 +00002001 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I){
Dan Gohman6f0d0242008-02-10 18:45:23 +00002002 I->second.print(DOUT, tri_);
David Greene25133302007-06-08 17:18:56 +00002003 DOUT << "\n";
2004 }
Evan Cheng32dfbea2007-10-12 08:50:34 +00002005
Evan Cheng8fc9a102007-11-06 08:52:21 +00002006 // Delete all coalesced copies.
2007 for (SmallPtrSet<MachineInstr*,32>::iterator I = JoinedCopies.begin(),
2008 E = JoinedCopies.end(); I != E; ++I) {
Evan Cheng3c88d742008-03-18 08:26:47 +00002009 MachineInstr *CopyMI = *I;
2010 unsigned SrcReg, DstReg;
Evan Chengff7a3e52008-04-16 18:48:43 +00002011 if (!tii_->isMoveInstr(*CopyMI, SrcReg, DstReg)) {
2012 assert((CopyMI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
2013 CopyMI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) &&
2014 "Unrecognized copy instruction");
2015 DstReg = CopyMI->getOperand(0).getReg();
2016 }
Evan Cheng3c88d742008-03-18 08:26:47 +00002017 if (CopyMI->registerDefIsDead(DstReg)) {
2018 LiveInterval &li = li_->getInterval(DstReg);
Evan Cheng9c1e06e2008-04-16 20:24:25 +00002019 if (!ShortenDeadCopySrcLiveRange(li, CopyMI))
2020 ShortenDeadCopyLiveRange(li, CopyMI);
Evan Cheng3c88d742008-03-18 08:26:47 +00002021 }
Evan Cheng8fc9a102007-11-06 08:52:21 +00002022 li_->RemoveMachineInstrFromMaps(*I);
2023 (*I)->eraseFromParent();
Evan Cheng70071432008-02-13 03:01:43 +00002024 ++numPeep;
Evan Cheng8fc9a102007-11-06 08:52:21 +00002025 }
David Greene25133302007-06-08 17:18:56 +00002026 }
2027
Evan Chengc8d044e2008-02-15 18:24:29 +00002028 // Perform a final pass over the instructions and compute spill weights
2029 // and remove identity moves.
David Greene25133302007-06-08 17:18:56 +00002030 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
2031 mbbi != mbbe; ++mbbi) {
2032 MachineBasicBlock* mbb = mbbi;
Evan Cheng22f07ff2007-12-11 02:09:15 +00002033 unsigned loopDepth = loopInfo->getLoopDepth(mbb);
David Greene25133302007-06-08 17:18:56 +00002034
2035 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
2036 mii != mie; ) {
2037 // if the move will be an identity move delete it
Evan Chengc8d044e2008-02-15 18:24:29 +00002038 unsigned srcReg, dstReg;
Evan Chengdb9b1c32008-04-03 16:41:54 +00002039 bool isMove = tii_->isMoveInstr(*mii, srcReg, dstReg);
2040 if (isMove && srcReg == dstReg) {
Evan Cheng3c88d742008-03-18 08:26:47 +00002041 if (li_->hasInterval(srcReg)) {
2042 LiveInterval &RegInt = li_->getInterval(srcReg);
2043 // If def of this move instruction is dead, remove its live range
2044 // from the dstination register's live interval.
2045 if (mii->registerDefIsDead(dstReg)) {
Evan Cheng9c1e06e2008-04-16 20:24:25 +00002046 if (!ShortenDeadCopySrcLiveRange(RegInt, mii))
2047 ShortenDeadCopyLiveRange(RegInt, mii);
Evan Cheng3c88d742008-03-18 08:26:47 +00002048 }
2049 }
David Greene25133302007-06-08 17:18:56 +00002050 li_->RemoveMachineInstrFromMaps(mii);
2051 mii = mbbi->erase(mii);
2052 ++numPeep;
Evan Chengdb9b1c32008-04-03 16:41:54 +00002053 } else if (!isMove || !TurnCopyIntoImpDef(mii, mbb, dstReg, srcReg)) {
David Greene25133302007-06-08 17:18:56 +00002054 SmallSet<unsigned, 4> UniqueUses;
2055 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
2056 const MachineOperand &mop = mii->getOperand(i);
2057 if (mop.isRegister() && mop.getReg() &&
Dan Gohman6f0d0242008-02-10 18:45:23 +00002058 TargetRegisterInfo::isVirtualRegister(mop.getReg())) {
Evan Chengc8d044e2008-02-15 18:24:29 +00002059 unsigned reg = mop.getReg();
David Greene25133302007-06-08 17:18:56 +00002060 // Multiple uses of reg by the same instruction. It should not
2061 // contribute to spill weight again.
2062 if (UniqueUses.count(reg) != 0)
2063 continue;
2064 LiveInterval &RegInt = li_->getInterval(reg);
Evan Cheng81a03822007-11-17 00:40:40 +00002065 RegInt.weight +=
2066 li_->getSpillWeight(mop.isDef(), mop.isUse(), loopDepth);
David Greene25133302007-06-08 17:18:56 +00002067 UniqueUses.insert(reg);
2068 }
2069 }
2070 ++mii;
2071 }
2072 }
2073 }
2074
2075 for (LiveIntervals::iterator I = li_->begin(), E = li_->end(); I != E; ++I) {
2076 LiveInterval &LI = I->second;
Dan Gohman6f0d0242008-02-10 18:45:23 +00002077 if (TargetRegisterInfo::isVirtualRegister(LI.reg)) {
David Greene25133302007-06-08 17:18:56 +00002078 // If the live interval length is essentially zero, i.e. in every live
2079 // range the use follows def immediately, it doesn't make sense to spill
2080 // it and hope it will be easier to allocate for this li.
2081 if (isZeroLengthInterval(&LI))
2082 LI.weight = HUGE_VALF;
Evan Cheng5ef3a042007-12-06 00:01:56 +00002083 else {
2084 bool isLoad = false;
Evan Cheng63a18c42008-02-09 08:36:28 +00002085 if (li_->isReMaterializable(LI, isLoad)) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00002086 // If all of the definitions of the interval are re-materializable,
2087 // it is a preferred candidate for spilling. If non of the defs are
2088 // loads, then it's potentially very cheap to re-materialize.
2089 // FIXME: this gets much more complicated once we support non-trivial
2090 // re-materialization.
2091 if (isLoad)
2092 LI.weight *= 0.9F;
2093 else
2094 LI.weight *= 0.5F;
2095 }
2096 }
David Greene25133302007-06-08 17:18:56 +00002097
2098 // Slightly prefer live interval that has been assigned a preferred reg.
2099 if (LI.preference)
2100 LI.weight *= 1.01F;
2101
2102 // Divide the weight of the interval by its size. This encourages
2103 // spilling of intervals that are large and have few uses, and
2104 // discourages spilling of small intervals with many uses.
2105 LI.weight /= LI.getSize();
2106 }
2107 }
2108
2109 DEBUG(dump());
2110 return true;
2111}
2112
2113/// print - Implement the dump method.
2114void SimpleRegisterCoalescing::print(std::ostream &O, const Module* m) const {
2115 li_->print(O, m);
2116}
David Greene2c17c4d2007-09-06 16:18:45 +00002117
2118RegisterCoalescer* llvm::createSimpleRegisterCoalescer() {
2119 return new SimpleRegisterCoalescing();
2120}
2121
2122// Make sure that anything that uses RegisterCoalescer pulls in this file...
2123DEFINING_FILE_FOR(SimpleRegisterCoalescing)