Split out the Dwarf writer stuff into separate files. This is a much more
[llvm/msp430.git] / lib / CodeGen / RegisterScavenging.cpp
blob944468ea11b837e85f1285c1385fc9ca85a855be
1 //===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the machine register scavenger. It can provide
11 // information, such as unused registers, at any point in a machine basic block.
12 // It also provides a mechanism to make registers available by evicting them to
13 // spill slots.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "reg-scavenging"
18 #include "llvm/CodeGen/RegisterScavenging.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Target/TargetRegisterInfo.h"
24 #include "llvm/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/STLExtras.h"
29 using namespace llvm;
31 /// RedefinesSuperRegPart - Return true if the specified register is redefining
32 /// part of a super-register.
33 static bool RedefinesSuperRegPart(const MachineInstr *MI, unsigned SubReg,
34 const TargetRegisterInfo *TRI) {
35 bool SeenSuperUse = false;
36 bool SeenSuperDef = false;
37 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
38 const MachineOperand &MO = MI->getOperand(i);
39 if (!MO.isReg())
40 continue;
41 if (TRI->isSuperRegister(SubReg, MO.getReg())) {
42 if (MO.isUse())
43 SeenSuperUse = true;
44 else if (MO.isImplicit())
45 SeenSuperDef = true;
49 return SeenSuperDef && SeenSuperUse;
52 static bool RedefinesSuperRegPart(const MachineInstr *MI,
53 const MachineOperand &MO,
54 const TargetRegisterInfo *TRI) {
55 assert(MO.isReg() && MO.isDef() && "Not a register def!");
56 return RedefinesSuperRegPart(MI, MO.getReg(), TRI);
59 /// setUsed - Set the register and its sub-registers as being used.
60 void RegScavenger::setUsed(unsigned Reg, bool ImpDef) {
61 RegsAvailable.reset(Reg);
62 ImplicitDefed[Reg] = ImpDef;
64 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
65 unsigned SubReg = *SubRegs; ++SubRegs) {
66 RegsAvailable.reset(SubReg);
67 ImplicitDefed[SubReg] = ImpDef;
71 /// setUnused - Set the register and its sub-registers as being unused.
72 void RegScavenger::setUnused(unsigned Reg, const MachineInstr *MI) {
73 RegsAvailable.set(Reg);
74 ImplicitDefed.reset(Reg);
76 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
77 unsigned SubReg = *SubRegs; ++SubRegs)
78 if (!RedefinesSuperRegPart(MI, Reg, TRI)) {
79 RegsAvailable.set(SubReg);
80 ImplicitDefed.reset(SubReg);
84 void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
85 MachineFunction &MF = *mbb->getParent();
86 const TargetMachine &TM = MF.getTarget();
87 TII = TM.getInstrInfo();
88 TRI = TM.getRegisterInfo();
89 MRI = &MF.getRegInfo();
91 assert((NumPhysRegs == 0 || NumPhysRegs == TRI->getNumRegs()) &&
92 "Target changed?");
94 if (!MBB) {
95 NumPhysRegs = TRI->getNumRegs();
96 RegsAvailable.resize(NumPhysRegs);
97 ImplicitDefed.resize(NumPhysRegs);
99 // Create reserved registers bitvector.
100 ReservedRegs = TRI->getReservedRegs(MF);
102 // Create callee-saved registers bitvector.
103 CalleeSavedRegs.resize(NumPhysRegs);
104 const unsigned *CSRegs = TRI->getCalleeSavedRegs();
105 if (CSRegs != NULL)
106 for (unsigned i = 0; CSRegs[i]; ++i)
107 CalleeSavedRegs.set(CSRegs[i]);
110 MBB = mbb;
111 ScavengedReg = 0;
112 ScavengedRC = NULL;
113 ScavengeRestore = NULL;
114 CurrDist = 0;
115 DistanceMap.clear();
116 ImplicitDefed.reset();
118 // All registers started out unused.
119 RegsAvailable.set();
121 // Reserved registers are always used.
122 RegsAvailable ^= ReservedRegs;
124 // Live-in registers are in use.
125 if (!MBB->livein_empty())
126 for (MachineBasicBlock::const_livein_iterator I = MBB->livein_begin(),
127 E = MBB->livein_end(); I != E; ++I)
128 setUsed(*I);
130 Tracking = false;
133 void RegScavenger::restoreScavengedReg() {
134 TII->loadRegFromStackSlot(*MBB, MBBI, ScavengedReg,
135 ScavengingFrameIndex, ScavengedRC);
136 MachineBasicBlock::iterator II = prior(MBBI);
137 TRI->eliminateFrameIndex(II, 0, this);
138 setUsed(ScavengedReg);
139 ScavengedReg = 0;
140 ScavengedRC = NULL;
143 #ifndef NDEBUG
144 /// isLiveInButUnusedBefore - Return true if register is livein the MBB not
145 /// not used before it reaches the MI that defines register.
146 static bool isLiveInButUnusedBefore(unsigned Reg, MachineInstr *MI,
147 MachineBasicBlock *MBB,
148 const TargetRegisterInfo *TRI,
149 MachineRegisterInfo* MRI) {
150 // First check if register is livein.
151 bool isLiveIn = false;
152 for (MachineBasicBlock::const_livein_iterator I = MBB->livein_begin(),
153 E = MBB->livein_end(); I != E; ++I)
154 if (Reg == *I || TRI->isSuperRegister(Reg, *I)) {
155 isLiveIn = true;
156 break;
158 if (!isLiveIn)
159 return false;
161 // Is there any use of it before the specified MI?
162 SmallPtrSet<MachineInstr*, 4> UsesInMBB;
163 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
164 UE = MRI->use_end(); UI != UE; ++UI) {
165 MachineInstr *UseMI = &*UI;
166 if (UseMI->getParent() == MBB)
167 UsesInMBB.insert(UseMI);
169 if (UsesInMBB.empty())
170 return true;
172 for (MachineBasicBlock::iterator I = MBB->begin(), E = MI; I != E; ++I)
173 if (UsesInMBB.count(&*I))
174 return false;
175 return true;
177 #endif
179 void RegScavenger::forward() {
180 // Move ptr forward.
181 if (!Tracking) {
182 MBBI = MBB->begin();
183 Tracking = true;
184 } else {
185 assert(MBBI != MBB->end() && "Already at the end of the basic block!");
186 MBBI = next(MBBI);
189 MachineInstr *MI = MBBI;
190 DistanceMap.insert(std::make_pair(MI, CurrDist++));
192 if (MI == ScavengeRestore) {
193 ScavengedReg = 0;
194 ScavengedRC = NULL;
195 ScavengeRestore = NULL;
198 bool IsImpDef = MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF;
200 // Separate register operands into 3 classes: uses, defs, earlyclobbers.
201 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> UseMOs;
202 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> DefMOs;
203 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> EarlyClobberMOs;
204 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
205 const MachineOperand &MO = MI->getOperand(i);
206 if (!MO.isReg() || MO.getReg() == 0)
207 continue;
208 if (MO.isUse())
209 UseMOs.push_back(std::make_pair(&MO,i));
210 else if (MO.isEarlyClobber())
211 EarlyClobberMOs.push_back(std::make_pair(&MO,i));
212 else
213 DefMOs.push_back(std::make_pair(&MO,i));
216 // Process uses first.
217 BitVector UseRegs(NumPhysRegs);
218 for (unsigned i = 0, e = UseMOs.size(); i != e; ++i) {
219 const MachineOperand MO = *UseMOs[i].first;
220 unsigned Reg = MO.getReg();
222 assert(isUsed(Reg) && "Using an undefined register!");
224 if (MO.isKill() && !isReserved(Reg)) {
225 UseRegs.set(Reg);
227 // Mark sub-registers as used.
228 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
229 unsigned SubReg = *SubRegs; ++SubRegs)
230 UseRegs.set(SubReg);
234 // Change states of all registers after all the uses are processed to guard
235 // against multiple uses.
236 setUnused(UseRegs);
238 // Process early clobber defs then process defs. We can have a early clobber
239 // that is dead, it should not conflict with a def that happens one "slot"
240 // (see InstrSlots in LiveIntervalAnalysis.h) later.
241 unsigned NumECs = EarlyClobberMOs.size();
242 unsigned NumDefs = DefMOs.size();
244 for (unsigned i = 0, e = NumECs + NumDefs; i != e; ++i) {
245 const MachineOperand &MO = (i < NumECs)
246 ? *EarlyClobberMOs[i].first : *DefMOs[i-NumECs].first;
247 unsigned Idx = (i < NumECs)
248 ? EarlyClobberMOs[i].second : DefMOs[i-NumECs].second;
249 unsigned Reg = MO.getReg();
251 // If it's dead upon def, then it is now free.
252 if (MO.isDead()) {
253 setUnused(Reg, MI);
254 continue;
257 // Skip two-address destination operand.
258 if (MI->isRegTiedToUseOperand(Idx)) {
259 assert(isUsed(Reg) && "Using an undefined register!");
260 continue;
263 // Skip if this is merely redefining part of a super-register.
264 if (RedefinesSuperRegPart(MI, MO, TRI))
265 continue;
267 // Implicit def is allowed to "re-define" any register. Similarly,
268 // implicitly defined registers can be clobbered.
269 assert((isReserved(Reg) || isUnused(Reg) ||
270 IsImpDef || isImplicitlyDefined(Reg) ||
271 isLiveInButUnusedBefore(Reg, MI, MBB, TRI, MRI)) &&
272 "Re-defining a live register!");
273 setUsed(Reg, IsImpDef);
277 void RegScavenger::backward() {
278 assert(Tracking && "Not tracking states!");
279 assert(MBBI != MBB->begin() && "Already at start of basic block!");
280 // Move ptr backward.
281 MBBI = prior(MBBI);
283 MachineInstr *MI = MBBI;
284 DistanceMap.erase(MI);
285 --CurrDist;
287 // Separate register operands into 3 classes: uses, defs, earlyclobbers.
288 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> UseMOs;
289 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> DefMOs;
290 SmallVector<std::pair<const MachineOperand*,unsigned>, 4> EarlyClobberMOs;
291 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
292 const MachineOperand &MO = MI->getOperand(i);
293 if (!MO.isReg() || MO.getReg() == 0)
294 continue;
295 if (MO.isUse())
296 UseMOs.push_back(std::make_pair(&MO,i));
297 else if (MO.isEarlyClobber())
298 EarlyClobberMOs.push_back(std::make_pair(&MO,i));
299 else
300 DefMOs.push_back(std::make_pair(&MO,i));
304 // Process defs first.
305 unsigned NumECs = EarlyClobberMOs.size();
306 unsigned NumDefs = DefMOs.size();
307 for (unsigned i = 0, e = NumECs + NumDefs; i != e; ++i) {
308 const MachineOperand &MO = (i < NumDefs)
309 ? *DefMOs[i].first : *EarlyClobberMOs[i-NumDefs].first;
310 unsigned Idx = (i < NumECs)
311 ? DefMOs[i].second : EarlyClobberMOs[i-NumDefs].second;
313 // Skip two-address destination operand.
314 if (MI->isRegTiedToUseOperand(Idx))
315 continue;
317 unsigned Reg = MO.getReg();
318 assert(isUsed(Reg));
319 if (!isReserved(Reg))
320 setUnused(Reg, MI);
323 // Process uses.
324 BitVector UseRegs(NumPhysRegs);
325 for (unsigned i = 0, e = UseMOs.size(); i != e; ++i) {
326 const MachineOperand MO = *UseMOs[i].first;
327 unsigned Reg = MO.getReg();
328 assert(isUnused(Reg) || isReserved(Reg));
329 UseRegs.set(Reg);
331 // Set the sub-registers as "used".
332 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
333 unsigned SubReg = *SubRegs; ++SubRegs)
334 UseRegs.set(SubReg);
336 setUsed(UseRegs);
339 void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
340 if (includeReserved)
341 used = ~RegsAvailable;
342 else
343 used = ~RegsAvailable & ~ReservedRegs;
346 /// CreateRegClassMask - Set the bits that represent the registers in the
347 /// TargetRegisterClass.
348 static void CreateRegClassMask(const TargetRegisterClass *RC, BitVector &Mask) {
349 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E;
350 ++I)
351 Mask.set(*I);
354 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RegClass,
355 const BitVector &Candidates) const {
356 // Mask off the registers which are not in the TargetRegisterClass.
357 BitVector RegsAvailableCopy(NumPhysRegs, false);
358 CreateRegClassMask(RegClass, RegsAvailableCopy);
359 RegsAvailableCopy &= RegsAvailable;
361 // Restrict the search to candidates.
362 RegsAvailableCopy &= Candidates;
364 // Returns the first unused (bit is set) register, or 0 is none is found.
365 int Reg = RegsAvailableCopy.find_first();
366 return (Reg == -1) ? 0 : Reg;
369 unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RegClass,
370 bool ExCalleeSaved) const {
371 // Mask off the registers which are not in the TargetRegisterClass.
372 BitVector RegsAvailableCopy(NumPhysRegs, false);
373 CreateRegClassMask(RegClass, RegsAvailableCopy);
374 RegsAvailableCopy &= RegsAvailable;
376 // If looking for a non-callee-saved register, mask off all the callee-saved
377 // registers.
378 if (ExCalleeSaved)
379 RegsAvailableCopy &= ~CalleeSavedRegs;
381 // Returns the first unused (bit is set) register, or 0 is none is found.
382 int Reg = RegsAvailableCopy.find_first();
383 return (Reg == -1) ? 0 : Reg;
386 /// findFirstUse - Calculate the distance to the first use of the
387 /// specified register.
388 MachineInstr*
389 RegScavenger::findFirstUse(MachineBasicBlock *MBB,
390 MachineBasicBlock::iterator I, unsigned Reg,
391 unsigned &Dist) {
392 MachineInstr *UseMI = 0;
393 Dist = ~0U;
394 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
395 RE = MRI->reg_end(); RI != RE; ++RI) {
396 MachineInstr *UDMI = &*RI;
397 if (UDMI->getParent() != MBB)
398 continue;
399 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
400 if (DI == DistanceMap.end()) {
401 // If it's not in map, it's below current MI, let's initialize the
402 // map.
403 I = next(I);
404 unsigned Dist = CurrDist + 1;
405 while (I != MBB->end()) {
406 DistanceMap.insert(std::make_pair(I, Dist++));
407 I = next(I);
410 DI = DistanceMap.find(UDMI);
411 if (DI->second > CurrDist && DI->second < Dist) {
412 Dist = DI->second;
413 UseMI = UDMI;
416 return UseMI;
419 unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
420 MachineBasicBlock::iterator I,
421 int SPAdj) {
422 assert(ScavengingFrameIndex >= 0 &&
423 "Cannot scavenge a register without an emergency spill slot!");
425 // Mask off the registers which are not in the TargetRegisterClass.
426 BitVector Candidates(NumPhysRegs, false);
427 CreateRegClassMask(RC, Candidates);
428 Candidates ^= ReservedRegs; // Do not include reserved registers.
430 // Exclude all the registers being used by the instruction.
431 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
432 MachineOperand &MO = I->getOperand(i);
433 if (MO.isReg())
434 Candidates.reset(MO.getReg());
437 // Find the register whose use is furthest away.
438 unsigned SReg = 0;
439 unsigned MaxDist = 0;
440 MachineInstr *MaxUseMI = 0;
441 int Reg = Candidates.find_first();
442 while (Reg != -1) {
443 unsigned Dist;
444 MachineInstr *UseMI = findFirstUse(MBB, I, Reg, Dist);
445 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
446 unsigned AsDist;
447 MachineInstr *AsUseMI = findFirstUse(MBB, I, *AS, AsDist);
448 if (AsDist < Dist) {
449 Dist = AsDist;
450 UseMI = AsUseMI;
453 if (Dist >= MaxDist) {
454 MaxDist = Dist;
455 MaxUseMI = UseMI;
456 SReg = Reg;
458 Reg = Candidates.find_next(Reg);
461 if (ScavengedReg != 0) {
462 assert(0 && "Scavenger slot is live, unable to scavenge another register!");
463 abort();
466 // Spill the scavenged register before I.
467 TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC);
468 MachineBasicBlock::iterator II = prior(I);
469 TRI->eliminateFrameIndex(II, SPAdj, this);
471 // Restore the scavenged register before its use (or first terminator).
472 II = MaxUseMI
473 ? MachineBasicBlock::iterator(MaxUseMI) : MBB->getFirstTerminator();
474 TII->loadRegFromStackSlot(*MBB, II, SReg, ScavengingFrameIndex, RC);
475 ScavengeRestore = prior(II);
476 ScavengedReg = SReg;
477 ScavengedRC = RC;
479 return SReg;