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