1 //===-- LiveRangeEdit.cpp - Basic tools for editing a register live range -===//
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 // The LiveRangeEdit class represents changes done to a virtual register when it
11 // is spilled or split.
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "regalloc"
15 #include "VirtRegMap.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/CodeGen/CalcSpillWeights.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/LiveRangeEdit.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25
26 using namespace llvm;
27
28 STATISTIC(NumDCEDeleted, "Number of instructions deleted by DCE");
29 STATISTIC(NumDCEFoldedLoads, "Number of single use loads folded after DCE");
30 STATISTIC(NumFracRanges, "Number of live ranges fractured by DCE");
31
anchor()32 void LiveRangeEdit::Delegate::anchor() { }
33
createFrom(unsigned OldReg)34 LiveInterval &LiveRangeEdit::createFrom(unsigned OldReg) {
35 unsigned VReg = MRI.createVirtualRegister(MRI.getRegClass(OldReg));
36 if (VRM) {
37 VRM->grow();
38 VRM->setIsSplitFromReg(VReg, VRM->getOriginal(OldReg));
39 }
40 LiveInterval &LI = LIS.getOrCreateInterval(VReg);
41 NewRegs.push_back(&LI);
42 return LI;
43 }
44
checkRematerializable(VNInfo * VNI,const MachineInstr * DefMI,AliasAnalysis * aa)45 bool LiveRangeEdit::checkRematerializable(VNInfo *VNI,
46 const MachineInstr *DefMI,
47 AliasAnalysis *aa) {
48 assert(DefMI && "Missing instruction");
49 ScannedRemattable = true;
50 if (!TII.isTriviallyReMaterializable(DefMI, aa))
51 return false;
52 Remattable.insert(VNI);
53 return true;
54 }
55
scanRemattable(AliasAnalysis * aa)56 void LiveRangeEdit::scanRemattable(AliasAnalysis *aa) {
57 for (LiveInterval::vni_iterator I = getParent().vni_begin(),
58 E = getParent().vni_end(); I != E; ++I) {
59 VNInfo *VNI = *I;
60 if (VNI->isUnused())
61 continue;
62 MachineInstr *DefMI = LIS.getInstructionFromIndex(VNI->def);
63 if (!DefMI)
64 continue;
65 checkRematerializable(VNI, DefMI, aa);
66 }
67 ScannedRemattable = true;
68 }
69
anyRematerializable(AliasAnalysis * aa)70 bool LiveRangeEdit::anyRematerializable(AliasAnalysis *aa) {
71 if (!ScannedRemattable)
72 scanRemattable(aa);
73 return !Remattable.empty();
74 }
75
76 /// allUsesAvailableAt - Return true if all registers used by OrigMI at
77 /// OrigIdx are also available with the same value at UseIdx.
allUsesAvailableAt(const MachineInstr * OrigMI,SlotIndex OrigIdx,SlotIndex UseIdx)78 bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
79 SlotIndex OrigIdx,
80 SlotIndex UseIdx) {
81 OrigIdx = OrigIdx.getRegSlot(true);
82 UseIdx = UseIdx.getRegSlot(true);
83 for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
84 const MachineOperand &MO = OrigMI->getOperand(i);
85 if (!MO.isReg() || !MO.getReg() || !MO.readsReg())
86 continue;
87
88 // We can't remat physreg uses, unless it is a constant.
89 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
90 if (MRI.isConstantPhysReg(MO.getReg(), VRM->getMachineFunction()))
91 continue;
92 return false;
93 }
94
95 LiveInterval &li = LIS.getInterval(MO.getReg());
96 const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
97 if (!OVNI)
98 continue;
99 if (OVNI != li.getVNInfoAt(UseIdx))
100 return false;
101 }
102 return true;
103 }
104
canRematerializeAt(Remat & RM,SlotIndex UseIdx,bool cheapAsAMove)105 bool LiveRangeEdit::canRematerializeAt(Remat &RM,
106 SlotIndex UseIdx,
107 bool cheapAsAMove) {
108 assert(ScannedRemattable && "Call anyRematerializable first");
109
110 // Use scanRemattable info.
111 if (!Remattable.count(RM.ParentVNI))
112 return false;
113
114 // No defining instruction provided.
115 SlotIndex DefIdx;
116 if (RM.OrigMI)
117 DefIdx = LIS.getInstructionIndex(RM.OrigMI);
118 else {
119 DefIdx = RM.ParentVNI->def;
120 RM.OrigMI = LIS.getInstructionFromIndex(DefIdx);
121 assert(RM.OrigMI && "No defining instruction for remattable value");
122 }
123
124 // If only cheap remats were requested, bail out early.
125 if (cheapAsAMove && !RM.OrigMI->isAsCheapAsAMove())
126 return false;
127
128 // Verify that all used registers are available with the same values.
129 if (!allUsesAvailableAt(RM.OrigMI, DefIdx, UseIdx))
130 return false;
131
132 return true;
133 }
134
rematerializeAt(MachineBasicBlock & MBB,MachineBasicBlock::iterator MI,unsigned DestReg,const Remat & RM,const TargetRegisterInfo & tri,bool Late)135 SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
136 MachineBasicBlock::iterator MI,
137 unsigned DestReg,
138 const Remat &RM,
139 const TargetRegisterInfo &tri,
140 bool Late) {
141 assert(RM.OrigMI && "Invalid remat");
142 TII.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
143 Rematted.insert(RM.ParentVNI);
144 return LIS.getSlotIndexes()->insertMachineInstrInMaps(--MI, Late)
145 .getRegSlot();
146 }
147
eraseVirtReg(unsigned Reg)148 void LiveRangeEdit::eraseVirtReg(unsigned Reg) {
149 if (TheDelegate && TheDelegate->LRE_CanEraseVirtReg(Reg))
150 LIS.removeInterval(Reg);
151 }
152
foldAsLoad(LiveInterval * LI,SmallVectorImpl<MachineInstr * > & Dead)153 bool LiveRangeEdit::foldAsLoad(LiveInterval *LI,
154 SmallVectorImpl<MachineInstr*> &Dead) {
155 MachineInstr *DefMI = 0, *UseMI = 0;
156
157 // Check that there is a single def and a single use.
158 for (MachineRegisterInfo::reg_nodbg_iterator I = MRI.reg_nodbg_begin(LI->reg),
159 E = MRI.reg_nodbg_end(); I != E; ++I) {
160 MachineOperand &MO = I.getOperand();
161 MachineInstr *MI = MO.getParent();
162 if (MO.isDef()) {
163 if (DefMI && DefMI != MI)
164 return false;
165 if (!MI->canFoldAsLoad())
166 return false;
167 DefMI = MI;
168 } else if (!MO.isUndef()) {
169 if (UseMI && UseMI != MI)
170 return false;
171 // FIXME: Targets don't know how to fold subreg uses.
172 if (MO.getSubReg())
173 return false;
174 UseMI = MI;
175 }
176 }
177 if (!DefMI || !UseMI)
178 return false;
179
180 // Since we're moving the DefMI load, make sure we're not extending any live
181 // ranges.
182 if (!allUsesAvailableAt(DefMI,
183 LIS.getInstructionIndex(DefMI),
184 LIS.getInstructionIndex(UseMI)))
185 return false;
186
187 // We also need to make sure it is safe to move the load.
188 // Assume there are stores between DefMI and UseMI.
189 bool SawStore = true;
190 if (!DefMI->isSafeToMove(&TII, 0, SawStore))
191 return false;
192
193 DEBUG(dbgs() << "Try to fold single def: " << *DefMI
194 << " into single use: " << *UseMI);
195
196 SmallVector<unsigned, 8> Ops;
197 if (UseMI->readsWritesVirtualRegister(LI->reg, &Ops).second)
198 return false;
199
200 MachineInstr *FoldMI = TII.foldMemoryOperand(UseMI, Ops, DefMI);
201 if (!FoldMI)
202 return false;
203 DEBUG(dbgs() << " folded: " << *FoldMI);
204 LIS.ReplaceMachineInstrInMaps(UseMI, FoldMI);
205 UseMI->eraseFromParent();
206 DefMI->addRegisterDead(LI->reg, 0);
207 Dead.push_back(DefMI);
208 ++NumDCEFoldedLoads;
209 return true;
210 }
211
eliminateDeadDefs(SmallVectorImpl<MachineInstr * > & Dead,ArrayRef<unsigned> RegsBeingSpilled)212 void LiveRangeEdit::eliminateDeadDefs(SmallVectorImpl<MachineInstr*> &Dead,
213 ArrayRef<unsigned> RegsBeingSpilled) {
214 SetVector<LiveInterval*,
215 SmallVector<LiveInterval*, 8>,
216 SmallPtrSet<LiveInterval*, 8> > ToShrink;
217
218 for (;;) {
219 // Erase all dead defs.
220 while (!Dead.empty()) {
221 MachineInstr *MI = Dead.pop_back_val();
222 assert(MI->allDefsAreDead() && "Def isn't really dead");
223 SlotIndex Idx = LIS.getInstructionIndex(MI).getRegSlot();
224
225 // Never delete inline asm.
226 if (MI->isInlineAsm()) {
227 DEBUG(dbgs() << "Won't delete: " << Idx << '\t' << *MI);
228 continue;
229 }
230
231 // Use the same criteria as DeadMachineInstructionElim.
232 bool SawStore = false;
233 if (!MI->isSafeToMove(&TII, 0, SawStore)) {
234 DEBUG(dbgs() << "Can't delete: " << Idx << '\t' << *MI);
235 continue;
236 }
237
238 DEBUG(dbgs() << "Deleting dead def " << Idx << '\t' << *MI);
239
240 // Collect virtual registers to be erased after MI is gone.
241 SmallVector<unsigned, 8> RegsToErase;
242 bool ReadsPhysRegs = false;
243
244 // Check for live intervals that may shrink
245 for (MachineInstr::mop_iterator MOI = MI->operands_begin(),
246 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
247 if (!MOI->isReg())
248 continue;
249 unsigned Reg = MOI->getReg();
250 if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
251 // Check if MI reads any unreserved physregs.
252 if (Reg && MOI->readsReg() && !LIS.isReserved(Reg))
253 ReadsPhysRegs = true;
254 continue;
255 }
256 LiveInterval &LI = LIS.getInterval(Reg);
257
258 // Shrink read registers, unless it is likely to be expensive and
259 // unlikely to change anything. We typically don't want to shrink the
260 // PIC base register that has lots of uses everywhere.
261 // Always shrink COPY uses that probably come from live range splitting.
262 if (MI->readsVirtualRegister(Reg) &&
263 (MI->isCopy() || MOI->isDef() || MRI.hasOneNonDBGUse(Reg) ||
264 LI.killedAt(Idx)))
265 ToShrink.insert(&LI);
266
267 // Remove defined value.
268 if (MOI->isDef()) {
269 if (VNInfo *VNI = LI.getVNInfoAt(Idx)) {
270 if (TheDelegate)
271 TheDelegate->LRE_WillShrinkVirtReg(LI.reg);
272 LI.removeValNo(VNI);
273 if (LI.empty())
274 RegsToErase.push_back(Reg);
275 }
276 }
277 }
278
279 // Currently, we don't support DCE of physreg live ranges. If MI reads
280 // any unreserved physregs, don't erase the instruction, but turn it into
281 // a KILL instead. This way, the physreg live ranges don't end up
282 // dangling.
283 // FIXME: It would be better to have something like shrinkToUses() for
284 // physregs. That could potentially enable more DCE and it would free up
285 // the physreg. It would not happen often, though.
286 if (ReadsPhysRegs) {
287 MI->setDesc(TII.get(TargetOpcode::KILL));
288 // Remove all operands that aren't physregs.
289 for (unsigned i = MI->getNumOperands(); i; --i) {
290 const MachineOperand &MO = MI->getOperand(i-1);
291 if (MO.isReg() && TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
292 continue;
293 MI->RemoveOperand(i-1);
294 }
295 DEBUG(dbgs() << "Converted physregs to:\t" << *MI);
296 } else {
297 if (TheDelegate)
298 TheDelegate->LRE_WillEraseInstruction(MI);
299 LIS.RemoveMachineInstrFromMaps(MI);
300 MI->eraseFromParent();
301 ++NumDCEDeleted;
302 }
303
304 // Erase any virtregs that are now empty and unused. There may be <undef>
305 // uses around. Keep the empty live range in that case.
306 for (unsigned i = 0, e = RegsToErase.size(); i != e; ++i) {
307 unsigned Reg = RegsToErase[i];
308 if (LIS.hasInterval(Reg) && MRI.reg_nodbg_empty(Reg)) {
309 ToShrink.remove(&LIS.getInterval(Reg));
310 eraseVirtReg(Reg);
311 }
312 }
313 }
314
315 if (ToShrink.empty())
316 break;
317
318 // Shrink just one live interval. Then delete new dead defs.
319 LiveInterval *LI = ToShrink.back();
320 ToShrink.pop_back();
321 if (foldAsLoad(LI, Dead))
322 continue;
323 if (TheDelegate)
324 TheDelegate->LRE_WillShrinkVirtReg(LI->reg);
325 if (!LIS.shrinkToUses(LI, &Dead))
326 continue;
327
328 // Don't create new intervals for a register being spilled.
329 // The new intervals would have to be spilled anyway so its not worth it.
330 // Also they currently aren't spilled so creating them and not spilling
331 // them results in incorrect code.
332 bool BeingSpilled = false;
333 for (unsigned i = 0, e = RegsBeingSpilled.size(); i != e; ++i) {
334 if (LI->reg == RegsBeingSpilled[i]) {
335 BeingSpilled = true;
336 break;
337 }
338 }
339
340 if (BeingSpilled) continue;
341
342 // LI may have been separated, create new intervals.
343 LI->RenumberValues(LIS);
344 ConnectedVNInfoEqClasses ConEQ(LIS);
345 unsigned NumComp = ConEQ.Classify(LI);
346 if (NumComp <= 1)
347 continue;
348 ++NumFracRanges;
349 bool IsOriginal = VRM && VRM->getOriginal(LI->reg) == LI->reg;
350 DEBUG(dbgs() << NumComp << " components: " << *LI << '\n');
351 SmallVector<LiveInterval*, 8> Dups(1, LI);
352 for (unsigned i = 1; i != NumComp; ++i) {
353 Dups.push_back(&createFrom(LI->reg));
354 // If LI is an original interval that hasn't been split yet, make the new
355 // intervals their own originals instead of referring to LI. The original
356 // interval must contain all the split products, and LI doesn't.
357 if (IsOriginal)
358 VRM->setIsSplitFromReg(Dups.back()->reg, 0);
359 if (TheDelegate)
360 TheDelegate->LRE_DidCloneVirtReg(Dups.back()->reg, LI->reg);
361 }
362 ConEQ.Distribute(&Dups[0], MRI);
363 DEBUG({
364 for (unsigned i = 0; i != NumComp; ++i)
365 dbgs() << '\t' << *Dups[i] << '\n';
366 });
367 }
368 }
369
calculateRegClassAndHint(MachineFunction & MF,const MachineLoopInfo & Loops)370 void LiveRangeEdit::calculateRegClassAndHint(MachineFunction &MF,
371 const MachineLoopInfo &Loops) {
372 VirtRegAuxInfo VRAI(MF, LIS, Loops);
373 for (iterator I = begin(), E = end(); I != E; ++I) {
374 LiveInterval &LI = **I;
375 if (MRI.recomputeRegClass(LI.reg, MF.getTarget()))
376 DEBUG(dbgs() << "Inflated " << PrintReg(LI.reg) << " to "
377 << MRI.getRegClass(LI.reg)->getName() << '\n');
378 VRAI.CalculateWeightAndHint(LI);
379 }
380 }
381