blob: 48558fe74fca76664dd0e1f29ae057d8802108cc [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);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000359 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000360 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);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000393 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
394 continue;
395 if (MO.getReg() == Reg)
396 DefOp = &MO;
397 else if (!MO.isDead())
398 HasLiveDef = true;
Lang Hames87e3bca2009-05-06 02:36:21 +0000399 }
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);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000433 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000434 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
Evan Cheng261ce1d2009-07-10 19:15:51 +00001160 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1161 /// where SrcReg is r1 and it is tied to r0. Return true if after
1162 /// commuting this instruction it will be r0 = op r2, r1.
1163 static bool CommuteChangesDestination(MachineInstr *DefMI,
1164 const TargetInstrDesc &TID,
1165 unsigned SrcReg,
1166 const TargetInstrInfo *TII,
1167 unsigned &DstIdx) {
1168 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1169 return false;
1170 if (!DefMI->getOperand(1).isReg() ||
1171 DefMI->getOperand(1).getReg() != SrcReg)
1172 return false;
1173 unsigned DefIdx;
1174 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1175 return false;
1176 unsigned SrcIdx1, SrcIdx2;
1177 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1178 return false;
1179 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1180 DstIdx = 2;
1181 return true;
1182 }
1183 return false;
1184 }
1185
Lang Hames87e3bca2009-05-06 02:36:21 +00001186 /// CommuteToFoldReload -
1187 /// Look for
1188 /// r1 = load fi#1
1189 /// r1 = op r1, r2<kill>
1190 /// store r1, fi#1
1191 ///
1192 /// If op is commutable and r2 is killed, then we can xform these to
1193 /// r2 = op r2, fi#1
1194 /// store r2, fi#1
1195 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1196 MachineBasicBlock::iterator &MII,
1197 unsigned VirtReg, unsigned SrcReg, int SS,
1198 AvailableSpills &Spills,
1199 BitVector &RegKills,
1200 std::vector<MachineOperand*> &KillOps,
1201 const TargetRegisterInfo *TRI,
1202 VirtRegMap &VRM) {
1203 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1204 return false;
1205
1206 MachineFunction &MF = *MBB.getParent();
1207 MachineInstr &MI = *MII;
1208 MachineBasicBlock::iterator DefMII = prior(MII);
1209 MachineInstr *DefMI = DefMII;
1210 const TargetInstrDesc &TID = DefMI->getDesc();
1211 unsigned NewDstIdx;
1212 if (DefMII != MBB.begin() &&
1213 TID.isCommutable() &&
Evan Cheng261ce1d2009-07-10 19:15:51 +00001214 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001215 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1216 unsigned NewReg = NewDstMO.getReg();
1217 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1218 return false;
1219 MachineInstr *ReloadMI = prior(DefMII);
1220 int FrameIdx;
1221 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1222 if (DestReg != SrcReg || FrameIdx != SS)
1223 return false;
1224 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1225 if (UseIdx == -1)
1226 return false;
1227 unsigned DefIdx;
1228 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1229 return false;
1230 assert(DefMI->getOperand(DefIdx).isReg() &&
1231 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1232
1233 // Now commute def instruction.
1234 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1235 if (!CommutedMI)
1236 return false;
1237 SmallVector<unsigned, 1> Ops;
1238 Ops.push_back(NewDstIdx);
1239 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1240 // Not needed since foldMemoryOperand returns new MI.
1241 MF.DeleteMachineInstr(CommutedMI);
1242 if (!FoldedMI)
1243 return false;
1244
1245 VRM.addSpillSlotUse(SS, FoldedMI);
1246 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1247 // Insert new def MI and spill MI.
1248 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1249 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1250 MII = prior(MII);
1251 MachineInstr *StoreMI = MII;
1252 VRM.addSpillSlotUse(SS, StoreMI);
1253 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1254 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1255
1256 // Delete all 3 old instructions.
Evan Cheng427a6b62009-05-15 06:48:19 +00001257 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001258 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1259 MBB.erase(ReloadMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001260 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001261 VRM.RemoveMachineInstrFromMaps(DefMI);
1262 MBB.erase(DefMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001263 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001264 VRM.RemoveMachineInstrFromMaps(&MI);
1265 MBB.erase(&MI);
1266
1267 // If NewReg was previously holding value of some SS, it's now clobbered.
1268 // This has to be done now because it's a physical register. When this
1269 // instruction is re-visited, it's ignored.
1270 Spills.ClobberPhysReg(NewReg);
1271
1272 ++NumCommutes;
1273 return true;
1274 }
1275
1276 return false;
1277 }
1278
1279 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1280 /// the last store to the same slot is now dead. If so, remove the last store.
1281 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1282 MachineBasicBlock::iterator &MII,
1283 int Idx, unsigned PhysReg, int StackSlot,
1284 const TargetRegisterClass *RC,
1285 bool isAvailable, MachineInstr *&LastStore,
1286 AvailableSpills &Spills,
1287 SmallSet<MachineInstr*, 4> &ReMatDefs,
1288 BitVector &RegKills,
1289 std::vector<MachineOperand*> &KillOps,
1290 VirtRegMap &VRM) {
1291
1292 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
1293 MachineInstr *StoreMI = next(MII);
1294 VRM.addSpillSlotUse(StackSlot, StoreMI);
1295 DOUT << "Store:\t" << *StoreMI;
1296
1297 // If there is a dead store to this stack slot, nuke it now.
1298 if (LastStore) {
1299 DOUT << "Removed dead store:\t" << *LastStore;
1300 ++NumDSE;
1301 SmallVector<unsigned, 2> KillRegs;
Evan Cheng427a6b62009-05-15 06:48:19 +00001302 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
Lang Hames87e3bca2009-05-06 02:36:21 +00001303 MachineBasicBlock::iterator PrevMII = LastStore;
1304 bool CheckDef = PrevMII != MBB.begin();
1305 if (CheckDef)
1306 --PrevMII;
1307 VRM.RemoveMachineInstrFromMaps(LastStore);
1308 MBB.erase(LastStore);
1309 if (CheckDef) {
1310 // Look at defs of killed registers on the store. Mark the defs
1311 // as dead since the store has been deleted and they aren't
1312 // being reused.
1313 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1314 bool HasOtherDef = false;
1315 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1316 MachineInstr *DeadDef = PrevMII;
1317 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
Evan Cheng4784f1f2009-06-30 08:49:04 +00001318 // FIXME: This assumes a remat def does not have side effects.
Lang Hames87e3bca2009-05-06 02:36:21 +00001319 VRM.RemoveMachineInstrFromMaps(DeadDef);
1320 MBB.erase(DeadDef);
1321 ++NumDRM;
1322 }
1323 }
1324 }
1325 }
1326 }
1327
1328 LastStore = next(MII);
1329
1330 // If the stack slot value was previously available in some other
1331 // register, change it now. Otherwise, make the register available,
1332 // in PhysReg.
1333 Spills.ModifyStackSlotOrReMat(StackSlot);
1334 Spills.ClobberPhysReg(PhysReg);
1335 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1336 ++NumStores;
1337 }
1338
1339 /// TransferDeadness - A identity copy definition is dead and it's being
1340 /// removed. Find the last def or use and mark it as dead / kill.
1341 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1342 unsigned Reg, BitVector &RegKills,
Evan Chengeca24fb2009-05-12 23:07:00 +00001343 std::vector<MachineOperand*> &KillOps,
1344 VirtRegMap &VRM) {
1345 SmallPtrSet<MachineInstr*, 4> Seens;
1346 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
Lang Hames87e3bca2009-05-06 02:36:21 +00001347 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1348 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1349 MachineInstr *UDMI = &*RI;
1350 if (UDMI->getParent() != MBB)
1351 continue;
1352 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1353 if (DI == DistanceMap.end() || DI->second > CurDist)
1354 continue;
Evan Chengeca24fb2009-05-12 23:07:00 +00001355 if (Seens.insert(UDMI))
1356 Refs.push_back(std::make_pair(UDMI, DI->second));
Lang Hames87e3bca2009-05-06 02:36:21 +00001357 }
1358
Evan Chengeca24fb2009-05-12 23:07:00 +00001359 if (Refs.empty())
1360 return;
1361 std::sort(Refs.begin(), Refs.end(), RefSorter());
1362
1363 while (!Refs.empty()) {
1364 MachineInstr *LastUDMI = Refs.back().first;
1365 Refs.pop_back();
1366
Lang Hames87e3bca2009-05-06 02:36:21 +00001367 MachineOperand *LastUD = NULL;
1368 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1369 MachineOperand &MO = LastUDMI->getOperand(i);
1370 if (!MO.isReg() || MO.getReg() != Reg)
1371 continue;
1372 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1373 LastUD = &MO;
1374 if (LastUDMI->isRegTiedToDefOperand(i))
Evan Chengeca24fb2009-05-12 23:07:00 +00001375 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001376 }
Evan Chengeca24fb2009-05-12 23:07:00 +00001377 if (LastUD->isDef()) {
1378 // If the instruction has no side effect, delete it and propagate
1379 // backward further. Otherwise, mark is dead and we are done.
1380 const TargetInstrDesc &TID = LastUDMI->getDesc();
1381 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1382 TID.hasUnmodeledSideEffects()) {
1383 LastUD->setIsDead();
1384 break;
1385 }
1386 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1387 MBB->erase(LastUDMI);
1388 } else {
Lang Hames87e3bca2009-05-06 02:36:21 +00001389 LastUD->setIsKill();
1390 RegKills.set(Reg);
1391 KillOps[Reg] = LastUD;
Evan Chengeca24fb2009-05-12 23:07:00 +00001392 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001393 }
1394 }
1395 }
1396
1397 /// rewriteMBB - Keep track of which spills are available even after the
1398 /// register allocator is done with them. If possible, avid reloading vregs.
1399 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1400 LiveIntervals *LIs,
1401 AvailableSpills &Spills, BitVector &RegKills,
1402 std::vector<MachineOperand*> &KillOps) {
1403
1404 DOUT << "\n**** Local spiller rewriting MBB '"
1405 << MBB.getBasicBlock()->getName() << "':\n";
1406
1407 MachineFunction &MF = *MBB.getParent();
1408
1409 // MaybeDeadStores - When we need to write a value back into a stack slot,
1410 // keep track of the inserted store. If the stack slot value is never read
1411 // (because the value was used from some available register, for example), and
1412 // subsequently stored to, the original store is dead. This map keeps track
1413 // of inserted stores that are not used. If we see a subsequent store to the
1414 // same stack slot, the original store is deleted.
1415 std::vector<MachineInstr*> MaybeDeadStores;
1416 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1417
1418 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1419 SmallSet<MachineInstr*, 4> ReMatDefs;
1420
1421 // Clear kill info.
1422 SmallSet<unsigned, 2> KilledMIRegs;
1423 RegKills.reset();
1424 KillOps.clear();
1425 KillOps.resize(TRI->getNumRegs(), NULL);
1426
1427 unsigned Dist = 0;
1428 DistanceMap.clear();
1429 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1430 MII != E; ) {
1431 MachineBasicBlock::iterator NextMII = next(MII);
1432
1433 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1434 bool Erased = false;
1435 bool BackTracked = false;
1436 if (OptimizeByUnfold(MBB, MII,
1437 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1438 NextMII = next(MII);
1439
1440 MachineInstr &MI = *MII;
1441
1442 if (VRM.hasEmergencySpills(&MI)) {
1443 // Spill physical register(s) in the rare case the allocator has run out
1444 // of registers to allocate.
1445 SmallSet<int, 4> UsedSS;
1446 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1447 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1448 unsigned PhysReg = EmSpills[i];
1449 const TargetRegisterClass *RC =
1450 TRI->getPhysicalRegisterRegClass(PhysReg);
1451 assert(RC && "Unable to determine register class!");
1452 int SS = VRM.getEmergencySpillSlot(RC);
1453 if (UsedSS.count(SS))
1454 assert(0 && "Need to spill more than one physical registers!");
1455 UsedSS.insert(SS);
1456 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1457 MachineInstr *StoreMI = prior(MII);
1458 VRM.addSpillSlotUse(SS, StoreMI);
1459 TII->loadRegFromStackSlot(MBB, next(MII), PhysReg, SS, RC);
1460 MachineInstr *LoadMI = next(MII);
1461 VRM.addSpillSlotUse(SS, LoadMI);
1462 ++NumPSpills;
1463 }
1464 NextMII = next(MII);
1465 }
1466
1467 // Insert restores here if asked to.
1468 if (VRM.isRestorePt(&MI)) {
1469 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1470 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1471 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1472 if (!VRM.getPreSplitReg(VirtReg))
1473 continue; // Split interval spilled again.
1474 unsigned Phys = VRM.getPhys(VirtReg);
1475 RegInfo->setPhysRegUsed(Phys);
1476
1477 // Check if the value being restored if available. If so, it must be
1478 // from a predecessor BB that fallthrough into this BB. We do not
1479 // expect:
1480 // BB1:
1481 // r1 = load fi#1
1482 // ...
1483 // = r1<kill>
1484 // ... # r1 not clobbered
1485 // ...
1486 // = load fi#1
1487 bool DoReMat = VRM.isReMaterialized(VirtReg);
1488 int SSorRMId = DoReMat
1489 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1490 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1491 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1492 if (InReg == Phys) {
1493 // If the value is already available in the expected register, save
1494 // a reload / remat.
1495 if (SSorRMId)
1496 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1497 else
1498 DOUT << "Reusing SS#" << SSorRMId;
1499 DOUT << " from physreg "
1500 << TRI->getName(InReg) << " for vreg"
1501 << VirtReg <<" instead of reloading into physreg "
1502 << TRI->getName(Phys) << "\n";
1503 ++NumOmitted;
1504 continue;
1505 } else if (InReg && InReg != Phys) {
1506 if (SSorRMId)
1507 DOUT << "Reusing RM#" << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1;
1508 else
1509 DOUT << "Reusing SS#" << SSorRMId;
1510 DOUT << " from physreg "
1511 << TRI->getName(InReg) << " for vreg"
1512 << VirtReg <<" by copying it into physreg "
1513 << TRI->getName(Phys) << "\n";
1514
1515 // If the reloaded / remat value is available in another register,
1516 // copy it to the desired register.
1517 TII->copyRegToReg(MBB, &MI, Phys, InReg, RC, RC);
1518
1519 // This invalidates Phys.
1520 Spills.ClobberPhysReg(Phys);
1521 // Remember it's available.
1522 Spills.addAvailable(SSorRMId, Phys);
1523
1524 // Mark is killed.
1525 MachineInstr *CopyMI = prior(MII);
1526 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1527 KillOpnd->setIsKill();
Evan Cheng427a6b62009-05-15 06:48:19 +00001528 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001529
1530 DOUT << '\t' << *CopyMI;
1531 ++NumCopified;
1532 continue;
1533 }
1534
1535 if (VRM.isReMaterialized(VirtReg)) {
1536 ReMaterialize(MBB, MII, Phys, VirtReg, TII, TRI, VRM);
1537 } else {
1538 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1539 TII->loadRegFromStackSlot(MBB, &MI, Phys, SSorRMId, RC);
1540 MachineInstr *LoadMI = prior(MII);
1541 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1542 ++NumLoads;
1543 }
1544
1545 // This invalidates Phys.
1546 Spills.ClobberPhysReg(Phys);
1547 // Remember it's available.
1548 Spills.addAvailable(SSorRMId, Phys);
1549
Evan Cheng427a6b62009-05-15 06:48:19 +00001550 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001551 DOUT << '\t' << *prior(MII);
1552 }
1553 }
1554
1555 // Insert spills here if asked to.
1556 if (VRM.isSpillPt(&MI)) {
1557 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1558 VRM.getSpillPtSpills(&MI);
1559 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1560 unsigned VirtReg = SpillRegs[i].first;
1561 bool isKill = SpillRegs[i].second;
1562 if (!VRM.getPreSplitReg(VirtReg))
1563 continue; // Split interval spilled again.
1564 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1565 unsigned Phys = VRM.getPhys(VirtReg);
1566 int StackSlot = VRM.getStackSlot(VirtReg);
1567 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
1568 MachineInstr *StoreMI = next(MII);
1569 VRM.addSpillSlotUse(StackSlot, StoreMI);
1570 DOUT << "Store:\t" << *StoreMI;
1571 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1572 }
1573 NextMII = next(MII);
1574 }
1575
1576 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1577 /// reuse.
1578 ReuseInfo ReusedOperands(MI, TRI);
1579 SmallVector<unsigned, 4> VirtUseOps;
1580 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1581 MachineOperand &MO = MI.getOperand(i);
1582 if (!MO.isReg() || MO.getReg() == 0)
1583 continue; // Ignore non-register operands.
1584
1585 unsigned VirtReg = MO.getReg();
1586 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1587 // Ignore physregs for spilling, but remember that it is used by this
1588 // function.
1589 RegInfo->setPhysRegUsed(VirtReg);
1590 continue;
1591 }
1592
1593 // We want to process implicit virtual register uses first.
1594 if (MO.isImplicit())
1595 // If the virtual register is implicitly defined, emit a implicit_def
1596 // before so scavenger knows it's "defined".
Evan Cheng4784f1f2009-06-30 08:49:04 +00001597 // FIXME: This is a horrible hack done the by register allocator to
1598 // remat a definition with virtual register operand.
Lang Hames87e3bca2009-05-06 02:36:21 +00001599 VirtUseOps.insert(VirtUseOps.begin(), i);
1600 else
1601 VirtUseOps.push_back(i);
1602 }
1603
1604 // Process all of the spilled uses and all non spilled reg references.
1605 SmallVector<int, 2> PotentialDeadStoreSlots;
1606 KilledMIRegs.clear();
1607 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1608 unsigned i = VirtUseOps[j];
1609 MachineOperand &MO = MI.getOperand(i);
1610 unsigned VirtReg = MO.getReg();
1611 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1612 "Not a virtual register?");
1613
1614 unsigned SubIdx = MO.getSubReg();
1615 if (VRM.isAssignedReg(VirtReg)) {
1616 // This virtual register was assigned a physreg!
1617 unsigned Phys = VRM.getPhys(VirtReg);
1618 RegInfo->setPhysRegUsed(Phys);
1619 if (MO.isDef())
1620 ReusedOperands.markClobbered(Phys);
1621 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1622 MI.getOperand(i).setReg(RReg);
1623 MI.getOperand(i).setSubReg(0);
1624 if (VRM.isImplicitlyDefined(VirtReg))
Evan Cheng4784f1f2009-06-30 08:49:04 +00001625 // FIXME: Is this needed?
Lang Hames87e3bca2009-05-06 02:36:21 +00001626 BuildMI(MBB, &MI, MI.getDebugLoc(),
1627 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1628 continue;
1629 }
1630
1631 // This virtual register is now known to be a spilled value.
1632 if (!MO.isUse())
1633 continue; // Handle defs in the loop below (handle use&def here though)
1634
Evan Cheng4784f1f2009-06-30 08:49:04 +00001635 bool AvoidReload = MO.isUndef();
1636 // Check if it is defined by an implicit def. It should not be spilled.
1637 // Note, this is for correctness reason. e.g.
1638 // 8 %reg1024<def> = IMPLICIT_DEF
1639 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1640 // The live range [12, 14) are not part of the r1024 live interval since
1641 // it's defined by an implicit def. It will not conflicts with live
1642 // interval of r1025. Now suppose both registers are spilled, you can
1643 // easily see a situation where both registers are reloaded before
1644 // the INSERT_SUBREG and both target registers that would overlap.
Lang Hames87e3bca2009-05-06 02:36:21 +00001645 bool DoReMat = VRM.isReMaterialized(VirtReg);
1646 int SSorRMId = DoReMat
1647 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1648 int ReuseSlot = SSorRMId;
1649
1650 // Check to see if this stack slot is available.
1651 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1652
1653 // If this is a sub-register use, make sure the reuse register is in the
1654 // right register class. For example, for x86 not all of the 32-bit
1655 // registers have accessible sub-registers.
1656 // Similarly so for EXTRACT_SUBREG. Consider this:
1657 // EDI = op
1658 // MOV32_mr fi#1, EDI
1659 // ...
1660 // = EXTRACT_SUBREG fi#1
1661 // fi#1 is available in EDI, but it cannot be reused because it's not in
1662 // the right register file.
1663 if (PhysReg && !AvoidReload &&
1664 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1665 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1666 if (!RC->contains(PhysReg))
1667 PhysReg = 0;
1668 }
1669
1670 if (PhysReg && !AvoidReload) {
1671 // This spilled operand might be part of a two-address operand. If this
1672 // is the case, then changing it will necessarily require changing the
1673 // def part of the instruction as well. However, in some cases, we
1674 // aren't allowed to modify the reused register. If none of these cases
1675 // apply, reuse it.
1676 bool CanReuse = true;
1677 bool isTied = MI.isRegTiedToDefOperand(i);
1678 if (isTied) {
1679 // Okay, we have a two address operand. We can reuse this physreg as
1680 // long as we are allowed to clobber the value and there isn't an
1681 // earlier def that has already clobbered the physreg.
1682 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1683 Spills.canClobberPhysReg(PhysReg);
1684 }
1685
1686 if (CanReuse) {
1687 // If this stack slot value is already available, reuse it!
1688 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1689 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1690 else
1691 DOUT << "Reusing SS#" << ReuseSlot;
1692 DOUT << " from physreg "
1693 << TRI->getName(PhysReg) << " for vreg"
1694 << VirtReg <<" instead of reloading into physreg "
1695 << TRI->getName(VRM.getPhys(VirtReg)) << "\n";
1696 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1697 MI.getOperand(i).setReg(RReg);
1698 MI.getOperand(i).setSubReg(0);
1699
1700 // The only technical detail we have is that we don't know that
1701 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1702 // later in the instruction. In particular, consider 'op V1, V2'.
1703 // If V1 is available in physreg R0, we would choose to reuse it
1704 // here, instead of reloading it into the register the allocator
1705 // indicated (say R1). However, V2 might have to be reloaded
1706 // later, and it might indicate that it needs to live in R0. When
1707 // this occurs, we need to have information available that
1708 // indicates it is safe to use R1 for the reload instead of R0.
1709 //
1710 // To further complicate matters, we might conflict with an alias,
1711 // or R0 and R1 might not be compatible with each other. In this
1712 // case, we actually insert a reload for V1 in R1, ensuring that
1713 // we can get at R0 or its alias.
1714 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1715 VRM.getPhys(VirtReg), VirtReg);
1716 if (isTied)
1717 // Only mark it clobbered if this is a use&def operand.
1718 ReusedOperands.markClobbered(PhysReg);
1719 ++NumReused;
1720
1721 if (MI.getOperand(i).isKill() &&
1722 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1723
1724 // The store of this spilled value is potentially dead, but we
1725 // won't know for certain until we've confirmed that the re-use
1726 // above is valid, which means waiting until the other operands
1727 // are processed. For now we just track the spill slot, we'll
1728 // remove it after the other operands are processed if valid.
1729
1730 PotentialDeadStoreSlots.push_back(ReuseSlot);
1731 }
1732
1733 // Mark is isKill if it's there no other uses of the same virtual
1734 // register and it's not a two-address operand. IsKill will be
1735 // unset if reg is reused.
1736 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1737 MI.getOperand(i).setIsKill();
1738 KilledMIRegs.insert(VirtReg);
1739 }
1740
1741 continue;
1742 } // CanReuse
1743
1744 // Otherwise we have a situation where we have a two-address instruction
1745 // whose mod/ref operand needs to be reloaded. This reload is already
1746 // available in some register "PhysReg", but if we used PhysReg as the
1747 // operand to our 2-addr instruction, the instruction would modify
1748 // PhysReg. This isn't cool if something later uses PhysReg and expects
1749 // to get its initial value.
1750 //
1751 // To avoid this problem, and to avoid doing a load right after a store,
1752 // we emit a copy from PhysReg into the designated register for this
1753 // operand.
1754 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1755 assert(DesignatedReg && "Must map virtreg to physreg!");
1756
1757 // Note that, if we reused a register for a previous operand, the
1758 // register we want to reload into might not actually be
1759 // available. If this occurs, use the register indicated by the
1760 // reuser.
1761 if (ReusedOperands.hasReuses())
1762 DesignatedReg = ReusedOperands.GetRegForReload(DesignatedReg, &MI,
1763 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1764
1765 // If the mapped designated register is actually the physreg we have
1766 // incoming, we don't need to inserted a dead copy.
1767 if (DesignatedReg == PhysReg) {
1768 // If this stack slot value is already available, reuse it!
1769 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
1770 DOUT << "Reusing RM#" << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1;
1771 else
1772 DOUT << "Reusing SS#" << ReuseSlot;
1773 DOUT << " from physreg " << TRI->getName(PhysReg)
1774 << " for vreg" << VirtReg
1775 << " instead of reloading into same physreg.\n";
1776 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1777 MI.getOperand(i).setReg(RReg);
1778 MI.getOperand(i).setSubReg(0);
1779 ReusedOperands.markClobbered(RReg);
1780 ++NumReused;
1781 continue;
1782 }
1783
1784 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1785 RegInfo->setPhysRegUsed(DesignatedReg);
1786 ReusedOperands.markClobbered(DesignatedReg);
1787 TII->copyRegToReg(MBB, &MI, DesignatedReg, PhysReg, RC, RC);
1788
1789 MachineInstr *CopyMI = prior(MII);
Evan Cheng427a6b62009-05-15 06:48:19 +00001790 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001791
1792 // This invalidates DesignatedReg.
1793 Spills.ClobberPhysReg(DesignatedReg);
1794
1795 Spills.addAvailable(ReuseSlot, DesignatedReg);
1796 unsigned RReg =
1797 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
1798 MI.getOperand(i).setReg(RReg);
1799 MI.getOperand(i).setSubReg(0);
1800 DOUT << '\t' << *prior(MII);
1801 ++NumReused;
1802 continue;
1803 } // if (PhysReg)
1804
1805 // Otherwise, reload it and remember that we have it.
1806 PhysReg = VRM.getPhys(VirtReg);
1807 assert(PhysReg && "Must map virtreg to physreg!");
1808
1809 // Note that, if we reused a register for a previous operand, the
1810 // register we want to reload into might not actually be
1811 // available. If this occurs, use the register indicated by the
1812 // reuser.
1813 if (ReusedOperands.hasReuses())
1814 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
1815 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
1816
1817 RegInfo->setPhysRegUsed(PhysReg);
1818 ReusedOperands.markClobbered(PhysReg);
1819 if (AvoidReload)
1820 ++NumAvoided;
1821 else {
1822 if (DoReMat) {
1823 ReMaterialize(MBB, MII, PhysReg, VirtReg, TII, TRI, VRM);
1824 } else {
1825 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1826 TII->loadRegFromStackSlot(MBB, &MI, PhysReg, SSorRMId, RC);
1827 MachineInstr *LoadMI = prior(MII);
1828 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1829 ++NumLoads;
1830 }
1831 // This invalidates PhysReg.
1832 Spills.ClobberPhysReg(PhysReg);
1833
1834 // Any stores to this stack slot are not dead anymore.
1835 if (!DoReMat)
1836 MaybeDeadStores[SSorRMId] = NULL;
1837 Spills.addAvailable(SSorRMId, PhysReg);
1838 // Assumes this is the last use. IsKill will be unset if reg is reused
1839 // unless it's a two-address operand.
1840 if (!MI.isRegTiedToDefOperand(i) &&
1841 KilledMIRegs.count(VirtReg) == 0) {
1842 MI.getOperand(i).setIsKill();
1843 KilledMIRegs.insert(VirtReg);
1844 }
1845
Evan Cheng427a6b62009-05-15 06:48:19 +00001846 UpdateKills(*prior(MII), TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001847 DOUT << '\t' << *prior(MII);
1848 }
1849 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1850 MI.getOperand(i).setReg(RReg);
1851 MI.getOperand(i).setSubReg(0);
1852 }
1853
1854 // Ok - now we can remove stores that have been confirmed dead.
1855 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
1856 // This was the last use and the spilled value is still available
1857 // for reuse. That means the spill was unnecessary!
1858 int PDSSlot = PotentialDeadStoreSlots[j];
1859 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
1860 if (DeadStore) {
1861 DOUT << "Removed dead store:\t" << *DeadStore;
Evan Cheng427a6b62009-05-15 06:48:19 +00001862 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001863 VRM.RemoveMachineInstrFromMaps(DeadStore);
1864 MBB.erase(DeadStore);
1865 MaybeDeadStores[PDSSlot] = NULL;
1866 ++NumDSE;
1867 }
1868 }
1869
1870
1871 DOUT << '\t' << MI;
1872
1873
1874 // If we have folded references to memory operands, make sure we clear all
1875 // physical registers that may contain the value of the spilled virtual
1876 // register
1877 SmallSet<int, 2> FoldedSS;
1878 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1879 unsigned VirtReg = I->second.first;
1880 VirtRegMap::ModRef MR = I->second.second;
1881 DOUT << "Folded vreg: " << VirtReg << " MR: " << MR;
1882
1883 // MI2VirtMap be can updated which invalidate the iterator.
1884 // Increment the iterator first.
1885 ++I;
1886 int SS = VRM.getStackSlot(VirtReg);
1887 if (SS == VirtRegMap::NO_STACK_SLOT)
1888 continue;
1889 FoldedSS.insert(SS);
1890 DOUT << " - StackSlot: " << SS << "\n";
1891
1892 // If this folded instruction is just a use, check to see if it's a
1893 // straight load from the virt reg slot.
1894 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
1895 int FrameIdx;
1896 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
1897 if (DestReg && FrameIdx == SS) {
1898 // If this spill slot is available, turn it into a copy (or nothing)
1899 // instead of leaving it as a load!
1900 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
1901 DOUT << "Promoted Load To Copy: " << MI;
1902 if (DestReg != InReg) {
1903 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1904 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
1905 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
1906 unsigned SubIdx = DefMO->getSubReg();
1907 // Revisit the copy so we make sure to notice the effects of the
1908 // operation on the destreg (either needing to RA it if it's
1909 // virtual or needing to clobber any values if it's physical).
1910 NextMII = &MI;
1911 --NextMII; // backtrack to the copy.
1912 // Propagate the sub-register index over.
1913 if (SubIdx) {
1914 DefMO = NextMII->findRegisterDefOperand(DestReg);
1915 DefMO->setSubReg(SubIdx);
1916 }
1917
1918 // Mark is killed.
1919 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
1920 KillOpnd->setIsKill();
1921
1922 BackTracked = true;
1923 } else {
1924 DOUT << "Removing now-noop copy: " << MI;
1925 // Unset last kill since it's being reused.
Evan Cheng427a6b62009-05-15 06:48:19 +00001926 InvalidateKill(InReg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001927 Spills.disallowClobberPhysReg(InReg);
1928 }
1929
Evan Cheng427a6b62009-05-15 06:48:19 +00001930 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001931 VRM.RemoveMachineInstrFromMaps(&MI);
1932 MBB.erase(&MI);
1933 Erased = true;
1934 goto ProcessNextInst;
1935 }
1936 } else {
1937 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1938 SmallVector<MachineInstr*, 4> NewMIs;
1939 if (PhysReg &&
1940 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
1941 MBB.insert(MII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00001942 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001943 VRM.RemoveMachineInstrFromMaps(&MI);
1944 MBB.erase(&MI);
1945 Erased = true;
1946 --NextMII; // backtrack to the unfolded instruction.
1947 BackTracked = true;
1948 goto ProcessNextInst;
1949 }
1950 }
1951 }
1952
1953 // If this reference is not a use, any previous store is now dead.
1954 // Otherwise, the store to this stack slot is not dead anymore.
1955 MachineInstr* DeadStore = MaybeDeadStores[SS];
1956 if (DeadStore) {
1957 bool isDead = !(MR & VirtRegMap::isRef);
1958 MachineInstr *NewStore = NULL;
1959 if (MR & VirtRegMap::isModRef) {
1960 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1961 SmallVector<MachineInstr*, 4> NewMIs;
1962 // We can reuse this physreg as long as we are allowed to clobber
1963 // the value and there isn't an earlier def that has already clobbered
1964 // the physreg.
1965 if (PhysReg &&
1966 !ReusedOperands.isClobbered(PhysReg) &&
1967 Spills.canClobberPhysReg(PhysReg) &&
1968 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
1969 MachineOperand *KillOpnd =
1970 DeadStore->findRegisterUseOperand(PhysReg, true);
1971 // Note, if the store is storing a sub-register, it's possible the
1972 // super-register is needed below.
1973 if (KillOpnd && !KillOpnd->getSubReg() &&
1974 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
1975 MBB.insert(MII, NewMIs[0]);
1976 NewStore = NewMIs[1];
1977 MBB.insert(MII, NewStore);
1978 VRM.addSpillSlotUse(SS, NewStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00001979 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001980 VRM.RemoveMachineInstrFromMaps(&MI);
1981 MBB.erase(&MI);
1982 Erased = true;
1983 --NextMII;
1984 --NextMII; // backtrack to the unfolded instruction.
1985 BackTracked = true;
1986 isDead = true;
1987 ++NumSUnfold;
1988 }
1989 }
1990 }
1991
1992 if (isDead) { // Previous store is dead.
1993 // If we get here, the store is dead, nuke it now.
1994 DOUT << "Removed dead store:\t" << *DeadStore;
Evan Cheng427a6b62009-05-15 06:48:19 +00001995 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001996 VRM.RemoveMachineInstrFromMaps(DeadStore);
1997 MBB.erase(DeadStore);
1998 if (!NewStore)
1999 ++NumDSE;
2000 }
2001
2002 MaybeDeadStores[SS] = NULL;
2003 if (NewStore) {
2004 // Treat this store as a spill merged into a copy. That makes the
2005 // stack slot value available.
2006 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2007 goto ProcessNextInst;
2008 }
2009 }
2010
2011 // If the spill slot value is available, and this is a new definition of
2012 // the value, the value is not available anymore.
2013 if (MR & VirtRegMap::isMod) {
2014 // Notice that the value in this stack slot has been modified.
2015 Spills.ModifyStackSlotOrReMat(SS);
2016
2017 // If this is *just* a mod of the value, check to see if this is just a
2018 // store to the spill slot (i.e. the spill got merged into the copy). If
2019 // so, realize that the vreg is available now, and add the store to the
2020 // MaybeDeadStore info.
2021 int StackSlot;
2022 if (!(MR & VirtRegMap::isRef)) {
2023 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2024 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2025 "Src hasn't been allocated yet?");
2026
2027 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2028 Spills, RegKills, KillOps, TRI, VRM)) {
2029 NextMII = next(MII);
2030 BackTracked = true;
2031 goto ProcessNextInst;
2032 }
2033
2034 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2035 // this as a potentially dead store in case there is a subsequent
2036 // store into the stack slot without a read from it.
2037 MaybeDeadStores[StackSlot] = &MI;
2038
2039 // If the stack slot value was previously available in some other
2040 // register, change it now. Otherwise, make the register
2041 // available in PhysReg.
2042 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2043 }
2044 }
2045 }
2046 }
2047
2048 // Process all of the spilled defs.
2049 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2050 MachineOperand &MO = MI.getOperand(i);
2051 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2052 continue;
2053
2054 unsigned VirtReg = MO.getReg();
2055 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2056 // Check to see if this is a noop copy. If so, eliminate the
2057 // instruction before considering the dest reg to be changed.
Evan Cheng2578ba22009-07-01 01:59:31 +00002058 // Also check if it's copying from an "undef", if so, we can't
2059 // eliminate this or else the undef marker is lost and it will
2060 // confuses the scavenger. This is extremely rare.
Lang Hames87e3bca2009-05-06 02:36:21 +00002061 unsigned Src, Dst, SrcSR, DstSR;
Evan Cheng2578ba22009-07-01 01:59:31 +00002062 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2063 !MI.findRegisterUseOperand(Src)->isUndef()) {
Lang Hames87e3bca2009-05-06 02:36:21 +00002064 ++NumDCE;
2065 DOUT << "Removing now-noop copy: " << MI;
2066 SmallVector<unsigned, 2> KillRegs;
Evan Cheng427a6b62009-05-15 06:48:19 +00002067 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
Lang Hames87e3bca2009-05-06 02:36:21 +00002068 if (MO.isDead() && !KillRegs.empty()) {
2069 // Source register or an implicit super/sub-register use is killed.
2070 assert(KillRegs[0] == Dst ||
2071 TRI->isSubRegister(KillRegs[0], Dst) ||
2072 TRI->isSuperRegister(KillRegs[0], Dst));
2073 // Last def is now dead.
Evan Chengeca24fb2009-05-12 23:07:00 +00002074 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002075 }
2076 VRM.RemoveMachineInstrFromMaps(&MI);
2077 MBB.erase(&MI);
2078 Erased = true;
2079 Spills.disallowClobberPhysReg(VirtReg);
2080 goto ProcessNextInst;
2081 }
Evan Cheng2578ba22009-07-01 01:59:31 +00002082
Lang Hames87e3bca2009-05-06 02:36:21 +00002083 // If it's not a no-op copy, it clobbers the value in the destreg.
2084 Spills.ClobberPhysReg(VirtReg);
2085 ReusedOperands.markClobbered(VirtReg);
2086
2087 // Check to see if this instruction is a load from a stack slot into
2088 // a register. If so, this provides the stack slot value in the reg.
2089 int FrameIdx;
2090 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2091 assert(DestReg == VirtReg && "Unknown load situation!");
2092
2093 // If it is a folded reference, then it's not safe to clobber.
2094 bool Folded = FoldedSS.count(FrameIdx);
2095 // Otherwise, if it wasn't available, remember that it is now!
2096 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2097 goto ProcessNextInst;
2098 }
2099
2100 continue;
2101 }
2102
2103 unsigned SubIdx = MO.getSubReg();
2104 bool DoReMat = VRM.isReMaterialized(VirtReg);
2105 if (DoReMat)
2106 ReMatDefs.insert(&MI);
2107
2108 // The only vregs left are stack slot definitions.
2109 int StackSlot = VRM.getStackSlot(VirtReg);
2110 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2111
2112 // If this def is part of a two-address operand, make sure to execute
2113 // the store from the correct physical register.
2114 unsigned PhysReg;
2115 unsigned TiedOp;
2116 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2117 PhysReg = MI.getOperand(TiedOp).getReg();
2118 if (SubIdx) {
2119 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2120 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2121 "Can't find corresponding super-register!");
2122 PhysReg = SuperReg;
2123 }
2124 } else {
2125 PhysReg = VRM.getPhys(VirtReg);
2126 if (ReusedOperands.isClobbered(PhysReg)) {
2127 // Another def has taken the assigned physreg. It must have been a
2128 // use&def which got it due to reuse. Undo the reuse!
2129 PhysReg = ReusedOperands.GetRegForReload(PhysReg, &MI,
2130 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
2131 }
2132 }
2133
2134 assert(PhysReg && "VR not assigned a physical register?");
2135 RegInfo->setPhysRegUsed(PhysReg);
2136 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2137 ReusedOperands.markClobbered(RReg);
2138 MI.getOperand(i).setReg(RReg);
2139 MI.getOperand(i).setSubReg(0);
2140
2141 if (!MO.isDead()) {
2142 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2143 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2144 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2145 NextMII = next(MII);
2146
2147 // Check to see if this is a noop copy. If so, eliminate the
2148 // instruction before considering the dest reg to be changed.
2149 {
2150 unsigned Src, Dst, SrcSR, DstSR;
2151 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2152 ++NumDCE;
2153 DOUT << "Removing now-noop copy: " << MI;
Evan Cheng427a6b62009-05-15 06:48:19 +00002154 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002155 VRM.RemoveMachineInstrFromMaps(&MI);
2156 MBB.erase(&MI);
2157 Erased = true;
Evan Cheng427a6b62009-05-15 06:48:19 +00002158 UpdateKills(*LastStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002159 goto ProcessNextInst;
2160 }
2161 }
2162 }
2163 }
2164 ProcessNextInst:
2165 DistanceMap.insert(std::make_pair(&MI, Dist++));
2166 if (!Erased && !BackTracked) {
2167 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
Evan Cheng427a6b62009-05-15 06:48:19 +00002168 UpdateKills(*II, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002169 }
2170 MII = NextMII;
2171 }
2172
2173 }
2174
2175};
2176
2177llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2178 switch (RewriterOpt) {
2179 default: assert(0 && "Unreachable!");
2180 case local:
2181 return new LocalRewriter();
Lang Hamesf41538d2009-06-02 16:53:25 +00002182 case trivial:
2183 return new TrivialRewriter();
Lang Hames87e3bca2009-05-06 02:36:21 +00002184 }
2185}