blob: 69f640ea11fef70ee9dd4414ccda0cc14743cdc6 [file] [log] [blame]
Lang Hames87e3bca2009-05-06 02:36:21 +00001//===-- llvm/CodeGen/Rewriter.cpp - Rewriter -----------------------------===//
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#define DEBUG_TYPE "virtregrewriter"
11#include "VirtRegRewriter.h"
12#include "llvm/Support/Compiler.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000013#include "llvm/Support/ErrorHandling.h"
Lang Hames87e3bca2009-05-06 02:36:21 +000014#include "llvm/ADT/DepthFirstIterator.h"
15#include "llvm/ADT/Statistic.h"
16#include "llvm/ADT/STLExtras.h"
17#include <algorithm>
18using namespace llvm;
19
20STATISTIC(NumDSE , "Number of dead stores elided");
21STATISTIC(NumDSS , "Number of dead spill slots removed");
22STATISTIC(NumCommutes, "Number of instructions commuted");
23STATISTIC(NumDRM , "Number of re-materializable defs elided");
24STATISTIC(NumStores , "Number of stores added");
25STATISTIC(NumPSpills , "Number of physical register spills");
26STATISTIC(NumOmitted , "Number of reloads omited");
27STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
28STATISTIC(NumCopified, "Number of available reloads turned into copies");
29STATISTIC(NumReMats , "Number of re-materialization");
30STATISTIC(NumLoads , "Number of loads added");
31STATISTIC(NumReused , "Number of values reused");
32STATISTIC(NumDCE , "Number of copies elided");
33STATISTIC(NumSUnfold , "Number of stores unfolded");
34STATISTIC(NumModRefUnfold, "Number of modref unfolded");
35
36namespace {
Lang Hamesac276402009-06-04 18:45:36 +000037 enum RewriterName { local, trivial };
Lang Hames87e3bca2009-05-06 02:36:21 +000038}
39
40static cl::opt<RewriterName>
41RewriterOpt("rewriter",
42 cl::desc("Rewriter to use: (default: local)"),
43 cl::Prefix,
Lang Hamesac276402009-06-04 18:45:36 +000044 cl::values(clEnumVal(local, "local rewriter"),
Lang Hamesf41538d2009-06-02 16:53:25 +000045 clEnumVal(trivial, "trivial rewriter"),
Lang Hames87e3bca2009-05-06 02:36:21 +000046 clEnumValEnd),
47 cl::init(local));
48
49VirtRegRewriter::~VirtRegRewriter() {}
50
Lang Hames87e3bca2009-05-06 02:36:21 +000051
Lang Hames87e3bca2009-05-06 02:36:21 +000052
Lang Hamesf41538d2009-06-02 16:53:25 +000053/// This class is intended for use with the new spilling framework only. It
54/// rewrites vreg def/uses to use the assigned preg, but does not insert any
55/// spill code.
56struct VISIBILITY_HIDDEN TrivialRewriter : public VirtRegRewriter {
57
58 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
59 LiveIntervals* LIs) {
60 DOUT << "********** REWRITE MACHINE CODE **********\n";
61 DOUT << "********** Function: " << MF.getFunction()->getName() << '\n';
62 MachineRegisterInfo *mri = &MF.getRegInfo();
63
64 bool changed = false;
65
66 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
67 liItr != liEnd; ++liItr) {
68
69 if (TargetRegisterInfo::isVirtualRegister(liItr->first)) {
70 if (VRM.hasPhys(liItr->first)) {
71 unsigned preg = VRM.getPhys(liItr->first);
72 mri->replaceRegWith(liItr->first, preg);
73 mri->setPhysRegUsed(preg);
74 changed = true;
75 }
76 }
77 else {
78 if (!liItr->second->empty()) {
79 mri->setPhysRegUsed(liItr->first);
80 }
81 }
82 }
83
84 return changed;
85 }
86
87};
88
Lang Hames87e3bca2009-05-06 02:36:21 +000089// ************************************************************************ //
90
91/// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
92/// from top down, keep track of which spill slots or remat are available in
93/// each register.
94///
95/// Note that not all physregs are created equal here. In particular, some
96/// physregs are reloads that we are allowed to clobber or ignore at any time.
97/// Other physregs are values that the register allocated program is using
98/// that we cannot CHANGE, but we can read if we like. We keep track of this
99/// on a per-stack-slot / remat id basis as the low bit in the value of the
100/// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
101/// this bit and addAvailable sets it if.
102class VISIBILITY_HIDDEN AvailableSpills {
103 const TargetRegisterInfo *TRI;
104 const TargetInstrInfo *TII;
105
106 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
107 // or remat'ed virtual register values that are still available, due to
108 // being loaded or stored to, but not invalidated yet.
109 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
110
111 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
112 // indicating which stack slot values are currently held by a physreg. This
113 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
114 // physreg is modified.
115 std::multimap<unsigned, int> PhysRegsAvailable;
116
117 void disallowClobberPhysRegOnly(unsigned PhysReg);
118
119 void ClobberPhysRegOnly(unsigned PhysReg);
120public:
121 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
122 : TRI(tri), TII(tii) {
123 }
124
125 /// clear - Reset the state.
126 void clear() {
127 SpillSlotsOrReMatsAvailable.clear();
128 PhysRegsAvailable.clear();
129 }
130
131 const TargetRegisterInfo *getRegInfo() const { return TRI; }
132
133 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
134 /// available in a physical register, return that PhysReg, otherwise
135 /// return 0.
136 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
137 std::map<int, unsigned>::const_iterator I =
138 SpillSlotsOrReMatsAvailable.find(Slot);
139 if (I != SpillSlotsOrReMatsAvailable.end()) {
140 return I->second >> 1; // Remove the CanClobber bit.
141 }
142 return 0;
143 }
144
145 /// addAvailable - Mark that the specified stack slot / remat is available
146 /// in the specified physreg. If CanClobber is true, the physreg can be
147 /// modified at any time without changing the semantics of the program.
148 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
149 // If this stack slot is thought to be available in some other physreg,
150 // remove its record.
151 ModifyStackSlotOrReMat(SlotOrReMat);
152
153 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
154 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
155 (unsigned)CanClobber;
156
157 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
158 DOUT << "Remembering RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1;
159 else
160 DOUT << "Remembering SS#" << SlotOrReMat;
161 DOUT << " in physreg " << TRI->getName(Reg) << "\n";
162 }
163
164 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
165 /// the value of the specified stackslot register if it desires. The
166 /// specified stack slot must be available in a physreg for this query to
167 /// make sense.
168 bool canClobberPhysRegForSS(int SlotOrReMat) const {
169 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
170 "Value not available!");
171 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
172 }
173
174 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
175 /// physical register where values for some stack slot(s) might be
176 /// available.
177 bool canClobberPhysReg(unsigned PhysReg) const {
178 std::multimap<unsigned, int>::const_iterator I =
179 PhysRegsAvailable.lower_bound(PhysReg);
180 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
181 int SlotOrReMat = I->second;
182 I++;
183 if (!canClobberPhysRegForSS(SlotOrReMat))
184 return false;
185 }
186 return true;
187 }
188
189 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
190 /// stackslot register. The register is still available but is no longer
191 /// allowed to be modifed.
192 void disallowClobberPhysReg(unsigned PhysReg);
193
194 /// ClobberPhysReg - This is called when the specified physreg changes
195 /// value. We use this to invalidate any info about stuff that lives in
196 /// it and any of its aliases.
197 void ClobberPhysReg(unsigned PhysReg);
198
199 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
200 /// slot changes. This removes information about which register the
201 /// previous value for this slot lives in (as the previous value is dead
202 /// now).
203 void ModifyStackSlotOrReMat(int SlotOrReMat);
204
205 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
206 /// into the specified MBB. Add available physical registers as potential
207 /// live-in's. If they are reused in the MBB, they will be added to the
208 /// live-in set to make register scavenger and post-allocation scheduler.
209 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
210 std::vector<MachineOperand*> &KillOps);
211};
212
213// ************************************************************************ //
214
215// ReusedOp - For each reused operand, we keep track of a bit of information,
216// in case we need to rollback upon processing a new operand. See comments
217// below.
218struct ReusedOp {
219 // The MachineInstr operand that reused an available value.
220 unsigned Operand;
221
222 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
223 unsigned StackSlotOrReMat;
224
225 // PhysRegReused - The physical register the value was available in.
226 unsigned PhysRegReused;
227
228 // AssignedPhysReg - The physreg that was assigned for use by the reload.
229 unsigned AssignedPhysReg;
230
231 // VirtReg - The virtual register itself.
232 unsigned VirtReg;
233
234 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
235 unsigned vreg)
236 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
237 AssignedPhysReg(apr), VirtReg(vreg) {}
238};
239
240/// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
241/// is reused instead of reloaded.
242class VISIBILITY_HIDDEN ReuseInfo {
243 MachineInstr &MI;
244 std::vector<ReusedOp> Reuses;
245 BitVector PhysRegsClobbered;
246public:
247 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
248 PhysRegsClobbered.resize(tri->getNumRegs());
249 }
250
251 bool hasReuses() const {
252 return !Reuses.empty();
253 }
254
255 /// addReuse - If we choose to reuse a virtual register that is already
256 /// available instead of reloading it, remember that we did so.
257 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
258 unsigned PhysRegReused, unsigned AssignedPhysReg,
259 unsigned VirtReg) {
260 // If the reload is to the assigned register anyway, no undo will be
261 // required.
262 if (PhysRegReused == AssignedPhysReg) return;
263
264 // Otherwise, remember this.
265 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
266 AssignedPhysReg, VirtReg));
267 }
268
269 void markClobbered(unsigned PhysReg) {
270 PhysRegsClobbered.set(PhysReg);
271 }
272
273 bool isClobbered(unsigned PhysReg) const {
274 return PhysRegsClobbered.test(PhysReg);
275 }
276
277 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
278 /// is some other operand that is using the specified register, either pick
279 /// a new register to use, or evict the previous reload and use this reg.
280 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
281 AvailableSpills &Spills,
282 std::vector<MachineInstr*> &MaybeDeadStores,
283 SmallSet<unsigned, 8> &Rejected,
284 BitVector &RegKills,
285 std::vector<MachineOperand*> &KillOps,
286 VirtRegMap &VRM);
287
288 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
289 /// 'Rejected' set to remember which registers have been considered and
290 /// rejected for the reload. This avoids infinite looping in case like
291 /// this:
292 /// t1 := op t2, t3
293 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
294 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
295 /// t1 <- desires r1
296 /// sees r1 is taken by t2, tries t2's reload register r0
297 /// sees r0 is taken by t3, tries t3's reload register r1
298 /// sees r1 is taken by t2, tries t2's reload register r0 ...
299 unsigned GetRegForReload(unsigned PhysReg, MachineInstr *MI,
300 AvailableSpills &Spills,
301 std::vector<MachineInstr*> &MaybeDeadStores,
302 BitVector &RegKills,
303 std::vector<MachineOperand*> &KillOps,
304 VirtRegMap &VRM) {
305 SmallSet<unsigned, 8> Rejected;
306 return GetRegForReload(PhysReg, MI, Spills, MaybeDeadStores, Rejected,
307 RegKills, KillOps, VRM);
308 }
309};
310
311
312// ****************** //
313// Utility Functions //
314// ****************** //
315
Lang Hames87e3bca2009-05-06 02:36:21 +0000316/// findSinglePredSuccessor - Return via reference a vector of machine basic
317/// blocks each of which is a successor of the specified BB and has no other
318/// predecessor.
319static void findSinglePredSuccessor(MachineBasicBlock *MBB,
320 SmallVectorImpl<MachineBasicBlock *> &Succs) {
321 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
322 SE = MBB->succ_end(); SI != SE; ++SI) {
323 MachineBasicBlock *SuccMBB = *SI;
324 if (SuccMBB->pred_size() == 1)
325 Succs.push_back(SuccMBB);
326 }
327}
328
Evan Cheng427a6b62009-05-15 06:48:19 +0000329/// InvalidateKill - Invalidate register kill information for a specific
330/// register. This also unsets the kills marker on the last kill operand.
331static void InvalidateKill(unsigned Reg,
332 const TargetRegisterInfo* TRI,
333 BitVector &RegKills,
334 std::vector<MachineOperand*> &KillOps) {
335 if (RegKills[Reg]) {
336 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000337 // KillOps[Reg] might be a def of a super-register.
338 unsigned KReg = KillOps[Reg]->getReg();
339 KillOps[KReg] = NULL;
340 RegKills.reset(KReg);
341 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
Evan Cheng427a6b62009-05-15 06:48:19 +0000342 if (RegKills[*SR]) {
343 KillOps[*SR]->setIsKill(false);
344 KillOps[*SR] = NULL;
345 RegKills.reset(*SR);
346 }
347 }
348 }
349}
350
Lang Hames87e3bca2009-05-06 02:36:21 +0000351/// InvalidateKills - MI is going to be deleted. If any of its operands are
352/// marked kill, then invalidate the information.
Evan Cheng427a6b62009-05-15 06:48:19 +0000353static void InvalidateKills(MachineInstr &MI,
354 const TargetRegisterInfo* TRI,
355 BitVector &RegKills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000356 std::vector<MachineOperand*> &KillOps,
357 SmallVector<unsigned, 2> *KillRegs = NULL) {
358 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
359 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000360 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000361 continue;
362 unsigned Reg = MO.getReg();
363 if (TargetRegisterInfo::isVirtualRegister(Reg))
364 continue;
365 if (KillRegs)
366 KillRegs->push_back(Reg);
367 assert(Reg < KillOps.size());
368 if (KillOps[Reg] == &MO) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000369 KillOps[Reg] = NULL;
Evan Cheng427a6b62009-05-15 06:48:19 +0000370 RegKills.reset(Reg);
371 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
372 if (RegKills[*SR]) {
373 KillOps[*SR] = NULL;
374 RegKills.reset(*SR);
375 }
376 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000377 }
378 }
379}
380
381/// InvalidateRegDef - If the def operand of the specified def MI is now dead
382/// (since it's spill instruction is removed), mark it isDead. Also checks if
383/// the def MI has other definition operands that are not dead. Returns it by
384/// reference.
385static bool InvalidateRegDef(MachineBasicBlock::iterator I,
386 MachineInstr &NewDef, unsigned Reg,
387 bool &HasLiveDef) {
388 // Due to remat, it's possible this reg isn't being reused. That is,
389 // the def of this reg (by prev MI) is now dead.
390 MachineInstr *DefMI = I;
391 MachineOperand *DefOp = NULL;
392 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
393 MachineOperand &MO = DefMI->getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000394 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
395 continue;
396 if (MO.getReg() == Reg)
397 DefOp = &MO;
398 else if (!MO.isDead())
399 HasLiveDef = true;
Lang Hames87e3bca2009-05-06 02:36:21 +0000400 }
401 if (!DefOp)
402 return false;
403
404 bool FoundUse = false, Done = false;
405 MachineBasicBlock::iterator E = &NewDef;
406 ++I; ++E;
407 for (; !Done && I != E; ++I) {
408 MachineInstr *NMI = I;
409 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
410 MachineOperand &MO = NMI->getOperand(j);
411 if (!MO.isReg() || MO.getReg() != Reg)
412 continue;
413 if (MO.isUse())
414 FoundUse = true;
415 Done = true; // Stop after scanning all the operands of this MI.
416 }
417 }
418 if (!FoundUse) {
419 // Def is dead!
420 DefOp->setIsDead();
421 return true;
422 }
423 return false;
424}
425
426/// UpdateKills - Track and update kill info. If a MI reads a register that is
427/// marked kill, then it must be due to register reuse. Transfer the kill info
428/// over.
Evan Cheng427a6b62009-05-15 06:48:19 +0000429static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
430 BitVector &RegKills,
431 std::vector<MachineOperand*> &KillOps) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000432 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
433 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000434 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000435 continue;
436 unsigned Reg = MO.getReg();
437 if (Reg == 0)
438 continue;
439
440 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
441 // That can't be right. Register is killed but not re-defined and it's
442 // being reused. Let's fix that.
443 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000444 // KillOps[Reg] might be a def of a super-register.
445 unsigned KReg = KillOps[Reg]->getReg();
446 KillOps[KReg] = NULL;
447 RegKills.reset(KReg);
448
449 // Must be a def of a super-register. Its other sub-regsters are no
450 // longer killed as well.
451 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
452 KillOps[*SR] = NULL;
453 RegKills.reset(*SR);
454 }
455
Lang Hames87e3bca2009-05-06 02:36:21 +0000456 if (!MI.isRegTiedToDefOperand(i))
457 // Unless it's a two-address operand, this is the new kill.
458 MO.setIsKill();
459 }
460 if (MO.isKill()) {
461 RegKills.set(Reg);
462 KillOps[Reg] = &MO;
Evan Cheng427a6b62009-05-15 06:48:19 +0000463 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
464 RegKills.set(*SR);
465 KillOps[*SR] = &MO;
466 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000467 }
468 }
469
470 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
471 const MachineOperand &MO = MI.getOperand(i);
472 if (!MO.isReg() || !MO.isDef())
473 continue;
474 unsigned Reg = MO.getReg();
475 RegKills.reset(Reg);
476 KillOps[Reg] = NULL;
477 // It also defines (or partially define) aliases.
Evan Cheng427a6b62009-05-15 06:48:19 +0000478 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
479 RegKills.reset(*SR);
480 KillOps[*SR] = NULL;
Lang Hames87e3bca2009-05-06 02:36:21 +0000481 }
482 }
483}
484
485/// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
486///
487static void ReMaterialize(MachineBasicBlock &MBB,
488 MachineBasicBlock::iterator &MII,
489 unsigned DestReg, unsigned Reg,
490 const TargetInstrInfo *TII,
491 const TargetRegisterInfo *TRI,
492 VirtRegMap &VRM) {
493 TII->reMaterialize(MBB, MII, DestReg, VRM.getReMaterializedMI(Reg));
494 MachineInstr *NewMI = prior(MII);
495 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
496 MachineOperand &MO = NewMI->getOperand(i);
497 if (!MO.isReg() || MO.getReg() == 0)
498 continue;
499 unsigned VirtReg = MO.getReg();
500 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
501 continue;
502 assert(MO.isUse());
503 unsigned SubIdx = MO.getSubReg();
504 unsigned Phys = VRM.getPhys(VirtReg);
505 assert(Phys);
506 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
507 MO.setReg(RReg);
508 MO.setSubReg(0);
509 }
510 ++NumReMats;
511}
512
513/// findSuperReg - Find the SubReg's super-register of given register class
514/// where its SubIdx sub-register is SubReg.
515static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
516 unsigned SubIdx, const TargetRegisterInfo *TRI) {
517 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
518 I != E; ++I) {
519 unsigned Reg = *I;
520 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
521 return Reg;
522 }
523 return 0;
524}
525
526// ******************************** //
527// Available Spills Implementation //
528// ******************************** //
529
530/// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
531/// stackslot register. The register is still available but is no longer
532/// allowed to be modifed.
533void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
534 std::multimap<unsigned, int>::iterator I =
535 PhysRegsAvailable.lower_bound(PhysReg);
536 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
537 int SlotOrReMat = I->second;
538 I++;
539 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
540 "Bidirectional map mismatch!");
541 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
542 DOUT << "PhysReg " << TRI->getName(PhysReg)
543 << " copied, it is available for use but can no longer be modified\n";
544 }
545}
546
547/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
548/// stackslot register and its aliases. The register and its aliases may
549/// still available but is no longer allowed to be modifed.
550void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
551 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
552 disallowClobberPhysRegOnly(*AS);
553 disallowClobberPhysRegOnly(PhysReg);
554}
555
556/// ClobberPhysRegOnly - This is called when the specified physreg changes
557/// value. We use this to invalidate any info about stuff we thing lives in it.
558void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
559 std::multimap<unsigned, int>::iterator I =
560 PhysRegsAvailable.lower_bound(PhysReg);
561 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
562 int SlotOrReMat = I->second;
563 PhysRegsAvailable.erase(I++);
564 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
565 "Bidirectional map mismatch!");
566 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
567 DOUT << "PhysReg " << TRI->getName(PhysReg)
568 << " clobbered, invalidating ";
569 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
570 DOUT << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 << "\n";
571 else
572 DOUT << "SS#" << SlotOrReMat << "\n";
573 }
574}
575
576/// ClobberPhysReg - This is called when the specified physreg changes
577/// value. We use this to invalidate any info about stuff we thing lives in
578/// it and any of its aliases.
579void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
580 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
581 ClobberPhysRegOnly(*AS);
582 ClobberPhysRegOnly(PhysReg);
583}
584
585/// AddAvailableRegsToLiveIn - Availability information is being kept coming
586/// into the specified MBB. Add available physical registers as potential
587/// live-in's. If they are reused in the MBB, they will be added to the
588/// live-in set to make register scavenger and post-allocation scheduler.
589void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
590 BitVector &RegKills,
591 std::vector<MachineOperand*> &KillOps) {
592 std::set<unsigned> NotAvailable;
593 for (std::multimap<unsigned, int>::iterator
594 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
595 I != E; ++I) {
596 unsigned Reg = I->first;
597 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
598 // FIXME: A temporary workaround. We can't reuse available value if it's
599 // not safe to move the def of the virtual register's class. e.g.
600 // X86::RFP* register classes. Do not add it as a live-in.
601 if (!TII->isSafeToMoveRegClassDefs(RC))
602 // This is no longer available.
603 NotAvailable.insert(Reg);
604 else {
605 MBB.addLiveIn(Reg);
Evan Cheng427a6b62009-05-15 06:48:19 +0000606 InvalidateKill(Reg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +0000607 }
608
609 // Skip over the same register.
610 std::multimap<unsigned, int>::iterator NI = next(I);
611 while (NI != E && NI->first == Reg) {
612 ++I;
613 ++NI;
614 }
615 }
616
617 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
618 E = NotAvailable.end(); I != E; ++I) {
619 ClobberPhysReg(*I);
620 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
621 *SubRegs; ++SubRegs)
622 ClobberPhysReg(*SubRegs);
623 }
624}
625
626/// ModifyStackSlotOrReMat - This method is called when the value in a stack
627/// slot changes. This removes information about which register the previous
628/// value for this slot lives in (as the previous value is dead now).
629void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
630 std::map<int, unsigned>::iterator It =
631 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
632 if (It == SpillSlotsOrReMatsAvailable.end()) return;
633 unsigned Reg = It->second >> 1;
634 SpillSlotsOrReMatsAvailable.erase(It);
635
636 // This register may hold the value of multiple stack slots, only remove this
637 // stack slot from the set of values the register contains.
638 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
639 for (; ; ++I) {
640 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
641 "Map inverse broken!");
642 if (I->second == SlotOrReMat) break;
643 }
644 PhysRegsAvailable.erase(I);
645}
646
647// ************************** //
648// Reuse Info Implementation //
649// ************************** //
650
651/// GetRegForReload - We are about to emit a reload into PhysReg. If there
652/// is some other operand that is using the specified register, either pick
653/// a new register to use, or evict the previous reload and use this reg.
654unsigned ReuseInfo::GetRegForReload(unsigned PhysReg, MachineInstr *MI,
655 AvailableSpills &Spills,
656 std::vector<MachineInstr*> &MaybeDeadStores,
657 SmallSet<unsigned, 8> &Rejected,
658 BitVector &RegKills,
659 std::vector<MachineOperand*> &KillOps,
660 VirtRegMap &VRM) {
661 const TargetInstrInfo* TII = MI->getParent()->getParent()->getTarget()
662 .getInstrInfo();
663
664 if (Reuses.empty()) return PhysReg; // This is most often empty.
665
666 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
667 ReusedOp &Op = Reuses[ro];
668 // If we find some other reuse that was supposed to use this register
669 // exactly for its reload, we can change this reload to use ITS reload
670 // register. That is, unless its reload register has already been
671 // considered and subsequently rejected because it has also been reused
672 // by another operand.
673 if (Op.PhysRegReused == PhysReg &&
674 Rejected.count(Op.AssignedPhysReg) == 0) {
675 // Yup, use the reload register that we didn't use before.
676 unsigned NewReg = Op.AssignedPhysReg;
677 Rejected.insert(PhysReg);
678 return GetRegForReload(NewReg, MI, Spills, MaybeDeadStores, Rejected,
679 RegKills, KillOps, VRM);
680 } else {
681 // Otherwise, we might also have a problem if a previously reused
682 // value aliases the new register. If so, codegen the previous reload
683 // and use this one.
684 unsigned PRRU = Op.PhysRegReused;
685 const TargetRegisterInfo *TRI = Spills.getRegInfo();
686 if (TRI->areAliases(PRRU, PhysReg)) {
687 // Okay, we found out that an alias of a reused register
688 // was used. This isn't good because it means we have
689 // to undo a previous reuse.
690 MachineBasicBlock *MBB = MI->getParent();
691 const TargetRegisterClass *AliasRC =
692 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
693
694 // Copy Op out of the vector and remove it, we're going to insert an
695 // explicit load for it.
696 ReusedOp NewOp = Op;
697 Reuses.erase(Reuses.begin()+ro);
698
699 // Ok, we're going to try to reload the assigned physreg into the
700 // slot that we were supposed to in the first place. However, that
701 // register could hold a reuse. Check to see if it conflicts or
702 // would prefer us to use a different register.
703 unsigned NewPhysReg = GetRegForReload(NewOp.AssignedPhysReg,
704 MI, Spills, MaybeDeadStores,
705 Rejected, RegKills, KillOps, VRM);
706
707 MachineBasicBlock::iterator MII = MI;
708 if (NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT) {
709 ReMaterialize(*MBB, MII, NewPhysReg, NewOp.VirtReg, TII, TRI,VRM);
710 } else {
711 TII->loadRegFromStackSlot(*MBB, MII, NewPhysReg,
712 NewOp.StackSlotOrReMat, AliasRC);
713 MachineInstr *LoadMI = prior(MII);
714 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
715 // Any stores to this stack slot are not dead anymore.
716 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
717 ++NumLoads;
718 }
719 Spills.ClobberPhysReg(NewPhysReg);
720 Spills.ClobberPhysReg(NewOp.PhysRegReused);
721
722 unsigned SubIdx = MI->getOperand(NewOp.Operand).getSubReg();
723 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) : NewPhysReg;
724 MI->getOperand(NewOp.Operand).setReg(RReg);
725 MI->getOperand(NewOp.Operand).setSubReg(0);
726
727 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
728 --MII;
Evan Cheng427a6b62009-05-15 06:48:19 +0000729 UpdateKills(*MII, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +0000730 DOUT << '\t' << *MII;
731
732 DOUT << "Reuse undone!\n";
733 --NumReused;
734
735 // Finally, PhysReg is now available, go ahead and use it.
736 return PhysReg;
737 }
738 }
739 }
740 return PhysReg;
741}
742
743// ************************************************************************ //
744
745/// FoldsStackSlotModRef - Return true if the specified MI folds the specified
746/// stack slot mod/ref. It also checks if it's possible to unfold the
747/// instruction by having it define a specified physical register instead.
748static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
749 const TargetInstrInfo *TII,
750 const TargetRegisterInfo *TRI,
751 VirtRegMap &VRM) {
752 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
753 return false;
754
755 bool Found = false;
756 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
757 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
758 unsigned VirtReg = I->second.first;
759 VirtRegMap::ModRef MR = I->second.second;
760 if (MR & VirtRegMap::isModRef)
761 if (VRM.getStackSlot(VirtReg) == SS) {
762 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
763 break;
764 }
765 }
766 if (!Found)
767 return false;
768
769 // Does the instruction uses a register that overlaps the scratch register?
770 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
771 MachineOperand &MO = MI.getOperand(i);
772 if (!MO.isReg() || MO.getReg() == 0)
773 continue;
774 unsigned Reg = MO.getReg();
775 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
776 if (!VRM.hasPhys(Reg))
777 continue;
778 Reg = VRM.getPhys(Reg);
779 }
780 if (TRI->regsOverlap(PhysReg, Reg))
781 return false;
782 }
783 return true;
784}
785
786/// FindFreeRegister - Find a free register of a given register class by looking
787/// at (at most) the last two machine instructions.
788static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
789 MachineBasicBlock &MBB,
790 const TargetRegisterClass *RC,
791 const TargetRegisterInfo *TRI,
792 BitVector &AllocatableRegs) {
793 BitVector Defs(TRI->getNumRegs());
794 BitVector Uses(TRI->getNumRegs());
795 SmallVector<unsigned, 4> LocalUses;
796 SmallVector<unsigned, 4> Kills;
797
798 // Take a look at 2 instructions at most.
799 for (unsigned Count = 0; Count < 2; ++Count) {
800 if (MII == MBB.begin())
801 break;
802 MachineInstr *PrevMI = prior(MII);
803 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
804 MachineOperand &MO = PrevMI->getOperand(i);
805 if (!MO.isReg() || MO.getReg() == 0)
806 continue;
807 unsigned Reg = MO.getReg();
808 if (MO.isDef()) {
809 Defs.set(Reg);
810 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
811 Defs.set(*AS);
812 } else {
813 LocalUses.push_back(Reg);
814 if (MO.isKill() && AllocatableRegs[Reg])
815 Kills.push_back(Reg);
816 }
817 }
818
819 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
820 unsigned Kill = Kills[i];
821 if (!Defs[Kill] && !Uses[Kill] &&
822 TRI->getPhysicalRegisterRegClass(Kill) == RC)
823 return Kill;
824 }
825 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
826 unsigned Reg = LocalUses[i];
827 Uses.set(Reg);
828 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
829 Uses.set(*AS);
830 }
831
832 MII = PrevMI;
833 }
834
835 return 0;
836}
837
838static
839void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
840 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
841 MachineOperand &MO = MI->getOperand(i);
842 if (MO.isReg() && MO.getReg() == VirtReg)
843 MO.setReg(PhysReg);
844 }
845}
846
Evan Chengeca24fb2009-05-12 23:07:00 +0000847namespace {
848 struct RefSorter {
849 bool operator()(const std::pair<MachineInstr*, int> &A,
850 const std::pair<MachineInstr*, int> &B) {
851 return A.second < B.second;
852 }
853 };
854}
Lang Hames87e3bca2009-05-06 02:36:21 +0000855
856// ***************************** //
857// Local Spiller Implementation //
858// ***************************** //
859
860class VISIBILITY_HIDDEN LocalRewriter : public VirtRegRewriter {
861 MachineRegisterInfo *RegInfo;
862 const TargetRegisterInfo *TRI;
863 const TargetInstrInfo *TII;
864 BitVector AllocatableRegs;
865 DenseMap<MachineInstr*, unsigned> DistanceMap;
866public:
867
868 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
869 LiveIntervals* LIs) {
870 RegInfo = &MF.getRegInfo();
871 TRI = MF.getTarget().getRegisterInfo();
872 TII = MF.getTarget().getInstrInfo();
873 AllocatableRegs = TRI->getAllocatableSet(MF);
874 DOUT << "\n**** Local spiller rewriting function '"
875 << MF.getFunction()->getName() << "':\n";
876 DOUT << "**** Machine Instrs (NOTE! Does not include spills and reloads!)"
877 " ****\n";
878 DEBUG(MF.dump());
879
880 // Spills - Keep track of which spilled values are available in physregs
881 // so that we can choose to reuse the physregs instead of emitting
882 // reloads. This is usually refreshed per basic block.
883 AvailableSpills Spills(TRI, TII);
884
885 // Keep track of kill information.
886 BitVector RegKills(TRI->getNumRegs());
887 std::vector<MachineOperand*> KillOps;
888 KillOps.resize(TRI->getNumRegs(), NULL);
889
890 // SingleEntrySuccs - Successor blocks which have a single predecessor.
891 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
892 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
893
894 // Traverse the basic blocks depth first.
895 MachineBasicBlock *Entry = MF.begin();
896 SmallPtrSet<MachineBasicBlock*,16> Visited;
897 for (df_ext_iterator<MachineBasicBlock*,
898 SmallPtrSet<MachineBasicBlock*,16> >
899 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
900 DFI != E; ++DFI) {
901 MachineBasicBlock *MBB = *DFI;
902 if (!EarlyVisited.count(MBB))
903 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
904
905 // If this MBB is the only predecessor of a successor. Keep the
906 // availability information and visit it next.
907 do {
908 // Keep visiting single predecessor successor as long as possible.
909 SinglePredSuccs.clear();
910 findSinglePredSuccessor(MBB, SinglePredSuccs);
911 if (SinglePredSuccs.empty())
912 MBB = 0;
913 else {
914 // FIXME: More than one successors, each of which has MBB has
915 // the only predecessor.
916 MBB = SinglePredSuccs[0];
917 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
918 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
919 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
920 }
921 }
922 } while (MBB);
923
924 // Clear the availability info.
925 Spills.clear();
926 }
927
928 DOUT << "**** Post Machine Instrs ****\n";
929 DEBUG(MF.dump());
930
931 // Mark unused spill slots.
932 MachineFrameInfo *MFI = MF.getFrameInfo();
933 int SS = VRM.getLowSpillSlot();
934 if (SS != VirtRegMap::NO_STACK_SLOT)
935 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
936 if (!VRM.isSpillSlotUsed(SS)) {
937 MFI->RemoveStackObject(SS);
938 ++NumDSS;
939 }
940
941 return true;
942 }
943
944private:
945
946 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
947 /// a scratch register is available.
948 /// xorq %r12<kill>, %r13
949 /// addq %rax, -184(%rbp)
950 /// addq %r13, -184(%rbp)
951 /// ==>
952 /// xorq %r12<kill>, %r13
953 /// movq -184(%rbp), %r12
954 /// addq %rax, %r12
955 /// addq %r13, %r12
956 /// movq %r12, -184(%rbp)
957 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
958 MachineBasicBlock &MBB,
959 MachineBasicBlock::iterator &MII,
960 std::vector<MachineInstr*> &MaybeDeadStores,
961 AvailableSpills &Spills,
962 BitVector &RegKills,
963 std::vector<MachineOperand*> &KillOps,
964 VirtRegMap &VRM) {
965
966 MachineBasicBlock::iterator NextMII = next(MII);
967 if (NextMII == MBB.end())
968 return false;
969
970 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
971 return false;
972
973 // Now let's see if the last couple of instructions happens to have freed up
974 // a register.
975 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
976 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
977 if (!PhysReg)
978 return false;
979
980 MachineFunction &MF = *MBB.getParent();
981 TRI = MF.getTarget().getRegisterInfo();
982 MachineInstr &MI = *MII;
983 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
984 return false;
985
986 // If the next instruction also folds the same SS modref and can be unfoled,
987 // then it's worthwhile to issue a load from SS into the free register and
988 // then unfold these instructions.
989 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
990 return false;
991
992 // Load from SS to the spare physical register.
993 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
994 // This invalidates Phys.
995 Spills.ClobberPhysReg(PhysReg);
996 // Remember it's available.
997 Spills.addAvailable(SS, PhysReg);
998 MaybeDeadStores[SS] = NULL;
999
1000 // Unfold current MI.
1001 SmallVector<MachineInstr*, 4> NewMIs;
1002 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
Torok Edwinc23197a2009-07-14 16:55:14 +00001003 llvm_unreachable("Unable unfold the load / store folding instruction!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001004 assert(NewMIs.size() == 1);
1005 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1006 VRM.transferRestorePts(&MI, NewMIs[0]);
1007 MII = MBB.insert(MII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00001008 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001009 VRM.RemoveMachineInstrFromMaps(&MI);
1010 MBB.erase(&MI);
1011 ++NumModRefUnfold;
1012
1013 // Unfold next instructions that fold the same SS.
1014 do {
1015 MachineInstr &NextMI = *NextMII;
1016 NextMII = next(NextMII);
1017 NewMIs.clear();
1018 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
Torok Edwinc23197a2009-07-14 16:55:14 +00001019 llvm_unreachable("Unable unfold the load / store folding instruction!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001020 assert(NewMIs.size() == 1);
1021 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1022 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1023 MBB.insert(NextMII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00001024 InvalidateKills(NextMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001025 VRM.RemoveMachineInstrFromMaps(&NextMI);
1026 MBB.erase(&NextMI);
1027 ++NumModRefUnfold;
Evan Cheng2c48fe62009-06-03 09:00:27 +00001028 if (NextMII == MBB.end())
1029 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001030 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1031
1032 // Store the value back into SS.
1033 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1034 MachineInstr *StoreMI = prior(NextMII);
1035 VRM.addSpillSlotUse(SS, StoreMI);
1036 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1037
1038 return true;
1039 }
1040
1041 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1042 /// instruction. e.g.
1043 /// xorl %edi, %eax
1044 /// movl %eax, -32(%ebp)
1045 /// movl -36(%ebp), %eax
1046 /// orl %eax, -32(%ebp)
1047 /// ==>
1048 /// xorl %edi, %eax
1049 /// orl -36(%ebp), %eax
1050 /// mov %eax, -32(%ebp)
1051 /// This enables unfolding optimization for a subsequent instruction which will
1052 /// also eliminate the newly introduced store instruction.
1053 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1054 MachineBasicBlock::iterator &MII,
1055 std::vector<MachineInstr*> &MaybeDeadStores,
1056 AvailableSpills &Spills,
1057 BitVector &RegKills,
1058 std::vector<MachineOperand*> &KillOps,
1059 VirtRegMap &VRM) {
1060 MachineFunction &MF = *MBB.getParent();
1061 MachineInstr &MI = *MII;
1062 unsigned UnfoldedOpc = 0;
1063 unsigned UnfoldPR = 0;
1064 unsigned UnfoldVR = 0;
1065 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1066 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1067 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1068 // Only transform a MI that folds a single register.
1069 if (UnfoldedOpc)
1070 return false;
1071 UnfoldVR = I->second.first;
1072 VirtRegMap::ModRef MR = I->second.second;
1073 // MI2VirtMap be can updated which invalidate the iterator.
1074 // Increment the iterator first.
1075 ++I;
1076 if (VRM.isAssignedReg(UnfoldVR))
1077 continue;
1078 // If this reference is not a use, any previous store is now dead.
1079 // Otherwise, the store to this stack slot is not dead anymore.
1080 FoldedSS = VRM.getStackSlot(UnfoldVR);
1081 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1082 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1083 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1084 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1085 continue;
1086 UnfoldPR = PhysReg;
1087 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1088 false, true);
1089 }
1090 }
1091
1092 if (!UnfoldedOpc) {
1093 if (!UnfoldVR)
1094 return false;
1095
1096 // Look for other unfolding opportunities.
1097 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1098 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1099 }
1100
1101 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1102 MachineOperand &MO = MI.getOperand(i);
1103 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1104 continue;
1105 unsigned VirtReg = MO.getReg();
1106 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1107 continue;
1108 if (VRM.isAssignedReg(VirtReg)) {
1109 unsigned PhysReg = VRM.getPhys(VirtReg);
1110 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1111 return false;
1112 } else if (VRM.isReMaterialized(VirtReg))
1113 continue;
1114 int SS = VRM.getStackSlot(VirtReg);
1115 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1116 if (PhysReg) {
1117 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1118 return false;
1119 continue;
1120 }
1121 if (VRM.hasPhys(VirtReg)) {
1122 PhysReg = VRM.getPhys(VirtReg);
1123 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1124 continue;
1125 }
1126
1127 // Ok, we'll need to reload the value into a register which makes
1128 // it impossible to perform the store unfolding optimization later.
1129 // Let's see if it is possible to fold the load if the store is
1130 // unfolded. This allows us to perform the store unfolding
1131 // optimization.
1132 SmallVector<MachineInstr*, 4> NewMIs;
1133 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1134 assert(NewMIs.size() == 1);
1135 MachineInstr *NewMI = NewMIs.back();
1136 NewMIs.clear();
1137 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1138 assert(Idx != -1);
1139 SmallVector<unsigned, 1> Ops;
1140 Ops.push_back(Idx);
1141 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1142 if (FoldedMI) {
1143 VRM.addSpillSlotUse(SS, FoldedMI);
1144 if (!VRM.hasPhys(UnfoldVR))
1145 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1146 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1147 MII = MBB.insert(MII, FoldedMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001148 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001149 VRM.RemoveMachineInstrFromMaps(&MI);
1150 MBB.erase(&MI);
1151 MF.DeleteMachineInstr(NewMI);
1152 return true;
1153 }
1154 MF.DeleteMachineInstr(NewMI);
1155 }
1156 }
1157
1158 return false;
1159 }
1160
Evan Cheng261ce1d2009-07-10 19:15:51 +00001161 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1162 /// where SrcReg is r1 and it is tied to r0. Return true if after
1163 /// commuting this instruction it will be r0 = op r2, r1.
1164 static bool CommuteChangesDestination(MachineInstr *DefMI,
1165 const TargetInstrDesc &TID,
1166 unsigned SrcReg,
1167 const TargetInstrInfo *TII,
1168 unsigned &DstIdx) {
1169 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1170 return false;
1171 if (!DefMI->getOperand(1).isReg() ||
1172 DefMI->getOperand(1).getReg() != SrcReg)
1173 return false;
1174 unsigned DefIdx;
1175 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1176 return false;
1177 unsigned SrcIdx1, SrcIdx2;
1178 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1179 return false;
1180 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1181 DstIdx = 2;
1182 return true;
1183 }
1184 return false;
1185 }
1186
Lang Hames87e3bca2009-05-06 02:36:21 +00001187 /// CommuteToFoldReload -
1188 /// Look for
1189 /// r1 = load fi#1
1190 /// r1 = op r1, r2<kill>
1191 /// store r1, fi#1
1192 ///
1193 /// If op is commutable and r2 is killed, then we can xform these to
1194 /// r2 = op r2, fi#1
1195 /// store r2, fi#1
1196 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1197 MachineBasicBlock::iterator &MII,
1198 unsigned VirtReg, unsigned SrcReg, int SS,
1199 AvailableSpills &Spills,
1200 BitVector &RegKills,
1201 std::vector<MachineOperand*> &KillOps,
1202 const TargetRegisterInfo *TRI,
1203 VirtRegMap &VRM) {
1204 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1205 return false;
1206
1207 MachineFunction &MF = *MBB.getParent();
1208 MachineInstr &MI = *MII;
1209 MachineBasicBlock::iterator DefMII = prior(MII);
1210 MachineInstr *DefMI = DefMII;
1211 const TargetInstrDesc &TID = DefMI->getDesc();
1212 unsigned NewDstIdx;
1213 if (DefMII != MBB.begin() &&
1214 TID.isCommutable() &&
Evan Cheng261ce1d2009-07-10 19:15:51 +00001215 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001216 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1217 unsigned NewReg = NewDstMO.getReg();
1218 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1219 return false;
1220 MachineInstr *ReloadMI = prior(DefMII);
1221 int FrameIdx;
1222 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1223 if (DestReg != SrcReg || FrameIdx != SS)
1224 return false;
1225 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1226 if (UseIdx == -1)
1227 return false;
1228 unsigned DefIdx;
1229 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1230 return false;
1231 assert(DefMI->getOperand(DefIdx).isReg() &&
1232 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1233
1234 // Now commute def instruction.
1235 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1236 if (!CommutedMI)
1237 return false;
1238 SmallVector<unsigned, 1> Ops;
1239 Ops.push_back(NewDstIdx);
1240 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1241 // Not needed since foldMemoryOperand returns new MI.
1242 MF.DeleteMachineInstr(CommutedMI);
1243 if (!FoldedMI)
1244 return false;
1245
1246 VRM.addSpillSlotUse(SS, FoldedMI);
1247 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1248 // Insert new def MI and spill MI.
1249 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1250 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1251 MII = prior(MII);
1252 MachineInstr *StoreMI = MII;
1253 VRM.addSpillSlotUse(SS, StoreMI);
1254 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1255 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1256
1257 // Delete all 3 old instructions.
Evan Cheng427a6b62009-05-15 06:48:19 +00001258 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001259 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1260 MBB.erase(ReloadMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001261 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001262 VRM.RemoveMachineInstrFromMaps(DefMI);
1263 MBB.erase(DefMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001264 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001265 VRM.RemoveMachineInstrFromMaps(&MI);
1266 MBB.erase(&MI);
1267
1268 // If NewReg was previously holding value of some SS, it's now clobbered.
1269 // This has to be done now because it's a physical register. When this
1270 // instruction is re-visited, it's ignored.
1271 Spills.ClobberPhysReg(NewReg);
1272
1273 ++NumCommutes;
1274 return true;
1275 }
1276
1277 return false;
1278 }
1279
1280 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1281 /// the last store to the same slot is now dead. If so, remove the last store.
1282 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1283 MachineBasicBlock::iterator &MII,
1284 int Idx, unsigned PhysReg, int StackSlot,
1285 const TargetRegisterClass *RC,
1286 bool isAvailable, MachineInstr *&LastStore,
1287 AvailableSpills &Spills,
1288 SmallSet<MachineInstr*, 4> &ReMatDefs,
1289 BitVector &RegKills,
1290 std::vector<MachineOperand*> &KillOps,
1291 VirtRegMap &VRM) {
1292
1293 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1294 MachineInstr *StoreMI = next(MII);
1295 VRM.addSpillSlotUse(StackSlot, StoreMI);
1296 DOUT << "Store:\t" << *StoreMI;
1297
1298 // If there is a dead store to this stack slot, nuke it now.
1299 if (LastStore) {
1300 DOUT << "Removed dead store:\t" << *LastStore;
1301 ++NumDSE;
1302 SmallVector<unsigned, 2> KillRegs;
Evan Cheng427a6b62009-05-15 06:48:19 +00001303 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
Lang Hames87e3bca2009-05-06 02:36:21 +00001304 MachineBasicBlock::iterator PrevMII = LastStore;
1305 bool CheckDef = PrevMII != MBB.begin();
1306 if (CheckDef)
1307 --PrevMII;
1308 VRM.RemoveMachineInstrFromMaps(LastStore);
1309 MBB.erase(LastStore);
1310 if (CheckDef) {
1311 // Look at defs of killed registers on the store. Mark the defs
1312 // as dead since the store has been deleted and they aren't
1313 // being reused.
1314 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1315 bool HasOtherDef = false;
1316 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1317 MachineInstr *DeadDef = PrevMII;
1318 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
Evan Cheng4784f1f2009-06-30 08:49:04 +00001319 // FIXME: This assumes a remat def does not have side effects.
Lang Hames87e3bca2009-05-06 02:36:21 +00001320 VRM.RemoveMachineInstrFromMaps(DeadDef);
1321 MBB.erase(DeadDef);
1322 ++NumDRM;
1323 }
1324 }
1325 }
1326 }
1327 }
1328
1329 LastStore = next(MII);
1330
1331 // If the stack slot value was previously available in some other
1332 // register, change it now. Otherwise, make the register available,
1333 // in PhysReg.
1334 Spills.ModifyStackSlotOrReMat(StackSlot);
1335 Spills.ClobberPhysReg(PhysReg);
1336 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1337 ++NumStores;
1338 }
1339
1340 /// TransferDeadness - A identity copy definition is dead and it's being
1341 /// removed. Find the last def or use and mark it as dead / kill.
1342 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1343 unsigned Reg, BitVector &RegKills,
Evan Chengeca24fb2009-05-12 23:07:00 +00001344 std::vector<MachineOperand*> &KillOps,
1345 VirtRegMap &VRM) {
1346 SmallPtrSet<MachineInstr*, 4> Seens;
1347 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
Lang Hames87e3bca2009-05-06 02:36:21 +00001348 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1349 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1350 MachineInstr *UDMI = &*RI;
1351 if (UDMI->getParent() != MBB)
1352 continue;
1353 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1354 if (DI == DistanceMap.end() || DI->second > CurDist)
1355 continue;
Evan Chengeca24fb2009-05-12 23:07:00 +00001356 if (Seens.insert(UDMI))
1357 Refs.push_back(std::make_pair(UDMI, DI->second));
Lang Hames87e3bca2009-05-06 02:36:21 +00001358 }
1359
Evan Chengeca24fb2009-05-12 23:07:00 +00001360 if (Refs.empty())
1361 return;
1362 std::sort(Refs.begin(), Refs.end(), RefSorter());
1363
1364 while (!Refs.empty()) {
1365 MachineInstr *LastUDMI = Refs.back().first;
1366 Refs.pop_back();
1367
Lang Hames87e3bca2009-05-06 02:36:21 +00001368 MachineOperand *LastUD = NULL;
1369 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1370 MachineOperand &MO = LastUDMI->getOperand(i);
1371 if (!MO.isReg() || MO.getReg() != Reg)
1372 continue;
1373 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1374 LastUD = &MO;
1375 if (LastUDMI->isRegTiedToDefOperand(i))
Evan Chengeca24fb2009-05-12 23:07:00 +00001376 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001377 }
Evan Chengeca24fb2009-05-12 23:07:00 +00001378 if (LastUD->isDef()) {
1379 // If the instruction has no side effect, delete it and propagate
1380 // backward further. Otherwise, mark is dead and we are done.
1381 const TargetInstrDesc &TID = LastUDMI->getDesc();
1382 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1383 TID.hasUnmodeledSideEffects()) {
1384 LastUD->setIsDead();
1385 break;
1386 }
1387 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1388 MBB->erase(LastUDMI);
1389 } else {
Lang Hames87e3bca2009-05-06 02:36:21 +00001390 LastUD->setIsKill();
1391 RegKills.set(Reg);
1392 KillOps[Reg] = LastUD;
Evan Chengeca24fb2009-05-12 23:07:00 +00001393 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001394 }
1395 }
1396 }
1397
1398 /// rewriteMBB - Keep track of which spills are available even after the
1399 /// register allocator is done with them. If possible, avid reloading vregs.
1400 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1401 LiveIntervals *LIs,
1402 AvailableSpills &Spills, BitVector &RegKills,
1403 std::vector<MachineOperand*> &KillOps) {
1404
1405 DOUT << "\n**** Local spiller rewriting MBB '"
1406 << MBB.getBasicBlock()->getName() << "':\n";
1407
1408 MachineFunction &MF = *MBB.getParent();
1409
1410 // MaybeDeadStores - When we need to write a value back into a stack slot,
1411 // keep track of the inserted store. If the stack slot value is never read
1412 // (because the value was used from some available register, for example), and
1413 // subsequently stored to, the original store is dead. This map keeps track
1414 // of inserted stores that are not used. If we see a subsequent store to the
1415 // same stack slot, the original store is deleted.
1416 std::vector<MachineInstr*> MaybeDeadStores;
1417 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1418
1419 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1420 SmallSet<MachineInstr*, 4> ReMatDefs;
1421
1422 // Clear kill info.
1423 SmallSet<unsigned, 2> KilledMIRegs;
1424 RegKills.reset();
1425 KillOps.clear();
1426 KillOps.resize(TRI->getNumRegs(), NULL);
1427
1428 unsigned Dist = 0;
1429 DistanceMap.clear();
1430 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1431 MII != E; ) {
1432 MachineBasicBlock::iterator NextMII = next(MII);
1433
1434 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1435 bool Erased = false;
1436 bool BackTracked = false;
1437 if (OptimizeByUnfold(MBB, MII,
1438 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1439 NextMII = next(MII);
1440
1441 MachineInstr &MI = *MII;
1442
1443 if (VRM.hasEmergencySpills(&MI)) {
1444 // Spill physical register(s) in the rare case the allocator has run out
1445 // of registers to allocate.
1446 SmallSet<int, 4> UsedSS;
1447 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1448 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1449 unsigned PhysReg = EmSpills[i];
1450 const TargetRegisterClass *RC =
1451 TRI->getPhysicalRegisterRegClass(PhysReg);
1452 assert(RC && "Unable to determine register class!");
1453 int SS = VRM.getEmergencySpillSlot(RC);
1454 if (UsedSS.count(SS))
Torok Edwinc23197a2009-07-14 16:55:14 +00001455 llvm_unreachable("Need to spill more than one physical registers!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001456 UsedSS.insert(SS);
1457 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1458 MachineInstr *StoreMI = prior(MII);
1459 VRM.addSpillSlotUse(SS, StoreMI);
1460 TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1461 MachineInstr *LoadMI = next(MII);
1462 VRM.addSpillSlotUse(SS, LoadMI);
1463 ++NumPSpills;
1464 }
1465 NextMII = next(MII);
1466 }
1467
1468 // Insert restores here if asked to.
1469 if (VRM.isRestorePt(&MI)) {
1470 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1471 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1472 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1473 if (!VRM.getPreSplitReg(VirtReg))
1474 continue; // Split interval spilled again.
1475 unsigned Phys = VRM.getPhys(VirtReg);
1476 RegInfo->setPhysRegUsed(Phys);
1477
1478 // Check if the value being restored if available. If so, it must be
1479 // from a predecessor BB that fallthrough into this BB. We do not
1480 // expect:
1481 // BB1:
1482 // r1 = load fi#1
1483 // ...
1484 // = r1<kill>
1485 // ... # r1 not clobbered
1486 // ...
1487 // = load fi#1
1488 bool DoReMat = VRM.isReMaterialized(VirtReg);
1489 int SSorRMId = DoReMat
1490 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1491 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1492 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1493 if (InReg == Phys) {
1494 // If the value is already available in the expected register, save
1495 // a reload / remat.
1496 if (SSorRMId)
1497 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1498 else
1499 DOUT << "Reusing SS#" << SSorRMId;
1500 DOUT << " from physreg "
1501 << TRI->getName(InReg) << " for vreg"
1502 << VirtReg <<" instead of reloading into physreg "
1503 << TRI->getName(Phys) << "\n";
1504 ++NumOmitted;
1505 continue;
1506 } else if (InReg && InReg != Phys) {
1507 if (SSorRMId)
1508 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1509 else
1510 DOUT << "Reusing SS#" << SSorRMId;
1511 DOUT << " from physreg "
1512 << TRI->getName(InReg) << " for vreg"
1513 << VirtReg <<" by copying it into physreg "
1514 << TRI->getName(Phys) << "\n";
1515
1516 // If the reloaded / remat value is available in another register,
1517 // copy it to the desired register.
1518 TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1519
1520 // This invalidates Phys.
1521 Spills.ClobberPhysReg(Phys);
1522 // Remember it's available.
1523 Spills.addAvailable(SSorRMId, Phys);
1524
1525 // Mark is killed.
1526 MachineInstr *CopyMI = prior(MII);
1527 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1528 KillOpnd->setIsKill();
Evan Cheng427a6b62009-05-15 06:48:19 +00001529 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001530
1531 DOUT << '\t' << *CopyMI;
1532 ++NumCopified;
1533 continue;
1534 }
1535
1536 if (VRM.isReMaterialized(VirtReg)) {
1537 ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1538 } else {
1539 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1540 TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1541 MachineInstr *LoadMI = prior(MII);
1542 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1543 ++NumLoads;
1544 }
1545
1546 // This invalidates Phys.
1547 Spills.ClobberPhysReg(Phys);
1548 // Remember it's available.
1549 Spills.addAvailable(SSorRMId, Phys);
1550
Evan Cheng427a6b62009-05-15 06:48:19 +00001551 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001552 DOUT << '\t' << *prior(MII);
1553 }
1554 }
1555
1556 // Insert spills here if asked to.
1557 if (VRM.isSpillPt(&MI)) {
1558 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1559 VRM.getSpillPtSpills(&MI);
1560 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1561 unsigned VirtReg = SpillRegs[i].first;
1562 bool isKill = SpillRegs[i].second;
1563 if (!VRM.getPreSplitReg(VirtReg))
1564 continue; // Split interval spilled again.
1565 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1566 unsigned Phys = VRM.getPhys(VirtReg);
1567 int StackSlot = VRM.getStackSlot(VirtReg);
1568 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1569 MachineInstr *StoreMI = next(MII);
1570 VRM.addSpillSlotUse(StackSlot, StoreMI);
1571 DOUT << "Store:\t" << *StoreMI;
1572 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1573 }
1574 NextMII = next(MII);
1575 }
1576
1577 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1578 /// reuse.
1579 ReuseInfo ReusedOperands(MI, TRI);
1580 SmallVector<unsigned, 4> VirtUseOps;
1581 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1582 MachineOperand &MO = MI.getOperand(i);
1583 if (!MO.isReg() || MO.getReg() == 0)
1584 continue; // Ignore non-register operands.
1585
1586 unsigned VirtReg = MO.getReg();
1587 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1588 // Ignore physregs for spilling, but remember that it is used by this
1589 // function.
1590 RegInfo->setPhysRegUsed(VirtReg);
1591 continue;
1592 }
1593
1594 // We want to process implicit virtual register uses first.
1595 if (MO.isImplicit())
1596 // If the virtual register is implicitly defined, emit a implicit_def
1597 // before so scavenger knows it's "defined".
Evan Cheng4784f1f2009-06-30 08:49:04 +00001598 // FIXME: This is a horrible hack done the by register allocator to
1599 // remat a definition with virtual register operand.
Lang Hames87e3bca2009-05-06 02:36:21 +00001600 VirtUseOps.insert(VirtUseOps.begin(), i);
1601 else
1602 VirtUseOps.push_back(i);
1603 }
1604
1605 // Process all of the spilled uses and all non spilled reg references.
1606 SmallVector<int, 2> PotentialDeadStoreSlots;
1607 KilledMIRegs.clear();
1608 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1609 unsigned i = VirtUseOps[j];
1610 MachineOperand &MO = MI.getOperand(i);
1611 unsigned VirtReg = MO.getReg();
1612 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1613 "Not a virtual register?");
1614
1615 unsigned SubIdx = MO.getSubReg();
1616 if (VRM.isAssignedReg(VirtReg)) {
1617 // This virtual register was assigned a physreg!
1618 unsigned Phys = VRM.getPhys(VirtReg);
1619 RegInfo->setPhysRegUsed(Phys);
1620 if (MO.isDef())
1621 ReusedOperands.markClobbered(Phys);
1622 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1623 MI.getOperand(i).setReg(RReg);
1624 MI.getOperand(i).setSubReg(0);
1625 if (VRM.isImplicitlyDefined(VirtReg))
Evan Cheng4784f1f2009-06-30 08:49:04 +00001626 // FIXME: Is this needed?
Lang Hames87e3bca2009-05-06 02:36:21 +00001627 BuildMI(MBB, &MI, MI.getDebugLoc(),
1628 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1629 continue;
1630 }
1631
1632 // This virtual register is now known to be a spilled value.
1633 if (!MO.isUse())
1634 continue; // Handle defs in the loop below (handle use&def here though)
1635
Evan Cheng4784f1f2009-06-30 08:49:04 +00001636 bool AvoidReload = MO.isUndef();
1637 // Check if it is defined by an implicit def. It should not be spilled.
1638 // Note, this is for correctness reason. e.g.
1639 // 8 %reg1024<def> = IMPLICIT_DEF
1640 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1641 // The live range [12, 14) are not part of the r1024 live interval since
1642 // it's defined by an implicit def. It will not conflicts with live
1643 // interval of r1025. Now suppose both registers are spilled, you can
1644 // easily see a situation where both registers are reloaded before
1645 // the INSERT_SUBREG and both target registers that would overlap.
Lang Hames87e3bca2009-05-06 02:36:21 +00001646 bool DoReMat = VRM.isReMaterialized(VirtReg);
1647 int SSorRMId = DoReMat
1648 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1649 int ReuseSlot = SSorRMId;
1650
1651 // Check to see if this stack slot is available.
1652 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1653
1654 // If this is a sub-register use, make sure the reuse register is in the
1655 // right register class. For example, for x86 not all of the 32-bit
1656 // registers have accessible sub-registers.
1657 // Similarly so for EXTRACT_SUBREG. Consider this:
1658 // EDI = op
1659 // MOV32_mr fi#1, EDI
1660 // ...
1661 // = EXTRACT_SUBREG fi#1
1662 // fi#1 is available in EDI, but it cannot be reused because it's not in
1663 // the right register file.
1664 if (PhysReg && !AvoidReload &&
1665 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1666 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1667 if (!RC->contains(PhysReg))
1668 PhysReg = 0;
1669 }
1670
1671 if (PhysReg && !AvoidReload) {
1672 // This spilled operand might be part of a two-address operand. If this
1673 // is the case, then changing it will necessarily require changing the
1674 // def part of the instruction as well. However, in some cases, we
1675 // aren't allowed to modify the reused register. If none of these cases
1676 // apply, reuse it.
1677 bool CanReuse = true;
1678 bool isTied = MI.isRegTiedToDefOperand(i);
1679 if (isTied) {
1680 // Okay, we have a two address operand. We can reuse this physreg as
1681 // long as we are allowed to clobber the value and there isn't an
1682 // earlier def that has already clobbered the physreg.
1683 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1684 Spills.canClobberPhysReg(PhysReg);
1685 }
1686
1687 if (CanReuse) {
1688 // If this stack slot value is already available, reuse it!
1689 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1690 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1691 else
1692 DOUT << "Reusing SS#" << ReuseSlot;
1693 DOUT << " from physreg "
1694 << TRI->getName(PhysReg) << " for vreg"
1695 << VirtReg <<" instead of reloading into physreg "
1696 << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1697 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1698 MI.getOperand(i).setReg(RReg);
1699 MI.getOperand(i).setSubReg(0);
1700
1701 // The only technical detail we have is that we don't know that
1702 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1703 // later in the instruction. In particular, consider 'op V1, V2'.
1704 // If V1 is available in physreg R0, we would choose to reuse it
1705 // here, instead of reloading it into the register the allocator
1706 // indicated (say R1). However, V2 might have to be reloaded
1707 // later, and it might indicate that it needs to live in R0. When
1708 // this occurs, we need to have information available that
1709 // indicates it is safe to use R1 for the reload instead of R0.
1710 //
1711 // To further complicate matters, we might conflict with an alias,
1712 // or R0 and R1 might not be compatible with each other. In this
1713 // case, we actually insert a reload for V1 in R1, ensuring that
1714 // we can get at R0 or its alias.
1715 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1716 VRM.getPhys(VirtReg), VirtReg);
1717 if (isTied)
1718 // Only mark it clobbered if this is a use&def operand.
1719 ReusedOperands.markClobbered(PhysReg);
1720 ++NumReused;
1721
1722 if (MI.getOperand(i).isKill() &&
1723 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1724
1725 // The store of this spilled value is potentially dead, but we
1726 // won't know for certain until we've confirmed that the re-use
1727 // above is valid, which means waiting until the other operands
1728 // are processed. For now we just track the spill slot, we'll
1729 // remove it after the other operands are processed if valid.
1730
1731 PotentialDeadStoreSlots.push_back(ReuseSlot);
1732 }
1733
1734 // Mark is isKill if it's there no other uses of the same virtual
1735 // register and it's not a two-address operand. IsKill will be
1736 // unset if reg is reused.
1737 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1738 MI.getOperand(i).setIsKill();
1739 KilledMIRegs.insert(VirtReg);
1740 }
1741
1742 continue;
1743 } // CanReuse
1744
1745 // Otherwise we have a situation where we have a two-address instruction
1746 // whose mod/ref operand needs to be reloaded. This reload is already
1747 // available in some register "PhysReg", but if we used PhysReg as the
1748 // operand to our 2-addr instruction, the instruction would modify
1749 // PhysReg. This isn't cool if something later uses PhysReg and expects
1750 // to get its initial value.
1751 //
1752 // To avoid this problem, and to avoid doing a load right after a store,
1753 // we emit a copy from PhysReg into the designated register for this
1754 // operand.
1755 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1756 assert(DesignatedReg && "Must map virtreg to physreg!");
1757
1758 // Note that, if we reused a register for a previous operand, the
1759 // register we want to reload into might not actually be
1760 // available. If this occurs, use the register indicated by the
1761 // reuser.
1762 if (ReusedOperands.hasReuses())
1763 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
1764 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1765
1766 // If the mapped designated register is actually the physreg we have
1767 // incoming, we don't need to inserted a dead copy.
1768 if (DesignatedReg == PhysReg) {
1769 // If this stack slot value is already available, reuse it!
1770 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1771 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1772 else
1773 DOUT << "Reusing SS#" << ReuseSlot;
1774 DOUT << " from physreg " << TRI->getName(PhysReg)
1775 << " for vreg" << VirtReg
1776 << " instead of reloading into same physreg.\n";
1777 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1778 MI.getOperand(i).setReg(RReg);
1779 MI.getOperand(i).setSubReg(0);
1780 ReusedOperands.markClobbered(RReg);
1781 ++NumReused;
1782 continue;
1783 }
1784
1785 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1786 RegInfo->setPhysRegUsed(DesignatedReg);
1787 ReusedOperands.markClobbered(DesignatedReg);
1788 TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1789
1790 MachineInstr *CopyMI = prior(MII);
Evan Cheng427a6b62009-05-15 06:48:19 +00001791 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001792
1793 // This invalidates DesignatedReg.
1794 Spills.ClobberPhysReg(DesignatedReg);
1795
1796 Spills.addAvailable(ReuseSlot, DesignatedReg);
1797 unsigned RReg =
1798 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1799 MI.getOperand(i).setReg(RReg);
1800 MI.getOperand(i).setSubReg(0);
1801 DOUT << '\t' << *prior(MII);
1802 ++NumReused;
1803 continue;
1804 } // if (PhysReg)
1805
1806 // Otherwise, reload it and remember that we have it.
1807 PhysReg = VRM.getPhys(VirtReg);
1808 assert(PhysReg && "Must map virtreg to physreg!");
1809
1810 // Note that, if we reused a register for a previous operand, the
1811 // register we want to reload into might not actually be
1812 // available. If this occurs, use the register indicated by the
1813 // reuser.
1814 if (ReusedOperands.hasReuses())
1815 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1816 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1817
1818 RegInfo->setPhysRegUsed(PhysReg);
1819 ReusedOperands.markClobbered(PhysReg);
1820 if (AvoidReload)
1821 ++NumAvoided;
1822 else {
1823 if (DoReMat) {
1824 ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1825 } else {
1826 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1827 TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1828 MachineInstr *LoadMI = prior(MII);
1829 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1830 ++NumLoads;
1831 }
1832 // This invalidates PhysReg.
1833 Spills.ClobberPhysReg(PhysReg);
1834
1835 // Any stores to this stack slot are not dead anymore.
1836 if (!DoReMat)
1837 MaybeDeadStores[SSorRMId] = NULL;
1838 Spills.addAvailable(SSorRMId, PhysReg);
1839 // Assumes this is the last use. IsKill will be unset if reg is reused
1840 // unless it's a two-address operand.
1841 if (!MI.isRegTiedToDefOperand(i) &&
1842 KilledMIRegs.count(VirtReg) == 0) {
1843 MI.getOperand(i).setIsKill();
1844 KilledMIRegs.insert(VirtReg);
1845 }
1846
Evan Cheng427a6b62009-05-15 06:48:19 +00001847 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001848 DOUT << '\t' << *prior(MII);
1849 }
1850 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1851 MI.getOperand(i).setReg(RReg);
1852 MI.getOperand(i).setSubReg(0);
1853 }
1854
1855 // Ok - now we can remove stores that have been confirmed dead.
1856 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1857 // This was the last use and the spilled value is still available
1858 // for reuse. That means the spill was unnecessary!
1859 int PDSSlot = PotentialDeadStoreSlots[j];
1860 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1861 if (DeadStore) {
1862 DOUT << "Removed dead store:\t" << *DeadStore;
Evan Cheng427a6b62009-05-15 06:48:19 +00001863 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001864 VRM.RemoveMachineInstrFromMaps(DeadStore);
1865 MBB.erase(DeadStore);
1866 MaybeDeadStores[PDSSlot] = NULL;
1867 ++NumDSE;
1868 }
1869 }
1870
1871
1872 DOUT << '\t' << MI;
1873
1874
1875 // If we have folded references to memory operands, make sure we clear all
1876 // physical registers that may contain the value of the spilled virtual
1877 // register
1878 SmallSet<int, 2> FoldedSS;
1879 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1880 unsigned VirtReg = I->second.first;
1881 VirtRegMap::ModRef MR = I->second.second;
1882 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR;
1883
1884 // MI2VirtMap be can updated which invalidate the iterator.
1885 // Increment the iterator first.
1886 ++I;
1887 int SS = VRM.getStackSlot(VirtReg);
1888 if (SS == VirtRegMap::NO_STACK_SLOT)
1889 continue;
1890 FoldedSS.insert(SS);
1891 DOUT << " - StackSlot: " << SS << "\n";
1892
1893 // If this folded instruction is just a use, check to see if it's a
1894 // straight load from the virt reg slot.
1895 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1896 int FrameIdx;
1897 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1898 if (DestReg && FrameIdx == SS) {
1899 // If this spill slot is available, turn it into a copy (or nothing)
1900 // instead of leaving it as a load!
1901 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1902 DOUT << "Promoted Load To Copy: " << MI;
1903 if (DestReg != InReg) {
1904 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1905 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1906 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1907 unsigned SubIdx = DefMO->getSubReg();
1908 // Revisit the copy so we make sure to notice the effects of the
1909 // operation on the destreg (either needing to RA it if it's
1910 // virtual or needing to clobber any values if it's physical).
1911 NextMII = &MI;
1912 --NextMII; // backtrack to the copy.
1913 // Propagate the sub-register index over.
1914 if (SubIdx) {
1915 DefMO = NextMII->findRegisterDefOperand(DestReg);
1916 DefMO->setSubReg(SubIdx);
1917 }
1918
1919 // Mark is killed.
1920 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1921 KillOpnd->setIsKill();
1922
1923 BackTracked = true;
1924 } else {
1925 DOUT << "Removing now-noop copy: " << MI;
1926 // Unset last kill since it's being reused.
Evan Cheng427a6b62009-05-15 06:48:19 +00001927 InvalidateKill(InReg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001928 Spills.disallowClobberPhysReg(InReg);
1929 }
1930
Evan Cheng427a6b62009-05-15 06:48:19 +00001931 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001932 VRM.RemoveMachineInstrFromMaps(&MI);
1933 MBB.erase(&MI);
1934 Erased = true;
1935 goto ProcessNextInst;
1936 }
1937 } else {
1938 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1939 SmallVector<MachineInstr*, 4> NewMIs;
1940 if (PhysReg &&
1941 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1942 MBB.insert(MII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00001943 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001944 VRM.RemoveMachineInstrFromMaps(&MI);
1945 MBB.erase(&MI);
1946 Erased = true;
1947 --NextMII; // backtrack to the unfolded instruction.
1948 BackTracked = true;
1949 goto ProcessNextInst;
1950 }
1951 }
1952 }
1953
1954 // If this reference is not a use, any previous store is now dead.
1955 // Otherwise, the store to this stack slot is not dead anymore.
1956 MachineInstr* DeadStore = MaybeDeadStores[SS];
1957 if (DeadStore) {
1958 bool isDead = !(MR & VirtRegMap::isRef);
1959 MachineInstr *NewStore = NULL;
1960 if (MR & VirtRegMap::isModRef) {
1961 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1962 SmallVector<MachineInstr*, 4> NewMIs;
1963 // We can reuse this physreg as long as we are allowed to clobber
1964 // the value and there isn't an earlier def that has already clobbered
1965 // the physreg.
1966 if (PhysReg &&
1967 !ReusedOperands.isClobbered(PhysReg) &&
1968 Spills.canClobberPhysReg(PhysReg) &&
1969 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1970 MachineOperand *KillOpnd =
1971 DeadStore->findRegisterUseOperand(PhysReg, true);
1972 // Note, if the store is storing a sub-register, it's possible the
1973 // super-register is needed below.
1974 if (KillOpnd && !KillOpnd->getSubReg() &&
1975 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1976 MBB.insert(MII, NewMIs[0]);
1977 NewStore = NewMIs[1];
1978 MBB.insert(MII, NewStore);
1979 VRM.addSpillSlotUse(SS, NewStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00001980 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001981 VRM.RemoveMachineInstrFromMaps(&MI);
1982 MBB.erase(&MI);
1983 Erased = true;
1984 --NextMII;
1985 --NextMII; // backtrack to the unfolded instruction.
1986 BackTracked = true;
1987 isDead = true;
1988 ++NumSUnfold;
1989 }
1990 }
1991 }
1992
1993 if (isDead) { // Previous store is dead.
1994 // If we get here, the store is dead, nuke it now.
1995 DOUT << "Removed dead store:\t" << *DeadStore;
Evan Cheng427a6b62009-05-15 06:48:19 +00001996 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001997 VRM.RemoveMachineInstrFromMaps(DeadStore);
1998 MBB.erase(DeadStore);
1999 if (!NewStore)
2000 ++NumDSE;
2001 }
2002
2003 MaybeDeadStores[SS] = NULL;
2004 if (NewStore) {
2005 // Treat this store as a spill merged into a copy. That makes the
2006 // stack slot value available.
2007 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2008 goto ProcessNextInst;
2009 }
2010 }
2011
2012 // If the spill slot value is available, and this is a new definition of
2013 // the value, the value is not available anymore.
2014 if (MR & VirtRegMap::isMod) {
2015 // Notice that the value in this stack slot has been modified.
2016 Spills.ModifyStackSlotOrReMat(SS);
2017
2018 // If this is *just* a mod of the value, check to see if this is just a
2019 // store to the spill slot (i.e. the spill got merged into the copy). If
2020 // so, realize that the vreg is available now, and add the store to the
2021 // MaybeDeadStore info.
2022 int StackSlot;
2023 if (!(MR & VirtRegMap::isRef)) {
2024 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2025 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2026 "Src hasn't been allocated yet?");
2027
2028 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2029 Spills, RegKills, KillOps, TRI, VRM)) {
2030 NextMII = next(MII);
2031 BackTracked = true;
2032 goto ProcessNextInst;
2033 }
2034
2035 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2036 // this as a potentially dead store in case there is a subsequent
2037 // store into the stack slot without a read from it.
2038 MaybeDeadStores[StackSlot] = &MI;
2039
2040 // If the stack slot value was previously available in some other
2041 // register, change it now. Otherwise, make the register
2042 // available in PhysReg.
2043 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2044 }
2045 }
2046 }
2047 }
2048
2049 // Process all of the spilled defs.
2050 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2051 MachineOperand &MO = MI.getOperand(i);
2052 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2053 continue;
2054
2055 unsigned VirtReg = MO.getReg();
2056 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2057 // Check to see if this is a noop copy. If so, eliminate the
2058 // instruction before considering the dest reg to be changed.
Evan Cheng2578ba22009-07-01 01:59:31 +00002059 // Also check if it's copying from an "undef", if so, we can't
2060 // eliminate this or else the undef marker is lost and it will
2061 // confuses the scavenger. This is extremely rare.
Lang Hames87e3bca2009-05-06 02:36:21 +00002062 unsigned Src, Dst, SrcSR, DstSR;
Evan Cheng2578ba22009-07-01 01:59:31 +00002063 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2064 !MI.findRegisterUseOperand(Src)->isUndef()) {
Lang Hames87e3bca2009-05-06 02:36:21 +00002065 ++NumDCE;
2066 DOUT << "Removing now-noop copy: " << MI;
2067 SmallVector<unsigned, 2> KillRegs;
Evan Cheng427a6b62009-05-15 06:48:19 +00002068 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
Lang Hames87e3bca2009-05-06 02:36:21 +00002069 if (MO.isDead() && !KillRegs.empty()) {
2070 // Source register or an implicit super/sub-register use is killed.
2071 assert(KillRegs[0] == Dst ||
2072 TRI->isSubRegister(KillRegs[0], Dst) ||
2073 TRI->isSuperRegister(KillRegs[0], Dst));
2074 // Last def is now dead.
Evan Chengeca24fb2009-05-12 23:07:00 +00002075 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002076 }
2077 VRM.RemoveMachineInstrFromMaps(&MI);
2078 MBB.erase(&MI);
2079 Erased = true;
2080 Spills.disallowClobberPhysReg(VirtReg);
2081 goto ProcessNextInst;
2082 }
Evan Cheng2578ba22009-07-01 01:59:31 +00002083
Lang Hames87e3bca2009-05-06 02:36:21 +00002084 // If it's not a no-op copy, it clobbers the value in the destreg.
2085 Spills.ClobberPhysReg(VirtReg);
2086 ReusedOperands.markClobbered(VirtReg);
2087
2088 // Check to see if this instruction is a load from a stack slot into
2089 // a register. If so, this provides the stack slot value in the reg.
2090 int FrameIdx;
2091 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2092 assert(DestReg == VirtReg && "Unknown load situation!");
2093
2094 // If it is a folded reference, then it's not safe to clobber.
2095 bool Folded = FoldedSS.count(FrameIdx);
2096 // Otherwise, if it wasn't available, remember that it is now!
2097 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2098 goto ProcessNextInst;
2099 }
2100
2101 continue;
2102 }
2103
2104 unsigned SubIdx = MO.getSubReg();
2105 bool DoReMat = VRM.isReMaterialized(VirtReg);
2106 if (DoReMat)
2107 ReMatDefs.insert(&MI);
2108
2109 // The only vregs left are stack slot definitions.
2110 int StackSlot = VRM.getStackSlot(VirtReg);
2111 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2112
2113 // If this def is part of a two-address operand, make sure to execute
2114 // the store from the correct physical register.
2115 unsigned PhysReg;
2116 unsigned TiedOp;
2117 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2118 PhysReg = MI.getOperand(TiedOp).getReg();
2119 if (SubIdx) {
2120 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2121 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2122 "Can't find corresponding super-register!");
2123 PhysReg = SuperReg;
2124 }
2125 } else {
2126 PhysReg = VRM.getPhys(VirtReg);
2127 if (ReusedOperands.isClobbered(PhysReg)) {
2128 // Another def has taken the assigned physreg. It must have been a
2129 // use&def which got it due to reuse. Undo the reuse!
2130 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
2131 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2132 }
2133 }
2134
2135 assert(PhysReg && "VR not assigned a physical register?");
2136 RegInfo->setPhysRegUsed(PhysReg);
2137 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2138 ReusedOperands.markClobbered(RReg);
2139 MI.getOperand(i).setReg(RReg);
2140 MI.getOperand(i).setSubReg(0);
2141
2142 if (!MO.isDead()) {
2143 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2144 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2145 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2146 NextMII = next(MII);
2147
2148 // Check to see if this is a noop copy. If so, eliminate the
2149 // instruction before considering the dest reg to be changed.
2150 {
2151 unsigned Src, Dst, SrcSR, DstSR;
2152 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2153 ++NumDCE;
2154 DOUT << "Removing now-noop copy: " << MI;
Evan Cheng427a6b62009-05-15 06:48:19 +00002155 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002156 VRM.RemoveMachineInstrFromMaps(&MI);
2157 MBB.erase(&MI);
2158 Erased = true;
Evan Cheng427a6b62009-05-15 06:48:19 +00002159 UpdateKills(*LastStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002160 goto ProcessNextInst;
2161 }
2162 }
2163 }
2164 }
2165 ProcessNextInst:
2166 DistanceMap.insert(std::make_pair(&MI, Dist++));
2167 if (!Erased && !BackTracked) {
2168 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
Evan Cheng427a6b62009-05-15 06:48:19 +00002169 UpdateKills(*II, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002170 }
2171 MII = NextMII;
2172 }
2173
2174 }
2175
2176};
2177
2178llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2179 switch (RewriterOpt) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002180 default: llvm_unreachable("Unreachable!");
Lang Hames87e3bca2009-05-06 02:36:21 +00002181 case local:
2182 return new LocalRewriter();
Lang Hamesf41538d2009-06-02 16:53:25 +00002183 case trivial:
2184 return new TrivialRewriter();
Lang Hames87e3bca2009-05-06 02:36:21 +00002185 }
2186}