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