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