blob: 70f1d21f112ec249001693742672c7ff3e35ce22 [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"
Benjamin Kramercfa6ec92009-08-23 11:37:21 +000012#include "llvm/Function.h"
13#include "llvm/CodeGen/MachineFrameInfo.h"
14#include "llvm/CodeGen/MachineInstrBuilder.h"
15#include "llvm/CodeGen/MachineRegisterInfo.h"
Benjamin Kramercfa6ec92009-08-23 11:37:21 +000016#include "llvm/Support/CommandLine.h"
17#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000018#include "llvm/Support/ErrorHandling.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000019#include "llvm/Support/raw_ostream.h"
Benjamin Kramercfa6ec92009-08-23 11:37:21 +000020#include "llvm/Target/TargetInstrInfo.h"
David Greene2d4e6d32009-07-28 16:49:24 +000021#include "llvm/Target/TargetLowering.h"
Lang Hames87e3bca2009-05-06 02:36:21 +000022#include "llvm/ADT/DepthFirstIterator.h"
23#include "llvm/ADT/Statistic.h"
Lang Hames87e3bca2009-05-06 02:36:21 +000024#include <algorithm>
25using namespace llvm;
26
27STATISTIC(NumDSE , "Number of dead stores elided");
28STATISTIC(NumDSS , "Number of dead spill slots removed");
29STATISTIC(NumCommutes, "Number of instructions commuted");
30STATISTIC(NumDRM , "Number of re-materializable defs elided");
31STATISTIC(NumStores , "Number of stores added");
32STATISTIC(NumPSpills , "Number of physical register spills");
33STATISTIC(NumOmitted , "Number of reloads omited");
34STATISTIC(NumAvoided , "Number of reloads deemed unnecessary");
35STATISTIC(NumCopified, "Number of available reloads turned into copies");
36STATISTIC(NumReMats , "Number of re-materialization");
37STATISTIC(NumLoads , "Number of loads added");
38STATISTIC(NumReused , "Number of values reused");
39STATISTIC(NumDCE , "Number of copies elided");
40STATISTIC(NumSUnfold , "Number of stores unfolded");
41STATISTIC(NumModRefUnfold, "Number of modref unfolded");
42
43namespace {
Lang Hamesac276402009-06-04 18:45:36 +000044 enum RewriterName { local, trivial };
Lang Hames87e3bca2009-05-06 02:36:21 +000045}
46
47static cl::opt<RewriterName>
48RewriterOpt("rewriter",
Duncan Sands18619b22010-02-18 14:37:52 +000049 cl::desc("Rewriter to use (default=local)"),
Lang Hames87e3bca2009-05-06 02:36:21 +000050 cl::Prefix,
Lang Hamesac276402009-06-04 18:45:36 +000051 cl::values(clEnumVal(local, "local rewriter"),
Lang Hamesf41538d2009-06-02 16:53:25 +000052 clEnumVal(trivial, "trivial rewriter"),
Lang Hames87e3bca2009-05-06 02:36:21 +000053 clEnumValEnd),
54 cl::init(local));
55
Dan Gohman7db949d2009-08-07 01:32:21 +000056static cl::opt<bool>
David Greene2d4e6d32009-07-28 16:49:24 +000057ScheduleSpills("schedule-spills",
58 cl::desc("Schedule spill code"),
59 cl::init(false));
60
Lang Hames87e3bca2009-05-06 02:36:21 +000061VirtRegRewriter::~VirtRegRewriter() {}
62
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +000063/// substitutePhysReg - Replace virtual register in MachineOperand with a
64/// physical register. Do the right thing with the sub-register index.
Jakob Stoklund Olesend135f142010-02-13 02:06:10 +000065/// Note that operands may be added, so the MO reference is no longer valid.
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +000066static void substitutePhysReg(MachineOperand &MO, unsigned Reg,
67 const TargetRegisterInfo &TRI) {
68 if (unsigned SubIdx = MO.getSubReg()) {
69 // Insert the physical subreg and reset the subreg field.
70 MO.setReg(TRI.getSubReg(Reg, SubIdx));
71 MO.setSubReg(0);
72
73 // Any def, dead, and kill flags apply to the full virtual register, so they
74 // also apply to the full physical register. Add imp-def/dead and imp-kill
75 // as needed.
76 MachineInstr &MI = *MO.getParent();
77 if (MO.isDef())
78 if (MO.isDead())
79 MI.addRegisterDead(Reg, &TRI, /*AddIfNotFound=*/ true);
80 else
81 MI.addRegisterDefined(Reg, &TRI);
82 else if (!MO.isUndef() &&
83 (MO.isKill() ||
84 MI.isRegTiedToDefOperand(&MO-&MI.getOperand(0))))
85 MI.addRegisterKilled(Reg, &TRI, /*AddIfNotFound=*/ true);
86 } else {
87 MO.setReg(Reg);
88 }
89}
90
Dan Gohman7db949d2009-08-07 01:32:21 +000091namespace {
Lang Hames87e3bca2009-05-06 02:36:21 +000092
Lang Hamesf41538d2009-06-02 16:53:25 +000093/// This class is intended for use with the new spilling framework only. It
94/// rewrites vreg def/uses to use the assigned preg, but does not insert any
95/// spill code.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000096struct TrivialRewriter : public VirtRegRewriter {
Lang Hamesf41538d2009-06-02 16:53:25 +000097
98 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
99 LiveIntervals* LIs) {
David Greene0ee52182010-01-05 01:25:52 +0000100 DEBUG(dbgs() << "********** REWRITE MACHINE CODE **********\n");
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000101 DEBUG(dbgs() << "********** Function: "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000102 << MF.getFunction()->getName() << '\n');
David Greene0ee52182010-01-05 01:25:52 +0000103 DEBUG(dbgs() << "**** Machine Instrs"
Chris Lattner6456d382009-08-23 03:20:44 +0000104 << "(NOTE! Does not include spills and reloads!) ****\n");
David Greene2d4e6d32009-07-28 16:49:24 +0000105 DEBUG(MF.dump());
106
Lang Hamesf41538d2009-06-02 16:53:25 +0000107 MachineRegisterInfo *mri = &MF.getRegInfo();
Lang Hames38283e22009-11-18 20:31:20 +0000108 const TargetRegisterInfo *tri = MF.getTarget().getRegisterInfo();
Lang Hamesf41538d2009-06-02 16:53:25 +0000109
110 bool changed = false;
111
112 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
113 liItr != liEnd; ++liItr) {
114
Lang Hames38283e22009-11-18 20:31:20 +0000115 const LiveInterval *li = liItr->second;
116 unsigned reg = li->reg;
117
118 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
119 if (!li->empty())
120 mri->setPhysRegUsed(reg);
121 }
122 else {
123 if (!VRM.hasPhys(reg))
124 continue;
125 unsigned pReg = VRM.getPhys(reg);
126 mri->setPhysRegUsed(pReg);
Jakob Stoklund Olesend135f142010-02-13 02:06:10 +0000127 // Copy the register use-list before traversing it.
128 SmallVector<std::pair<MachineInstr*, unsigned>, 32> reglist;
129 for (MachineRegisterInfo::reg_iterator I = mri->reg_begin(reg),
130 E = mri->reg_end(); I != E; ++I)
131 reglist.push_back(std::make_pair(&*I, I.getOperandNo()));
132 for (unsigned N=0; N != reglist.size(); ++N)
133 substitutePhysReg(reglist[N].first->getOperand(reglist[N].second),
134 pReg, *tri);
135 changed |= !reglist.empty();
Lang Hamesf41538d2009-06-02 16:53:25 +0000136 }
Lang Hamesf41538d2009-06-02 16:53:25 +0000137 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000138
David Greene0ee52182010-01-05 01:25:52 +0000139 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
David Greene2d4e6d32009-07-28 16:49:24 +0000140 DEBUG(MF.dump());
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000141
Lang Hamesf41538d2009-06-02 16:53:25 +0000142 return changed;
143 }
144
145};
146
Dan Gohman7db949d2009-08-07 01:32:21 +0000147}
148
Lang Hames87e3bca2009-05-06 02:36:21 +0000149// ************************************************************************ //
150
Dan Gohman7db949d2009-08-07 01:32:21 +0000151namespace {
152
Lang Hames87e3bca2009-05-06 02:36:21 +0000153/// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
154/// from top down, keep track of which spill slots or remat are available in
155/// each register.
156///
157/// Note that not all physregs are created equal here. In particular, some
158/// physregs are reloads that we are allowed to clobber or ignore at any time.
159/// Other physregs are values that the register allocated program is using
160/// that we cannot CHANGE, but we can read if we like. We keep track of this
161/// on a per-stack-slot / remat id basis as the low bit in the value of the
162/// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
163/// this bit and addAvailable sets it if.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000164class AvailableSpills {
Lang Hames87e3bca2009-05-06 02:36:21 +0000165 const TargetRegisterInfo *TRI;
166 const TargetInstrInfo *TII;
167
168 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
169 // or remat'ed virtual register values that are still available, due to
170 // being loaded or stored to, but not invalidated yet.
171 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
172
173 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
174 // indicating which stack slot values are currently held by a physreg. This
175 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
176 // physreg is modified.
177 std::multimap<unsigned, int> PhysRegsAvailable;
178
179 void disallowClobberPhysRegOnly(unsigned PhysReg);
180
181 void ClobberPhysRegOnly(unsigned PhysReg);
182public:
183 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
184 : TRI(tri), TII(tii) {
185 }
186
187 /// clear - Reset the state.
188 void clear() {
189 SpillSlotsOrReMatsAvailable.clear();
190 PhysRegsAvailable.clear();
191 }
192
193 const TargetRegisterInfo *getRegInfo() const { return TRI; }
194
195 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
196 /// available in a physical register, return that PhysReg, otherwise
197 /// return 0.
198 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
199 std::map<int, unsigned>::const_iterator I =
200 SpillSlotsOrReMatsAvailable.find(Slot);
201 if (I != SpillSlotsOrReMatsAvailable.end()) {
202 return I->second >> 1; // Remove the CanClobber bit.
203 }
204 return 0;
205 }
206
207 /// addAvailable - Mark that the specified stack slot / remat is available
208 /// in the specified physreg. If CanClobber is true, the physreg can be
209 /// modified at any time without changing the semantics of the program.
210 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000211 // If this stack slot is thought to be available in some other physreg,
Lang Hames87e3bca2009-05-06 02:36:21 +0000212 // remove its record.
213 ModifyStackSlotOrReMat(SlotOrReMat);
214
215 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
216 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
217 (unsigned)CanClobber;
218
219 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
David Greene0ee52182010-01-05 01:25:52 +0000220 DEBUG(dbgs() << "Remembering RM#"
Chris Lattner6456d382009-08-23 03:20:44 +0000221 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +0000222 else
David Greene0ee52182010-01-05 01:25:52 +0000223 DEBUG(dbgs() << "Remembering SS#" << SlotOrReMat);
224 DEBUG(dbgs() << " in physreg " << TRI->getName(Reg) << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000225 }
226
227 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
228 /// the value of the specified stackslot register if it desires. The
229 /// specified stack slot must be available in a physreg for this query to
230 /// make sense.
231 bool canClobberPhysRegForSS(int SlotOrReMat) const {
232 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
233 "Value not available!");
234 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
235 }
236
237 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
238 /// physical register where values for some stack slot(s) might be
239 /// available.
240 bool canClobberPhysReg(unsigned PhysReg) const {
241 std::multimap<unsigned, int>::const_iterator I =
242 PhysRegsAvailable.lower_bound(PhysReg);
243 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
244 int SlotOrReMat = I->second;
245 I++;
246 if (!canClobberPhysRegForSS(SlotOrReMat))
247 return false;
248 }
249 return true;
250 }
251
252 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
253 /// stackslot register. The register is still available but is no longer
254 /// allowed to be modifed.
255 void disallowClobberPhysReg(unsigned PhysReg);
256
257 /// ClobberPhysReg - This is called when the specified physreg changes
258 /// value. We use this to invalidate any info about stuff that lives in
259 /// it and any of its aliases.
260 void ClobberPhysReg(unsigned PhysReg);
261
262 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
263 /// slot changes. This removes information about which register the
264 /// previous value for this slot lives in (as the previous value is dead
265 /// now).
266 void ModifyStackSlotOrReMat(int SlotOrReMat);
267
268 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
269 /// into the specified MBB. Add available physical registers as potential
270 /// live-in's. If they are reused in the MBB, they will be added to the
271 /// live-in set to make register scavenger and post-allocation scheduler.
272 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
273 std::vector<MachineOperand*> &KillOps);
274};
275
Dan Gohman7db949d2009-08-07 01:32:21 +0000276}
277
Lang Hames87e3bca2009-05-06 02:36:21 +0000278// ************************************************************************ //
279
David Greene2d4e6d32009-07-28 16:49:24 +0000280// Given a location where a reload of a spilled register or a remat of
281// a constant is to be inserted, attempt to find a safe location to
282// insert the load at an earlier point in the basic-block, to hide
283// latency of the load and to avoid address-generation interlock
284// issues.
285static MachineBasicBlock::iterator
286ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
287 MachineBasicBlock::iterator const Begin,
288 unsigned PhysReg,
289 const TargetRegisterInfo *TRI,
290 bool DoReMat,
291 int SSorRMId,
292 const TargetInstrInfo *TII,
293 const MachineFunction &MF)
294{
295 if (!ScheduleSpills)
296 return InsertLoc;
297
298 // Spill backscheduling is of primary interest to addresses, so
299 // don't do anything if the register isn't in the register class
300 // used for pointers.
301
302 const TargetLowering *TL = MF.getTarget().getTargetLowering();
303
304 if (!TL->isTypeLegal(TL->getPointerTy()))
305 // Believe it or not, this is true on PIC16.
306 return InsertLoc;
307
308 const TargetRegisterClass *ptrRegClass =
309 TL->getRegClassFor(TL->getPointerTy());
310 if (!ptrRegClass->contains(PhysReg))
311 return InsertLoc;
312
313 // Scan upwards through the preceding instructions. If an instruction doesn't
314 // reference the stack slot or the register we're loading, we can
315 // backschedule the reload up past it.
316 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
317 while (NewInsertLoc != Begin) {
318 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
319 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
320 MachineOperand &Op = Prev->getOperand(i);
321 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
322 goto stop;
323 }
324 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
325 Prev->findRegisterDefOperand(PhysReg))
326 goto stop;
327 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
328 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
329 Prev->findRegisterDefOperand(*Alias))
330 goto stop;
331 NewInsertLoc = Prev;
332 }
333stop:;
334
335 // If we made it to the beginning of the block, turn around and move back
336 // down just past any existing reloads. They're likely to be reloads/remats
337 // for instructions earlier than what our current reload/remat is for, so
338 // they should be scheduled earlier.
339 if (NewInsertLoc == Begin) {
340 int FrameIdx;
341 while (InsertLoc != NewInsertLoc &&
342 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
343 TII->isTriviallyReMaterializable(NewInsertLoc)))
344 ++NewInsertLoc;
345 }
346
347 return NewInsertLoc;
348}
Dan Gohman7db949d2009-08-07 01:32:21 +0000349
350namespace {
351
Lang Hames87e3bca2009-05-06 02:36:21 +0000352// ReusedOp - For each reused operand, we keep track of a bit of information,
353// in case we need to rollback upon processing a new operand. See comments
354// below.
355struct ReusedOp {
356 // The MachineInstr operand that reused an available value.
357 unsigned Operand;
358
359 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
360 unsigned StackSlotOrReMat;
361
362 // PhysRegReused - The physical register the value was available in.
363 unsigned PhysRegReused;
364
365 // AssignedPhysReg - The physreg that was assigned for use by the reload.
366 unsigned AssignedPhysReg;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000367
Lang Hames87e3bca2009-05-06 02:36:21 +0000368 // VirtReg - The virtual register itself.
369 unsigned VirtReg;
370
371 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
372 unsigned vreg)
373 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
374 AssignedPhysReg(apr), VirtReg(vreg) {}
375};
376
377/// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
378/// is reused instead of reloaded.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000379class ReuseInfo {
Lang Hames87e3bca2009-05-06 02:36:21 +0000380 MachineInstr &MI;
381 std::vector<ReusedOp> Reuses;
382 BitVector PhysRegsClobbered;
383public:
384 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
385 PhysRegsClobbered.resize(tri->getNumRegs());
386 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000387
Lang Hames87e3bca2009-05-06 02:36:21 +0000388 bool hasReuses() const {
389 return !Reuses.empty();
390 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000391
Lang Hames87e3bca2009-05-06 02:36:21 +0000392 /// addReuse - If we choose to reuse a virtual register that is already
393 /// available instead of reloading it, remember that we did so.
394 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
395 unsigned PhysRegReused, unsigned AssignedPhysReg,
396 unsigned VirtReg) {
397 // If the reload is to the assigned register anyway, no undo will be
398 // required.
399 if (PhysRegReused == AssignedPhysReg) return;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000400
Lang Hames87e3bca2009-05-06 02:36:21 +0000401 // Otherwise, remember this.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000402 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
Lang Hames87e3bca2009-05-06 02:36:21 +0000403 AssignedPhysReg, VirtReg));
404 }
405
406 void markClobbered(unsigned PhysReg) {
407 PhysRegsClobbered.set(PhysReg);
408 }
409
410 bool isClobbered(unsigned PhysReg) const {
411 return PhysRegsClobbered.test(PhysReg);
412 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000413
Lang Hames87e3bca2009-05-06 02:36:21 +0000414 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
415 /// is some other operand that is using the specified register, either pick
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000416 /// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000417 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
418 MachineFunction &MF, MachineInstr *MI,
Lang Hames87e3bca2009-05-06 02:36:21 +0000419 AvailableSpills &Spills,
420 std::vector<MachineInstr*> &MaybeDeadStores,
421 SmallSet<unsigned, 8> &Rejected,
422 BitVector &RegKills,
423 std::vector<MachineOperand*> &KillOps,
424 VirtRegMap &VRM);
425
426 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
427 /// 'Rejected' set to remember which registers have been considered and
428 /// rejected for the reload. This avoids infinite looping in case like
429 /// this:
430 /// t1 := op t2, t3
431 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
432 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
433 /// t1 <- desires r1
434 /// sees r1 is taken by t2, tries t2's reload register r0
435 /// sees r0 is taken by t3, tries t3's reload register r1
436 /// sees r1 is taken by t2, tries t2's reload register r0 ...
Evan Cheng5d885022009-07-21 09:15:00 +0000437 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
Lang Hames87e3bca2009-05-06 02:36:21 +0000438 AvailableSpills &Spills,
439 std::vector<MachineInstr*> &MaybeDeadStores,
440 BitVector &RegKills,
441 std::vector<MachineOperand*> &KillOps,
442 VirtRegMap &VRM) {
443 SmallSet<unsigned, 8> Rejected;
Evan Cheng5d885022009-07-21 09:15:00 +0000444 MachineFunction &MF = *MI->getParent()->getParent();
445 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
446 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
447 Rejected, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +0000448 }
449};
450
Dan Gohman7db949d2009-08-07 01:32:21 +0000451}
Lang Hames87e3bca2009-05-06 02:36:21 +0000452
453// ****************** //
454// Utility Functions //
455// ****************** //
456
Lang Hames87e3bca2009-05-06 02:36:21 +0000457/// findSinglePredSuccessor - Return via reference a vector of machine basic
458/// blocks each of which is a successor of the specified BB and has no other
459/// predecessor.
460static void findSinglePredSuccessor(MachineBasicBlock *MBB,
461 SmallVectorImpl<MachineBasicBlock *> &Succs) {
462 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
463 SE = MBB->succ_end(); SI != SE; ++SI) {
464 MachineBasicBlock *SuccMBB = *SI;
465 if (SuccMBB->pred_size() == 1)
466 Succs.push_back(SuccMBB);
467 }
468}
469
Evan Cheng427a6b62009-05-15 06:48:19 +0000470/// InvalidateKill - Invalidate register kill information for a specific
471/// register. This also unsets the kills marker on the last kill operand.
472static void InvalidateKill(unsigned Reg,
473 const TargetRegisterInfo* TRI,
474 BitVector &RegKills,
475 std::vector<MachineOperand*> &KillOps) {
476 if (RegKills[Reg]) {
477 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000478 // KillOps[Reg] might be a def of a super-register.
479 unsigned KReg = KillOps[Reg]->getReg();
480 KillOps[KReg] = NULL;
481 RegKills.reset(KReg);
482 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
Evan Cheng427a6b62009-05-15 06:48:19 +0000483 if (RegKills[*SR]) {
484 KillOps[*SR]->setIsKill(false);
485 KillOps[*SR] = NULL;
486 RegKills.reset(*SR);
487 }
488 }
489 }
490}
491
Lang Hames87e3bca2009-05-06 02:36:21 +0000492/// InvalidateKills - MI is going to be deleted. If any of its operands are
493/// marked kill, then invalidate the information.
Evan Cheng427a6b62009-05-15 06:48:19 +0000494static void InvalidateKills(MachineInstr &MI,
495 const TargetRegisterInfo* TRI,
496 BitVector &RegKills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000497 std::vector<MachineOperand*> &KillOps,
498 SmallVector<unsigned, 2> *KillRegs = NULL) {
499 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
500 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000501 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000502 continue;
503 unsigned Reg = MO.getReg();
504 if (TargetRegisterInfo::isVirtualRegister(Reg))
505 continue;
506 if (KillRegs)
507 KillRegs->push_back(Reg);
508 assert(Reg < KillOps.size());
509 if (KillOps[Reg] == &MO) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000510 KillOps[Reg] = NULL;
Evan Cheng427a6b62009-05-15 06:48:19 +0000511 RegKills.reset(Reg);
512 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
513 if (RegKills[*SR]) {
514 KillOps[*SR] = NULL;
515 RegKills.reset(*SR);
516 }
517 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000518 }
519 }
520}
521
522/// InvalidateRegDef - If the def operand of the specified def MI is now dead
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000523/// (since its spill instruction is removed), mark it isDead. Also checks if
Lang Hames87e3bca2009-05-06 02:36:21 +0000524/// the def MI has other definition operands that are not dead. Returns it by
525/// reference.
526static bool InvalidateRegDef(MachineBasicBlock::iterator I,
527 MachineInstr &NewDef, unsigned Reg,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000528 bool &HasLiveDef,
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000529 const TargetRegisterInfo *TRI) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000530 // Due to remat, it's possible this reg isn't being reused. That is,
531 // the def of this reg (by prev MI) is now dead.
532 MachineInstr *DefMI = I;
533 MachineOperand *DefOp = NULL;
534 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
535 MachineOperand &MO = DefMI->getOperand(i);
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000536 if (!MO.isReg() || !MO.isDef() || !MO.isKill() || MO.isUndef())
Evan Cheng4784f1f2009-06-30 08:49:04 +0000537 continue;
538 if (MO.getReg() == Reg)
539 DefOp = &MO;
540 else if (!MO.isDead())
541 HasLiveDef = true;
Lang Hames87e3bca2009-05-06 02:36:21 +0000542 }
543 if (!DefOp)
544 return false;
545
546 bool FoundUse = false, Done = false;
547 MachineBasicBlock::iterator E = &NewDef;
548 ++I; ++E;
549 for (; !Done && I != E; ++I) {
550 MachineInstr *NMI = I;
551 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
552 MachineOperand &MO = NMI->getOperand(j);
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000553 if (!MO.isReg() || MO.getReg() == 0 ||
554 (MO.getReg() != Reg && !TRI->isSubRegister(Reg, MO.getReg())))
Lang Hames87e3bca2009-05-06 02:36:21 +0000555 continue;
556 if (MO.isUse())
557 FoundUse = true;
558 Done = true; // Stop after scanning all the operands of this MI.
559 }
560 }
561 if (!FoundUse) {
562 // Def is dead!
563 DefOp->setIsDead();
564 return true;
565 }
566 return false;
567}
568
569/// UpdateKills - Track and update kill info. If a MI reads a register that is
570/// marked kill, then it must be due to register reuse. Transfer the kill info
571/// over.
Evan Cheng427a6b62009-05-15 06:48:19 +0000572static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
573 BitVector &RegKills,
574 std::vector<MachineOperand*> &KillOps) {
Dale Johannesen4d12d3b2010-03-26 19:21:26 +0000575 // These do not affect kill info at all.
576 if (MI.isDebugValue())
577 return;
Lang Hames87e3bca2009-05-06 02:36:21 +0000578 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
579 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000580 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000581 continue;
582 unsigned Reg = MO.getReg();
583 if (Reg == 0)
584 continue;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000585
Lang Hames87e3bca2009-05-06 02:36:21 +0000586 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
587 // That can't be right. Register is killed but not re-defined and it's
588 // being reused. Let's fix that.
589 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000590 // KillOps[Reg] might be a def of a super-register.
591 unsigned KReg = KillOps[Reg]->getReg();
592 KillOps[KReg] = NULL;
593 RegKills.reset(KReg);
594
595 // Must be a def of a super-register. Its other sub-regsters are no
596 // longer killed as well.
597 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
598 KillOps[*SR] = NULL;
599 RegKills.reset(*SR);
600 }
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000601 } else {
602 // Check for subreg kills as well.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000603 // d4 =
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000604 // store d4, fi#0
605 // ...
606 // = s8<kill>
607 // ...
608 // = d4 <avoiding reload>
609 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
610 unsigned SReg = *SR;
611 if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
612 KillOps[SReg]->setIsKill(false);
613 unsigned KReg = KillOps[SReg]->getReg();
614 KillOps[KReg] = NULL;
615 RegKills.reset(KReg);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000616
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000617 for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
618 KillOps[*SSR] = NULL;
619 RegKills.reset(*SSR);
620 }
621 }
622 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000623 }
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000624
Lang Hames87e3bca2009-05-06 02:36:21 +0000625 if (MO.isKill()) {
626 RegKills.set(Reg);
627 KillOps[Reg] = &MO;
Evan Cheng427a6b62009-05-15 06:48:19 +0000628 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
629 RegKills.set(*SR);
630 KillOps[*SR] = &MO;
631 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000632 }
633 }
634
635 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
636 const MachineOperand &MO = MI.getOperand(i);
Evan Chengd57cdd52009-11-14 02:55:43 +0000637 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000638 continue;
639 unsigned Reg = MO.getReg();
640 RegKills.reset(Reg);
641 KillOps[Reg] = NULL;
642 // It also defines (or partially define) aliases.
Evan Cheng427a6b62009-05-15 06:48:19 +0000643 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
644 RegKills.reset(*SR);
645 KillOps[*SR] = NULL;
Lang Hames87e3bca2009-05-06 02:36:21 +0000646 }
Evan Cheng1f6a3c82009-11-13 23:16:41 +0000647 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
648 RegKills.reset(*SR);
649 KillOps[*SR] = NULL;
650 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000651 }
652}
653
654/// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
655///
656static void ReMaterialize(MachineBasicBlock &MBB,
657 MachineBasicBlock::iterator &MII,
658 unsigned DestReg, unsigned Reg,
659 const TargetInstrInfo *TII,
660 const TargetRegisterInfo *TRI,
661 VirtRegMap &VRM) {
Evan Cheng5f159922009-07-16 20:15:00 +0000662 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
Daniel Dunbar24cd3c42009-07-16 22:08:25 +0000663#ifndef NDEBUG
Evan Cheng5f159922009-07-16 20:15:00 +0000664 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
Evan Chengc1b46f92009-07-17 00:32:06 +0000665 assert(TID.getNumDefs() == 1 &&
Evan Cheng5f159922009-07-16 20:15:00 +0000666 "Don't know how to remat instructions that define > 1 values!");
667#endif
668 TII->reMaterialize(MBB, MII, DestReg,
Evan Chengd57cdd52009-11-14 02:55:43 +0000669 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI, TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +0000670 MachineInstr *NewMI = prior(MII);
671 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
672 MachineOperand &MO = NewMI->getOperand(i);
673 if (!MO.isReg() || MO.getReg() == 0)
674 continue;
675 unsigned VirtReg = MO.getReg();
676 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
677 continue;
678 assert(MO.isUse());
Lang Hames87e3bca2009-05-06 02:36:21 +0000679 unsigned Phys = VRM.getPhys(VirtReg);
Evan Cheng427c3ba2009-10-25 07:51:47 +0000680 assert(Phys && "Virtual register is not assigned a register?");
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +0000681 substitutePhysReg(MO, Phys, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +0000682 }
683 ++NumReMats;
684}
685
686/// findSuperReg - Find the SubReg's super-register of given register class
687/// where its SubIdx sub-register is SubReg.
688static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
689 unsigned SubIdx, const TargetRegisterInfo *TRI) {
690 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
691 I != E; ++I) {
692 unsigned Reg = *I;
693 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
694 return Reg;
695 }
696 return 0;
697}
698
699// ******************************** //
700// Available Spills Implementation //
701// ******************************** //
702
703/// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
704/// stackslot register. The register is still available but is no longer
705/// allowed to be modifed.
706void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
707 std::multimap<unsigned, int>::iterator I =
708 PhysRegsAvailable.lower_bound(PhysReg);
709 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
710 int SlotOrReMat = I->second;
711 I++;
712 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
713 "Bidirectional map mismatch!");
714 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
David Greene0ee52182010-01-05 01:25:52 +0000715 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
Chris Lattner6456d382009-08-23 03:20:44 +0000716 << " copied, it is available for use but can no longer be modified\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000717 }
718}
719
720/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
721/// stackslot register and its aliases. The register and its aliases may
722/// still available but is no longer allowed to be modifed.
723void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
724 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
725 disallowClobberPhysRegOnly(*AS);
726 disallowClobberPhysRegOnly(PhysReg);
727}
728
729/// ClobberPhysRegOnly - This is called when the specified physreg changes
730/// value. We use this to invalidate any info about stuff we thing lives in it.
731void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
732 std::multimap<unsigned, int>::iterator I =
733 PhysRegsAvailable.lower_bound(PhysReg);
734 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
735 int SlotOrReMat = I->second;
736 PhysRegsAvailable.erase(I++);
737 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
738 "Bidirectional map mismatch!");
739 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
David Greene0ee52182010-01-05 01:25:52 +0000740 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
Chris Lattner6456d382009-08-23 03:20:44 +0000741 << " clobbered, invalidating ");
Lang Hames87e3bca2009-05-06 02:36:21 +0000742 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
David Greene0ee52182010-01-05 01:25:52 +0000743 DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000744 else
David Greene0ee52182010-01-05 01:25:52 +0000745 DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000746 }
747}
748
749/// ClobberPhysReg - This is called when the specified physreg changes
750/// value. We use this to invalidate any info about stuff we thing lives in
751/// it and any of its aliases.
752void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
753 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
754 ClobberPhysRegOnly(*AS);
755 ClobberPhysRegOnly(PhysReg);
756}
757
758/// AddAvailableRegsToLiveIn - Availability information is being kept coming
759/// into the specified MBB. Add available physical registers as potential
760/// live-in's. If they are reused in the MBB, they will be added to the
761/// live-in set to make register scavenger and post-allocation scheduler.
762void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
763 BitVector &RegKills,
764 std::vector<MachineOperand*> &KillOps) {
765 std::set<unsigned> NotAvailable;
766 for (std::multimap<unsigned, int>::iterator
767 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
768 I != E; ++I) {
769 unsigned Reg = I->first;
770 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
771 // FIXME: A temporary workaround. We can't reuse available value if it's
772 // not safe to move the def of the virtual register's class. e.g.
773 // X86::RFP* register classes. Do not add it as a live-in.
774 if (!TII->isSafeToMoveRegClassDefs(RC))
775 // This is no longer available.
776 NotAvailable.insert(Reg);
777 else {
778 MBB.addLiveIn(Reg);
Evan Cheng427a6b62009-05-15 06:48:19 +0000779 InvalidateKill(Reg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +0000780 }
781
782 // Skip over the same register.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000783 std::multimap<unsigned, int>::iterator NI = llvm::next(I);
Lang Hames87e3bca2009-05-06 02:36:21 +0000784 while (NI != E && NI->first == Reg) {
785 ++I;
786 ++NI;
787 }
788 }
789
790 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
791 E = NotAvailable.end(); I != E; ++I) {
792 ClobberPhysReg(*I);
793 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
794 *SubRegs; ++SubRegs)
795 ClobberPhysReg(*SubRegs);
796 }
797}
798
799/// ModifyStackSlotOrReMat - This method is called when the value in a stack
800/// slot changes. This removes information about which register the previous
801/// value for this slot lives in (as the previous value is dead now).
802void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
803 std::map<int, unsigned>::iterator It =
804 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
805 if (It == SpillSlotsOrReMatsAvailable.end()) return;
806 unsigned Reg = It->second >> 1;
807 SpillSlotsOrReMatsAvailable.erase(It);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000808
Lang Hames87e3bca2009-05-06 02:36:21 +0000809 // This register may hold the value of multiple stack slots, only remove this
810 // stack slot from the set of values the register contains.
811 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
812 for (; ; ++I) {
813 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
814 "Map inverse broken!");
815 if (I->second == SlotOrReMat) break;
816 }
817 PhysRegsAvailable.erase(I);
818}
819
820// ************************** //
821// Reuse Info Implementation //
822// ************************** //
823
824/// GetRegForReload - We are about to emit a reload into PhysReg. If there
825/// is some other operand that is using the specified register, either pick
826/// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000827unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
828 unsigned PhysReg,
829 MachineFunction &MF,
830 MachineInstr *MI, AvailableSpills &Spills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000831 std::vector<MachineInstr*> &MaybeDeadStores,
832 SmallSet<unsigned, 8> &Rejected,
833 BitVector &RegKills,
834 std::vector<MachineOperand*> &KillOps,
835 VirtRegMap &VRM) {
Evan Cheng5d885022009-07-21 09:15:00 +0000836 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
837 const TargetRegisterInfo *TRI = Spills.getRegInfo();
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000838
Lang Hames87e3bca2009-05-06 02:36:21 +0000839 if (Reuses.empty()) return PhysReg; // This is most often empty.
840
841 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
842 ReusedOp &Op = Reuses[ro];
843 // If we find some other reuse that was supposed to use this register
844 // exactly for its reload, we can change this reload to use ITS reload
845 // register. That is, unless its reload register has already been
846 // considered and subsequently rejected because it has also been reused
847 // by another operand.
848 if (Op.PhysRegReused == PhysReg &&
Evan Cheng5d885022009-07-21 09:15:00 +0000849 Rejected.count(Op.AssignedPhysReg) == 0 &&
850 RC->contains(Op.AssignedPhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000851 // Yup, use the reload register that we didn't use before.
852 unsigned NewReg = Op.AssignedPhysReg;
853 Rejected.insert(PhysReg);
Evan Cheng5d885022009-07-21 09:15:00 +0000854 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
Lang Hames87e3bca2009-05-06 02:36:21 +0000855 RegKills, KillOps, VRM);
856 } else {
857 // Otherwise, we might also have a problem if a previously reused
Evan Cheng5d885022009-07-21 09:15:00 +0000858 // value aliases the new register. If so, codegen the previous reload
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000859 // and use this one.
Lang Hames87e3bca2009-05-06 02:36:21 +0000860 unsigned PRRU = Op.PhysRegReused;
Lang Hames3f2f3f52009-09-03 02:52:02 +0000861 if (TRI->regsOverlap(PRRU, PhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000862 // Okay, we found out that an alias of a reused register
863 // was used. This isn't good because it means we have
864 // to undo a previous reuse.
865 MachineBasicBlock *MBB = MI->getParent();
866 const TargetRegisterClass *AliasRC =
867 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
868
869 // Copy Op out of the vector and remove it, we're going to insert an
870 // explicit load for it.
871 ReusedOp NewOp = Op;
872 Reuses.erase(Reuses.begin()+ro);
873
Jakob Stoklund Olesen46ff9692009-08-23 13:01:45 +0000874 // MI may be using only a sub-register of PhysRegUsed.
875 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
876 unsigned SubIdx = 0;
877 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
878 "A reuse cannot be a virtual register");
879 if (PRRU != RealPhysRegUsed) {
880 // What was the sub-register index?
Evan Chengfae3e922009-11-14 03:42:17 +0000881 SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
882 assert(SubIdx &&
Jakob Stoklund Olesen46ff9692009-08-23 13:01:45 +0000883 "Operand physreg is not a sub-register of PhysRegUsed");
884 }
885
Lang Hames87e3bca2009-05-06 02:36:21 +0000886 // Ok, we're going to try to reload the assigned physreg into the
887 // slot that we were supposed to in the first place. However, that
888 // register could hold a reuse. Check to see if it conflicts or
889 // would prefer us to use a different register.
Evan Cheng5d885022009-07-21 09:15:00 +0000890 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
891 MF, MI, Spills, MaybeDeadStores,
892 Rejected, RegKills, KillOps, VRM);
David Greene2d4e6d32009-07-28 16:49:24 +0000893
894 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
895 int SSorRMId = DoReMat
896 ? VRM.getReMatId(NewOp.VirtReg) : NewOp.StackSlotOrReMat;
897
898 // Back-schedule reloads and remats.
899 MachineBasicBlock::iterator InsertLoc =
900 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
901 DoReMat, SSorRMId, TII, MF);
902
903 if (DoReMat) {
904 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
905 TRI, VRM);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000906 } else {
David Greene2d4e6d32009-07-28 16:49:24 +0000907 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
Lang Hames87e3bca2009-05-06 02:36:21 +0000908 NewOp.StackSlotOrReMat, AliasRC);
David Greene2d4e6d32009-07-28 16:49:24 +0000909 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +0000910 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
911 // Any stores to this stack slot are not dead anymore.
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000912 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
Lang Hames87e3bca2009-05-06 02:36:21 +0000913 ++NumLoads;
914 }
915 Spills.ClobberPhysReg(NewPhysReg);
916 Spills.ClobberPhysReg(NewOp.PhysRegReused);
917
Evan Cheng427c3ba2009-10-25 07:51:47 +0000918 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
Lang Hames87e3bca2009-05-06 02:36:21 +0000919 MI->getOperand(NewOp.Operand).setReg(RReg);
920 MI->getOperand(NewOp.Operand).setSubReg(0);
921
922 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
David Greene2d4e6d32009-07-28 16:49:24 +0000923 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
David Greene0ee52182010-01-05 01:25:52 +0000924 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000925
David Greene0ee52182010-01-05 01:25:52 +0000926 DEBUG(dbgs() << "Reuse undone!\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000927 --NumReused;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +0000928
Lang Hames87e3bca2009-05-06 02:36:21 +0000929 // Finally, PhysReg is now available, go ahead and use it.
930 return PhysReg;
931 }
932 }
933 }
934 return PhysReg;
935}
936
937// ************************************************************************ //
938
939/// FoldsStackSlotModRef - Return true if the specified MI folds the specified
940/// stack slot mod/ref. It also checks if it's possible to unfold the
941/// instruction by having it define a specified physical register instead.
942static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
943 const TargetInstrInfo *TII,
944 const TargetRegisterInfo *TRI,
945 VirtRegMap &VRM) {
946 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
947 return false;
948
949 bool Found = false;
950 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
951 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
952 unsigned VirtReg = I->second.first;
953 VirtRegMap::ModRef MR = I->second.second;
954 if (MR & VirtRegMap::isModRef)
955 if (VRM.getStackSlot(VirtReg) == SS) {
956 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
957 break;
958 }
959 }
960 if (!Found)
961 return false;
962
963 // Does the instruction uses a register that overlaps the scratch register?
964 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
965 MachineOperand &MO = MI.getOperand(i);
966 if (!MO.isReg() || MO.getReg() == 0)
967 continue;
968 unsigned Reg = MO.getReg();
969 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
970 if (!VRM.hasPhys(Reg))
971 continue;
972 Reg = VRM.getPhys(Reg);
973 }
974 if (TRI->regsOverlap(PhysReg, Reg))
975 return false;
976 }
977 return true;
978}
979
980/// FindFreeRegister - Find a free register of a given register class by looking
981/// at (at most) the last two machine instructions.
982static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
983 MachineBasicBlock &MBB,
984 const TargetRegisterClass *RC,
985 const TargetRegisterInfo *TRI,
986 BitVector &AllocatableRegs) {
987 BitVector Defs(TRI->getNumRegs());
988 BitVector Uses(TRI->getNumRegs());
989 SmallVector<unsigned, 4> LocalUses;
990 SmallVector<unsigned, 4> Kills;
991
992 // Take a look at 2 instructions at most.
993 for (unsigned Count = 0; Count < 2; ++Count) {
994 if (MII == MBB.begin())
995 break;
996 MachineInstr *PrevMI = prior(MII);
997 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
998 MachineOperand &MO = PrevMI->getOperand(i);
999 if (!MO.isReg() || MO.getReg() == 0)
1000 continue;
1001 unsigned Reg = MO.getReg();
1002 if (MO.isDef()) {
1003 Defs.set(Reg);
1004 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1005 Defs.set(*AS);
1006 } else {
1007 LocalUses.push_back(Reg);
1008 if (MO.isKill() && AllocatableRegs[Reg])
1009 Kills.push_back(Reg);
1010 }
1011 }
1012
1013 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1014 unsigned Kill = Kills[i];
1015 if (!Defs[Kill] && !Uses[Kill] &&
1016 TRI->getPhysicalRegisterRegClass(Kill) == RC)
1017 return Kill;
1018 }
1019 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1020 unsigned Reg = LocalUses[i];
1021 Uses.set(Reg);
1022 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1023 Uses.set(*AS);
1024 }
1025
1026 MII = PrevMI;
1027 }
1028
1029 return 0;
1030}
1031
1032static
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001033void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1034 const TargetRegisterInfo &TRI) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001035 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1036 MachineOperand &MO = MI->getOperand(i);
1037 if (MO.isReg() && MO.getReg() == VirtReg)
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001038 substitutePhysReg(MO, PhysReg, TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001039 }
1040}
1041
Evan Chengeca24fb2009-05-12 23:07:00 +00001042namespace {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001043
1044struct RefSorter {
1045 bool operator()(const std::pair<MachineInstr*, int> &A,
1046 const std::pair<MachineInstr*, int> &B) {
1047 return A.second < B.second;
1048 }
1049};
Lang Hames87e3bca2009-05-06 02:36:21 +00001050
1051// ***************************** //
1052// Local Spiller Implementation //
1053// ***************************** //
1054
Nick Lewycky6726b6d2009-10-25 06:33:48 +00001055class LocalRewriter : public VirtRegRewriter {
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001056 MachineRegisterInfo *MRI;
Lang Hames87e3bca2009-05-06 02:36:21 +00001057 const TargetRegisterInfo *TRI;
1058 const TargetInstrInfo *TII;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001059 VirtRegMap *VRM;
Lang Hames87e3bca2009-05-06 02:36:21 +00001060 BitVector AllocatableRegs;
1061 DenseMap<MachineInstr*, unsigned> DistanceMap;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001062
1063 MachineBasicBlock *MBB; // Basic block currently being processed.
1064
Lang Hames87e3bca2009-05-06 02:36:21 +00001065public:
1066
1067 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001068 LiveIntervals* LIs);
Lang Hames87e3bca2009-05-06 02:36:21 +00001069
1070private:
1071
Lang Hames87e3bca2009-05-06 02:36:21 +00001072 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
Lang Hames87e3bca2009-05-06 02:36:21 +00001073 MachineBasicBlock::iterator &MII,
1074 std::vector<MachineInstr*> &MaybeDeadStores,
1075 AvailableSpills &Spills,
1076 BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001077 std::vector<MachineOperand*> &KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001078
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001079 bool OptimizeByUnfold(MachineBasicBlock::iterator &MII,
Lang Hames87e3bca2009-05-06 02:36:21 +00001080 std::vector<MachineInstr*> &MaybeDeadStores,
1081 AvailableSpills &Spills,
1082 BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001083 std::vector<MachineOperand*> &KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001084
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001085 bool CommuteToFoldReload(MachineBasicBlock::iterator &MII,
Lang Hames87e3bca2009-05-06 02:36:21 +00001086 unsigned VirtReg, unsigned SrcReg, int SS,
1087 AvailableSpills &Spills,
1088 BitVector &RegKills,
1089 std::vector<MachineOperand*> &KillOps,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001090 const TargetRegisterInfo *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001091
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001092 void SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
Lang Hames87e3bca2009-05-06 02:36:21 +00001093 int Idx, unsigned PhysReg, int StackSlot,
1094 const TargetRegisterClass *RC,
1095 bool isAvailable, MachineInstr *&LastStore,
1096 AvailableSpills &Spills,
1097 SmallSet<MachineInstr*, 4> &ReMatDefs,
1098 BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001099 std::vector<MachineOperand*> &KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001100
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001101 void TransferDeadness(unsigned Reg, BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001102 std::vector<MachineOperand*> &KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001103
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001104 bool InsertEmergencySpills(MachineInstr *MI);
1105
1106 bool InsertRestores(MachineInstr *MI,
1107 AvailableSpills &Spills,
1108 BitVector &RegKills,
1109 std::vector<MachineOperand*> &KillOps);
1110
1111 bool InsertSpills(MachineInstr *MI);
1112
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001113 void RewriteMBB(LiveIntervals *LIs,
1114 AvailableSpills &Spills, BitVector &RegKills,
1115 std::vector<MachineOperand*> &KillOps);
1116};
1117}
1118
1119bool LocalRewriter::runOnMachineFunction(MachineFunction &MF, VirtRegMap &vrm,
1120 LiveIntervals* LIs) {
1121 MRI = &MF.getRegInfo();
1122 TRI = MF.getTarget().getRegisterInfo();
1123 TII = MF.getTarget().getInstrInfo();
1124 VRM = &vrm;
1125 AllocatableRegs = TRI->getAllocatableSet(MF);
1126 DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
1127 << MF.getFunction()->getName() << "':\n");
1128 DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
1129 " reloads!) ****\n");
1130 DEBUG(MF.dump());
1131
1132 // Spills - Keep track of which spilled values are available in physregs
1133 // so that we can choose to reuse the physregs instead of emitting
1134 // reloads. This is usually refreshed per basic block.
1135 AvailableSpills Spills(TRI, TII);
1136
1137 // Keep track of kill information.
1138 BitVector RegKills(TRI->getNumRegs());
1139 std::vector<MachineOperand*> KillOps;
1140 KillOps.resize(TRI->getNumRegs(), NULL);
1141
1142 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1143 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1144 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1145
1146 // Traverse the basic blocks depth first.
1147 MachineBasicBlock *Entry = MF.begin();
1148 SmallPtrSet<MachineBasicBlock*,16> Visited;
1149 for (df_ext_iterator<MachineBasicBlock*,
1150 SmallPtrSet<MachineBasicBlock*,16> >
1151 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1152 DFI != E; ++DFI) {
1153 MBB = *DFI;
1154 if (!EarlyVisited.count(MBB))
1155 RewriteMBB(LIs, Spills, RegKills, KillOps);
1156
1157 // If this MBB is the only predecessor of a successor. Keep the
1158 // availability information and visit it next.
1159 do {
1160 // Keep visiting single predecessor successor as long as possible.
1161 SinglePredSuccs.clear();
1162 findSinglePredSuccessor(MBB, SinglePredSuccs);
1163 if (SinglePredSuccs.empty())
1164 MBB = 0;
1165 else {
1166 // FIXME: More than one successors, each of which has MBB has
1167 // the only predecessor.
1168 MBB = SinglePredSuccs[0];
1169 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1170 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1171 RewriteMBB(LIs, Spills, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001172 }
1173 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001174 } while (MBB);
Lang Hames87e3bca2009-05-06 02:36:21 +00001175
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001176 // Clear the availability info.
1177 Spills.clear();
Lang Hames87e3bca2009-05-06 02:36:21 +00001178 }
1179
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001180 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
1181 DEBUG(MF.dump());
1182
1183 // Mark unused spill slots.
1184 MachineFrameInfo *MFI = MF.getFrameInfo();
1185 int SS = VRM->getLowSpillSlot();
1186 if (SS != VirtRegMap::NO_STACK_SLOT)
1187 for (int e = VRM->getHighSpillSlot(); SS <= e; ++SS)
1188 if (!VRM->isSpillSlotUsed(SS)) {
1189 MFI->RemoveStackObject(SS);
1190 ++NumDSS;
1191 }
1192
1193 return true;
1194}
1195
1196/// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1197/// a scratch register is available.
1198/// xorq %r12<kill>, %r13
1199/// addq %rax, -184(%rbp)
1200/// addq %r13, -184(%rbp)
1201/// ==>
1202/// xorq %r12<kill>, %r13
1203/// movq -184(%rbp), %r12
1204/// addq %rax, %r12
1205/// addq %r13, %r12
1206/// movq %r12, -184(%rbp)
1207bool LocalRewriter::
1208OptimizeByUnfold2(unsigned VirtReg, int SS,
1209 MachineBasicBlock::iterator &MII,
1210 std::vector<MachineInstr*> &MaybeDeadStores,
1211 AvailableSpills &Spills,
1212 BitVector &RegKills,
1213 std::vector<MachineOperand*> &KillOps) {
1214
1215 MachineBasicBlock::iterator NextMII = llvm::next(MII);
1216 if (NextMII == MBB->end())
1217 return false;
1218
1219 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1220 return false;
1221
1222 // Now let's see if the last couple of instructions happens to have freed up
1223 // a register.
1224 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1225 unsigned PhysReg = FindFreeRegister(MII, *MBB, RC, TRI, AllocatableRegs);
1226 if (!PhysReg)
1227 return false;
1228
1229 MachineFunction &MF = *MBB->getParent();
1230 TRI = MF.getTarget().getRegisterInfo();
1231 MachineInstr &MI = *MII;
1232 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, *VRM))
1233 return false;
1234
1235 // If the next instruction also folds the same SS modref and can be unfoled,
1236 // then it's worthwhile to issue a load from SS into the free register and
1237 // then unfold these instructions.
1238 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM))
1239 return false;
1240
1241 // Back-schedule reloads and remats.
1242 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, false, SS, TII, MF);
1243
1244 // Load from SS to the spare physical register.
1245 TII->loadRegFromStackSlot(*MBB, MII, PhysReg, SS, RC);
1246 // This invalidates Phys.
1247 Spills.ClobberPhysReg(PhysReg);
1248 // Remember it's available.
1249 Spills.addAvailable(SS, PhysReg);
1250 MaybeDeadStores[SS] = NULL;
1251
1252 // Unfold current MI.
1253 SmallVector<MachineInstr*, 4> NewMIs;
1254 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
1255 llvm_unreachable("Unable unfold the load / store folding instruction!");
1256 assert(NewMIs.size() == 1);
1257 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1258 VRM->transferRestorePts(&MI, NewMIs[0]);
1259 MII = MBB->insert(MII, NewMIs[0]);
1260 InvalidateKills(MI, TRI, RegKills, KillOps);
1261 VRM->RemoveMachineInstrFromMaps(&MI);
1262 MBB->erase(&MI);
1263 ++NumModRefUnfold;
1264
1265 // Unfold next instructions that fold the same SS.
1266 do {
1267 MachineInstr &NextMI = *NextMII;
1268 NextMII = llvm::next(NextMII);
1269 NewMIs.clear();
1270 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
1271 llvm_unreachable("Unable unfold the load / store folding instruction!");
1272 assert(NewMIs.size() == 1);
1273 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
1274 VRM->transferRestorePts(&NextMI, NewMIs[0]);
1275 MBB->insert(NextMII, NewMIs[0]);
1276 InvalidateKills(NextMI, TRI, RegKills, KillOps);
1277 VRM->RemoveMachineInstrFromMaps(&NextMI);
1278 MBB->erase(&NextMI);
1279 ++NumModRefUnfold;
1280 if (NextMII == MBB->end())
1281 break;
1282 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, *VRM));
1283
1284 // Store the value back into SS.
1285 TII->storeRegToStackSlot(*MBB, NextMII, PhysReg, true, SS, RC);
1286 MachineInstr *StoreMI = prior(NextMII);
1287 VRM->addSpillSlotUse(SS, StoreMI);
1288 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1289
1290 return true;
1291}
1292
1293/// OptimizeByUnfold - Turn a store folding instruction into a load folding
1294/// instruction. e.g.
1295/// xorl %edi, %eax
1296/// movl %eax, -32(%ebp)
1297/// movl -36(%ebp), %eax
1298/// orl %eax, -32(%ebp)
1299/// ==>
1300/// xorl %edi, %eax
1301/// orl -36(%ebp), %eax
1302/// mov %eax, -32(%ebp)
1303/// This enables unfolding optimization for a subsequent instruction which will
1304/// also eliminate the newly introduced store instruction.
1305bool LocalRewriter::
1306OptimizeByUnfold(MachineBasicBlock::iterator &MII,
1307 std::vector<MachineInstr*> &MaybeDeadStores,
1308 AvailableSpills &Spills,
1309 BitVector &RegKills,
1310 std::vector<MachineOperand*> &KillOps) {
1311 MachineFunction &MF = *MBB->getParent();
1312 MachineInstr &MI = *MII;
1313 unsigned UnfoldedOpc = 0;
1314 unsigned UnfoldPR = 0;
1315 unsigned UnfoldVR = 0;
1316 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1317 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1318 for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
1319 // Only transform a MI that folds a single register.
1320 if (UnfoldedOpc)
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001321 return false;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001322 UnfoldVR = I->second.first;
1323 VirtRegMap::ModRef MR = I->second.second;
1324 // MI2VirtMap be can updated which invalidate the iterator.
1325 // Increment the iterator first.
1326 ++I;
1327 if (VRM->isAssignedReg(UnfoldVR))
1328 continue;
1329 // If this reference is not a use, any previous store is now dead.
1330 // Otherwise, the store to this stack slot is not dead anymore.
1331 FoldedSS = VRM->getStackSlot(UnfoldVR);
1332 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1333 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1334 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1335 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001336 continue;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001337 UnfoldPR = PhysReg;
1338 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1339 false, true);
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001340 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001341 }
1342
1343 if (!UnfoldedOpc) {
1344 if (!UnfoldVR)
1345 return false;
1346
1347 // Look for other unfolding opportunities.
1348 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MII, MaybeDeadStores, Spills,
1349 RegKills, KillOps);
1350 }
1351
1352 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1353 MachineOperand &MO = MI.getOperand(i);
1354 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1355 continue;
1356 unsigned VirtReg = MO.getReg();
1357 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1358 continue;
1359 if (VRM->isAssignedReg(VirtReg)) {
1360 unsigned PhysReg = VRM->getPhys(VirtReg);
1361 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1362 return false;
1363 } else if (VRM->isReMaterialized(VirtReg))
1364 continue;
1365 int SS = VRM->getStackSlot(VirtReg);
1366 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1367 if (PhysReg) {
1368 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1369 return false;
1370 continue;
1371 }
1372 if (VRM->hasPhys(VirtReg)) {
1373 PhysReg = VRM->getPhys(VirtReg);
1374 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1375 continue;
1376 }
1377
1378 // Ok, we'll need to reload the value into a register which makes
1379 // it impossible to perform the store unfolding optimization later.
1380 // Let's see if it is possible to fold the load if the store is
1381 // unfolded. This allows us to perform the store unfolding
1382 // optimization.
1383 SmallVector<MachineInstr*, 4> NewMIs;
1384 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1385 assert(NewMIs.size() == 1);
1386 MachineInstr *NewMI = NewMIs.back();
1387 NewMIs.clear();
1388 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1389 assert(Idx != -1);
1390 SmallVector<unsigned, 1> Ops;
1391 Ops.push_back(Idx);
1392 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1393 if (FoldedMI) {
1394 VRM->addSpillSlotUse(SS, FoldedMI);
1395 if (!VRM->hasPhys(UnfoldVR))
1396 VRM->assignVirt2Phys(UnfoldVR, UnfoldPR);
1397 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1398 MII = MBB->insert(MII, FoldedMI);
1399 InvalidateKills(MI, TRI, RegKills, KillOps);
1400 VRM->RemoveMachineInstrFromMaps(&MI);
1401 MBB->erase(&MI);
1402 MF.DeleteMachineInstr(NewMI);
1403 return true;
1404 }
1405 MF.DeleteMachineInstr(NewMI);
1406 }
1407 }
1408
1409 return false;
1410}
1411
1412/// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1413/// where SrcReg is r1 and it is tied to r0. Return true if after
1414/// commuting this instruction it will be r0 = op r2, r1.
1415static bool CommuteChangesDestination(MachineInstr *DefMI,
1416 const TargetInstrDesc &TID,
1417 unsigned SrcReg,
1418 const TargetInstrInfo *TII,
1419 unsigned &DstIdx) {
1420 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1421 return false;
1422 if (!DefMI->getOperand(1).isReg() ||
1423 DefMI->getOperand(1).getReg() != SrcReg)
1424 return false;
1425 unsigned DefIdx;
1426 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1427 return false;
1428 unsigned SrcIdx1, SrcIdx2;
1429 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1430 return false;
1431 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1432 DstIdx = 2;
1433 return true;
1434 }
1435 return false;
1436}
1437
1438/// CommuteToFoldReload -
1439/// Look for
1440/// r1 = load fi#1
1441/// r1 = op r1, r2<kill>
1442/// store r1, fi#1
1443///
1444/// If op is commutable and r2 is killed, then we can xform these to
1445/// r2 = op r2, fi#1
1446/// store r2, fi#1
1447bool LocalRewriter::
1448CommuteToFoldReload(MachineBasicBlock::iterator &MII,
1449 unsigned VirtReg, unsigned SrcReg, int SS,
1450 AvailableSpills &Spills,
1451 BitVector &RegKills,
1452 std::vector<MachineOperand*> &KillOps,
1453 const TargetRegisterInfo *TRI) {
1454 if (MII == MBB->begin() || !MII->killsRegister(SrcReg))
1455 return false;
1456
1457 MachineFunction &MF = *MBB->getParent();
1458 MachineInstr &MI = *MII;
1459 MachineBasicBlock::iterator DefMII = prior(MII);
1460 MachineInstr *DefMI = DefMII;
1461 const TargetInstrDesc &TID = DefMI->getDesc();
1462 unsigned NewDstIdx;
1463 if (DefMII != MBB->begin() &&
1464 TID.isCommutable() &&
1465 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
1466 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1467 unsigned NewReg = NewDstMO.getReg();
1468 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1469 return false;
1470 MachineInstr *ReloadMI = prior(DefMII);
1471 int FrameIdx;
1472 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1473 if (DestReg != SrcReg || FrameIdx != SS)
1474 return false;
1475 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1476 if (UseIdx == -1)
1477 return false;
1478 unsigned DefIdx;
1479 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1480 return false;
1481 assert(DefMI->getOperand(DefIdx).isReg() &&
1482 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1483
1484 // Now commute def instruction.
1485 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1486 if (!CommutedMI)
1487 return false;
1488 SmallVector<unsigned, 1> Ops;
1489 Ops.push_back(NewDstIdx);
1490 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1491 // Not needed since foldMemoryOperand returns new MI.
1492 MF.DeleteMachineInstr(CommutedMI);
1493 if (!FoldedMI)
1494 return false;
1495
1496 VRM->addSpillSlotUse(SS, FoldedMI);
1497 VRM->virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1498 // Insert new def MI and spill MI.
1499 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1500 TII->storeRegToStackSlot(*MBB, &MI, NewReg, true, SS, RC);
1501 MII = prior(MII);
1502 MachineInstr *StoreMI = MII;
1503 VRM->addSpillSlotUse(SS, StoreMI);
1504 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1505 MII = MBB->insert(MII, FoldedMI); // Update MII to backtrack.
1506
1507 // Delete all 3 old instructions.
1508 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
1509 VRM->RemoveMachineInstrFromMaps(ReloadMI);
1510 MBB->erase(ReloadMI);
1511 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
1512 VRM->RemoveMachineInstrFromMaps(DefMI);
1513 MBB->erase(DefMI);
1514 InvalidateKills(MI, TRI, RegKills, KillOps);
1515 VRM->RemoveMachineInstrFromMaps(&MI);
1516 MBB->erase(&MI);
1517
1518 // If NewReg was previously holding value of some SS, it's now clobbered.
1519 // This has to be done now because it's a physical register. When this
1520 // instruction is re-visited, it's ignored.
1521 Spills.ClobberPhysReg(NewReg);
1522
1523 ++NumCommutes;
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001524 return true;
1525 }
1526
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001527 return false;
1528}
Lang Hames87e3bca2009-05-06 02:36:21 +00001529
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001530/// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1531/// the last store to the same slot is now dead. If so, remove the last store.
1532void LocalRewriter::
1533SpillRegToStackSlot(MachineBasicBlock::iterator &MII,
1534 int Idx, unsigned PhysReg, int StackSlot,
1535 const TargetRegisterClass *RC,
1536 bool isAvailable, MachineInstr *&LastStore,
1537 AvailableSpills &Spills,
1538 SmallSet<MachineInstr*, 4> &ReMatDefs,
1539 BitVector &RegKills,
1540 std::vector<MachineOperand*> &KillOps) {
Evan Chengeca24fb2009-05-12 23:07:00 +00001541
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001542 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1543 TII->storeRegToStackSlot(*MBB, llvm::next(MII), PhysReg, true, StackSlot, RC);
1544 MachineInstr *StoreMI = prior(oldNextMII);
1545 VRM->addSpillSlotUse(StackSlot, StoreMI);
1546 DEBUG(dbgs() << "Store:\t" << *StoreMI);
Evan Chengeca24fb2009-05-12 23:07:00 +00001547
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001548 // If there is a dead store to this stack slot, nuke it now.
1549 if (LastStore) {
1550 DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
1551 ++NumDSE;
1552 SmallVector<unsigned, 2> KillRegs;
1553 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
1554 MachineBasicBlock::iterator PrevMII = LastStore;
1555 bool CheckDef = PrevMII != MBB->begin();
1556 if (CheckDef)
1557 --PrevMII;
1558 VRM->RemoveMachineInstrFromMaps(LastStore);
1559 MBB->erase(LastStore);
1560 if (CheckDef) {
1561 // Look at defs of killed registers on the store. Mark the defs
1562 // as dead since the store has been deleted and they aren't
1563 // being reused.
1564 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1565 bool HasOtherDef = false;
1566 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
1567 MachineInstr *DeadDef = PrevMII;
1568 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
1569 // FIXME: This assumes a remat def does not have side effects.
1570 VRM->RemoveMachineInstrFromMaps(DeadDef);
1571 MBB->erase(DeadDef);
1572 ++NumDRM;
1573 }
Evan Chengeca24fb2009-05-12 23:07:00 +00001574 }
Lang Hames87e3bca2009-05-06 02:36:21 +00001575 }
1576 }
1577 }
1578
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001579 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1580 // the last of multiple instructions is the actual store.
1581 LastStore = prior(oldNextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001582
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001583 // If the stack slot value was previously available in some other
1584 // register, change it now. Otherwise, make the register available,
1585 // in PhysReg.
1586 Spills.ModifyStackSlotOrReMat(StackSlot);
1587 Spills.ClobberPhysReg(PhysReg);
1588 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1589 ++NumStores;
1590}
Lang Hames87e3bca2009-05-06 02:36:21 +00001591
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001592/// isSafeToDelete - Return true if this instruction doesn't produce any side
1593/// effect and all of its defs are dead.
1594static bool isSafeToDelete(MachineInstr &MI) {
1595 const TargetInstrDesc &TID = MI.getDesc();
1596 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1597 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1598 TID.hasUnmodeledSideEffects())
1599 return false;
1600 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1601 MachineOperand &MO = MI.getOperand(i);
1602 if (!MO.isReg() || !MO.getReg())
1603 continue;
1604 if (MO.isDef() && !MO.isDead())
1605 return false;
1606 if (MO.isUse() && MO.isKill())
1607 // FIXME: We can't remove kill markers or else the scavenger will assert.
1608 // An alternative is to add a ADD pseudo instruction to replace kill
1609 // markers.
1610 return false;
1611 }
1612 return true;
1613}
Lang Hames87e3bca2009-05-06 02:36:21 +00001614
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001615/// TransferDeadness - A identity copy definition is dead and it's being
1616/// removed. Find the last def or use and mark it as dead / kill.
1617void LocalRewriter::
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001618TransferDeadness(unsigned Reg, BitVector &RegKills,
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001619 std::vector<MachineOperand*> &KillOps) {
1620 SmallPtrSet<MachineInstr*, 4> Seens;
1621 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
1622 for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(Reg),
1623 RE = MRI->reg_end(); RI != RE; ++RI) {
1624 MachineInstr *UDMI = &*RI;
1625 if (UDMI->getParent() != MBB)
1626 continue;
1627 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001628 if (DI == DistanceMap.end())
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001629 continue;
1630 if (Seens.insert(UDMI))
1631 Refs.push_back(std::make_pair(UDMI, DI->second));
1632 }
Lang Hames87e3bca2009-05-06 02:36:21 +00001633
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001634 if (Refs.empty())
1635 return;
1636 std::sort(Refs.begin(), Refs.end(), RefSorter());
Lang Hames87e3bca2009-05-06 02:36:21 +00001637
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001638 while (!Refs.empty()) {
1639 MachineInstr *LastUDMI = Refs.back().first;
1640 Refs.pop_back();
Lang Hames87e3bca2009-05-06 02:36:21 +00001641
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001642 MachineOperand *LastUD = NULL;
1643 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1644 MachineOperand &MO = LastUDMI->getOperand(i);
1645 if (!MO.isReg() || MO.getReg() != Reg)
1646 continue;
1647 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1648 LastUD = &MO;
1649 if (LastUDMI->isRegTiedToDefOperand(i))
1650 break;
1651 }
1652 if (LastUD->isDef()) {
1653 // If the instruction has no side effect, delete it and propagate
1654 // backward further. Otherwise, mark is dead and we are done.
1655 if (!isSafeToDelete(*LastUDMI)) {
1656 LastUD->setIsDead();
1657 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001658 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001659 VRM->RemoveMachineInstrFromMaps(LastUDMI);
1660 MBB->erase(LastUDMI);
1661 } else {
1662 LastUD->setIsKill();
1663 RegKills.set(Reg);
1664 KillOps[Reg] = LastUD;
1665 break;
1666 }
1667 }
1668}
Lang Hames87e3bca2009-05-06 02:36:21 +00001669
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001670/// InsertEmergencySpills - Insert emergency spills before MI if requested by
1671/// VRM. Return true if spills were inserted.
1672bool LocalRewriter::InsertEmergencySpills(MachineInstr *MI) {
1673 if (!VRM->hasEmergencySpills(MI))
1674 return false;
1675 MachineBasicBlock::iterator MII = MI;
1676 SmallSet<int, 4> UsedSS;
1677 std::vector<unsigned> &EmSpills = VRM->getEmergencySpills(MI);
1678 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1679 unsigned PhysReg = EmSpills[i];
1680 const TargetRegisterClass *RC = TRI->getPhysicalRegisterRegClass(PhysReg);
1681 assert(RC && "Unable to determine register class!");
1682 int SS = VRM->getEmergencySpillSlot(RC);
1683 if (UsedSS.count(SS))
1684 llvm_unreachable("Need to spill more than one physical registers!");
1685 UsedSS.insert(SS);
1686 TII->storeRegToStackSlot(*MBB, MII, PhysReg, true, SS, RC);
1687 MachineInstr *StoreMI = prior(MII);
1688 VRM->addSpillSlotUse(SS, StoreMI);
1689
1690 // Back-schedule reloads and remats.
1691 MachineBasicBlock::iterator InsertLoc =
1692 ComputeReloadLoc(llvm::next(MII), MBB->begin(), PhysReg, TRI, false, SS,
1693 TII, *MBB->getParent());
1694
1695 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SS, RC);
1696
1697 MachineInstr *LoadMI = prior(InsertLoc);
1698 VRM->addSpillSlotUse(SS, LoadMI);
1699 ++NumPSpills;
1700 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1701 }
1702 return true;
1703}
1704
1705/// InsertRestores - Restore registers before MI is requested by VRM. Return
1706/// true is any instructions were inserted.
1707bool LocalRewriter::InsertRestores(MachineInstr *MI,
1708 AvailableSpills &Spills,
1709 BitVector &RegKills,
1710 std::vector<MachineOperand*> &KillOps) {
1711 if (!VRM->isRestorePt(MI))
1712 return false;
1713 MachineBasicBlock::iterator MII = MI;
1714 std::vector<unsigned> &RestoreRegs = VRM->getRestorePtRestores(MI);
1715 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1716 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1717 if (!VRM->getPreSplitReg(VirtReg))
1718 continue; // Split interval spilled again.
1719 unsigned Phys = VRM->getPhys(VirtReg);
1720 MRI->setPhysRegUsed(Phys);
1721
1722 // Check if the value being restored if available. If so, it must be
1723 // from a predecessor BB that fallthrough into this BB. We do not
1724 // expect:
1725 // BB1:
1726 // r1 = load fi#1
1727 // ...
1728 // = r1<kill>
1729 // ... # r1 not clobbered
1730 // ...
1731 // = load fi#1
1732 bool DoReMat = VRM->isReMaterialized(VirtReg);
1733 int SSorRMId = DoReMat
1734 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1735 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1736 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1737 if (InReg == Phys) {
1738 // If the value is already available in the expected register, save
1739 // a reload / remat.
1740 if (SSorRMId)
1741 DEBUG(dbgs() << "Reusing RM#"
1742 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1743 else
1744 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1745 DEBUG(dbgs() << " from physreg "
1746 << TRI->getName(InReg) << " for vreg"
1747 << VirtReg <<" instead of reloading into physreg "
1748 << TRI->getName(Phys) << '\n');
1749 ++NumOmitted;
1750 continue;
1751 } else if (InReg && InReg != Phys) {
1752 if (SSorRMId)
1753 DEBUG(dbgs() << "Reusing RM#"
1754 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
1755 else
1756 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1757 DEBUG(dbgs() << " from physreg "
1758 << TRI->getName(InReg) << " for vreg"
1759 << VirtReg <<" by copying it into physreg "
1760 << TRI->getName(Phys) << '\n');
1761
1762 // If the reloaded / remat value is available in another register,
1763 // copy it to the desired register.
1764
1765 // Back-schedule reloads and remats.
1766 MachineBasicBlock::iterator InsertLoc =
1767 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1768 *MBB->getParent());
1769
1770 TII->copyRegToReg(*MBB, InsertLoc, Phys, InReg, RC, RC);
1771
1772 // This invalidates Phys.
1773 Spills.ClobberPhysReg(Phys);
1774 // Remember it's available.
1775 Spills.addAvailable(SSorRMId, Phys);
1776
1777 // Mark is killed.
1778 MachineInstr *CopyMI = prior(InsertLoc);
1779 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
1780 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1781 KillOpnd->setIsKill();
1782 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
1783
1784 DEBUG(dbgs() << '\t' << *CopyMI);
1785 ++NumCopified;
1786 continue;
1787 }
1788
1789 // Back-schedule reloads and remats.
1790 MachineBasicBlock::iterator InsertLoc =
1791 ComputeReloadLoc(MII, MBB->begin(), Phys, TRI, DoReMat, SSorRMId, TII,
1792 *MBB->getParent());
1793
1794 if (VRM->isReMaterialized(VirtReg)) {
1795 ReMaterialize(*MBB, InsertLoc, Phys, VirtReg, TII, TRI, *VRM);
1796 } else {
1797 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1798 TII->loadRegFromStackSlot(*MBB, InsertLoc, Phys, SSorRMId, RC);
1799 MachineInstr *LoadMI = prior(InsertLoc);
1800 VRM->addSpillSlotUse(SSorRMId, LoadMI);
1801 ++NumLoads;
1802 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
1803 }
1804
1805 // This invalidates Phys.
1806 Spills.ClobberPhysReg(Phys);
1807 // Remember it's available.
1808 Spills.addAvailable(SSorRMId, Phys);
1809
1810 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
1811 DEBUG(dbgs() << '\t' << *prior(MII));
1812 }
1813 return true;
1814}
1815
1816/// InsertEmergencySpills - Insert spills after MI if requested by VRM. Return
1817/// true if spills were inserted.
1818bool LocalRewriter::InsertSpills(MachineInstr *MI) {
1819 if (!VRM->isSpillPt(MI))
1820 return false;
1821 MachineBasicBlock::iterator MII = MI;
1822 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1823 VRM->getSpillPtSpills(MI);
1824 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1825 unsigned VirtReg = SpillRegs[i].first;
1826 bool isKill = SpillRegs[i].second;
1827 if (!VRM->getPreSplitReg(VirtReg))
1828 continue; // Split interval spilled again.
1829 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
1830 unsigned Phys = VRM->getPhys(VirtReg);
1831 int StackSlot = VRM->getStackSlot(VirtReg);
1832 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1833 TII->storeRegToStackSlot(*MBB, llvm::next(MII), Phys, isKill, StackSlot,
1834 RC);
1835 MachineInstr *StoreMI = prior(oldNextMII);
1836 VRM->addSpillSlotUse(StackSlot, StoreMI);
1837 DEBUG(dbgs() << "Store:\t" << *StoreMI);
1838 VRM->virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1839 }
1840 return true;
1841}
1842
1843
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001844/// rewriteMBB - Keep track of which spills are available even after the
1845/// register allocator is done with them. If possible, avid reloading vregs.
1846void
1847LocalRewriter::RewriteMBB(LiveIntervals *LIs,
1848 AvailableSpills &Spills, BitVector &RegKills,
1849 std::vector<MachineOperand*> &KillOps) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001850
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001851 DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
1852 << MBB->getName() << "':\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001853
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001854 MachineFunction &MF = *MBB->getParent();
David Greene2d4e6d32009-07-28 16:49:24 +00001855
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001856 // MaybeDeadStores - When we need to write a value back into a stack slot,
1857 // keep track of the inserted store. If the stack slot value is never read
1858 // (because the value was used from some available register, for example), and
1859 // subsequently stored to, the original store is dead. This map keeps track
1860 // of inserted stores that are not used. If we see a subsequent store to the
1861 // same stack slot, the original store is deleted.
1862 std::vector<MachineInstr*> MaybeDeadStores;
1863 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
David Greene2d4e6d32009-07-28 16:49:24 +00001864
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001865 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1866 SmallSet<MachineInstr*, 4> ReMatDefs;
Lang Hames87e3bca2009-05-06 02:36:21 +00001867
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001868 // Clear kill info.
1869 SmallSet<unsigned, 2> KilledMIRegs;
1870 RegKills.reset();
1871 KillOps.clear();
1872 KillOps.resize(TRI->getNumRegs(), NULL);
Lang Hames87e3bca2009-05-06 02:36:21 +00001873
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001874 DistanceMap.clear();
1875 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1876 MII != E; ) {
1877 MachineBasicBlock::iterator NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001878
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001879 if (OptimizeByUnfold(MII, MaybeDeadStores, Spills, RegKills, KillOps))
1880 NextMII = llvm::next(MII);
1881
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00001882 if (InsertEmergencySpills(MII))
1883 NextMII = llvm::next(MII);
1884
1885 InsertRestores(MII, Spills, RegKills, KillOps);
1886
1887 if (InsertSpills(MII))
1888 NextMII = llvm::next(MII);
1889
1890 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1891 bool Erased = false;
1892 bool BackTracked = false;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001893 MachineInstr &MI = *MII;
1894
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00001895 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1896 /// reuse.
1897 ReuseInfo ReusedOperands(MI, TRI);
1898 SmallVector<unsigned, 4> VirtUseOps;
1899 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1900 MachineOperand &MO = MI.getOperand(i);
1901 if (!MO.isReg() || MO.getReg() == 0)
1902 continue; // Ignore non-register operands.
1903
1904 unsigned VirtReg = MO.getReg();
1905 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1906 // Ignore physregs for spilling, but remember that it is used by this
1907 // function.
1908 MRI->setPhysRegUsed(VirtReg);
1909 continue;
1910 }
1911
1912 // We want to process implicit virtual register uses first.
1913 if (MO.isImplicit())
1914 // If the virtual register is implicitly defined, emit a implicit_def
1915 // before so scavenger knows it's "defined".
1916 // FIXME: This is a horrible hack done the by register allocator to
1917 // remat a definition with virtual register operand.
1918 VirtUseOps.insert(VirtUseOps.begin(), i);
1919 else
1920 VirtUseOps.push_back(i);
1921 }
1922
1923 // Process all of the spilled uses and all non spilled reg references.
1924 SmallVector<int, 2> PotentialDeadStoreSlots;
1925 KilledMIRegs.clear();
1926 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1927 unsigned i = VirtUseOps[j];
1928 unsigned VirtReg = MI.getOperand(i).getReg();
1929 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1930 "Not a virtual register?");
1931
1932 unsigned SubIdx = MI.getOperand(i).getSubReg();
1933 if (VRM->isAssignedReg(VirtReg)) {
1934 // This virtual register was assigned a physreg!
1935 unsigned Phys = VRM->getPhys(VirtReg);
1936 MRI->setPhysRegUsed(Phys);
1937 if (MI.getOperand(i).isDef())
1938 ReusedOperands.markClobbered(Phys);
1939 substitutePhysReg(MI.getOperand(i), Phys, *TRI);
1940 if (VRM->isImplicitlyDefined(VirtReg))
1941 // FIXME: Is this needed?
1942 BuildMI(*MBB, &MI, MI.getDebugLoc(),
1943 TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
1944 continue;
1945 }
1946
1947 // This virtual register is now known to be a spilled value.
1948 if (!MI.getOperand(i).isUse())
1949 continue; // Handle defs in the loop below (handle use&def here though)
1950
1951 bool AvoidReload = MI.getOperand(i).isUndef();
1952 // Check if it is defined by an implicit def. It should not be spilled.
1953 // Note, this is for correctness reason. e.g.
1954 // 8 %reg1024<def> = IMPLICIT_DEF
1955 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1956 // The live range [12, 14) are not part of the r1024 live interval since
1957 // it's defined by an implicit def. It will not conflicts with live
1958 // interval of r1025. Now suppose both registers are spilled, you can
1959 // easily see a situation where both registers are reloaded before
1960 // the INSERT_SUBREG and both target registers that would overlap.
1961 bool DoReMat = VRM->isReMaterialized(VirtReg);
1962 int SSorRMId = DoReMat
1963 ? VRM->getReMatId(VirtReg) : VRM->getStackSlot(VirtReg);
1964 int ReuseSlot = SSorRMId;
1965
1966 // Check to see if this stack slot is available.
1967 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1968
1969 // If this is a sub-register use, make sure the reuse register is in the
1970 // right register class. For example, for x86 not all of the 32-bit
1971 // registers have accessible sub-registers.
1972 // Similarly so for EXTRACT_SUBREG. Consider this:
1973 // EDI = op
1974 // MOV32_mr fi#1, EDI
1975 // ...
1976 // = EXTRACT_SUBREG fi#1
1977 // fi#1 is available in EDI, but it cannot be reused because it's not in
1978 // the right register file.
1979 if (PhysReg && !AvoidReload && (SubIdx || MI.isExtractSubreg())) {
1980 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
1981 if (!RC->contains(PhysReg))
1982 PhysReg = 0;
1983 }
1984
1985 if (PhysReg && !AvoidReload) {
1986 // This spilled operand might be part of a two-address operand. If this
1987 // is the case, then changing it will necessarily require changing the
1988 // def part of the instruction as well. However, in some cases, we
1989 // aren't allowed to modify the reused register. If none of these cases
1990 // apply, reuse it.
1991 bool CanReuse = true;
1992 bool isTied = MI.isRegTiedToDefOperand(i);
1993 if (isTied) {
1994 // Okay, we have a two address operand. We can reuse this physreg as
1995 // long as we are allowed to clobber the value and there isn't an
1996 // earlier def that has already clobbered the physreg.
1997 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1998 Spills.canClobberPhysReg(PhysReg);
1999 }
2000
2001 if (CanReuse) {
2002 // If this stack slot value is already available, reuse it!
2003 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2004 DEBUG(dbgs() << "Reusing RM#"
2005 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2006 else
2007 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2008 DEBUG(dbgs() << " from physreg "
2009 << TRI->getName(PhysReg) << " for vreg"
2010 << VirtReg <<" instead of reloading into physreg "
2011 << TRI->getName(VRM->getPhys(VirtReg)) << '\n');
2012 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
Lang Hames87e3bca2009-05-06 02:36:21 +00002013 MI.getOperand(i).setReg(RReg);
2014 MI.getOperand(i).setSubReg(0);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002015
2016 // The only technical detail we have is that we don't know that
2017 // PhysReg won't be clobbered by a reloaded stack slot that occurs
2018 // later in the instruction. In particular, consider 'op V1, V2'.
2019 // If V1 is available in physreg R0, we would choose to reuse it
2020 // here, instead of reloading it into the register the allocator
2021 // indicated (say R1). However, V2 might have to be reloaded
2022 // later, and it might indicate that it needs to live in R0. When
2023 // this occurs, we need to have information available that
2024 // indicates it is safe to use R1 for the reload instead of R0.
2025 //
2026 // To further complicate matters, we might conflict with an alias,
2027 // or R0 and R1 might not be compatible with each other. In this
2028 // case, we actually insert a reload for V1 in R1, ensuring that
2029 // we can get at R0 or its alias.
2030 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
2031 VRM->getPhys(VirtReg), VirtReg);
2032 if (isTied)
2033 // Only mark it clobbered if this is a use&def operand.
2034 ReusedOperands.markClobbered(PhysReg);
Lang Hames87e3bca2009-05-06 02:36:21 +00002035 ++NumReused;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002036
2037 if (MI.getOperand(i).isKill() &&
2038 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
2039
2040 // The store of this spilled value is potentially dead, but we
2041 // won't know for certain until we've confirmed that the re-use
2042 // above is valid, which means waiting until the other operands
2043 // are processed. For now we just track the spill slot, we'll
2044 // remove it after the other operands are processed if valid.
2045
2046 PotentialDeadStoreSlots.push_back(ReuseSlot);
2047 }
2048
2049 // Mark is isKill if it's there no other uses of the same virtual
2050 // register and it's not a two-address operand. IsKill will be
2051 // unset if reg is reused.
2052 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
2053 MI.getOperand(i).setIsKill();
2054 KilledMIRegs.insert(VirtReg);
2055 }
2056
Lang Hames87e3bca2009-05-06 02:36:21 +00002057 continue;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002058 } // CanReuse
2059
2060 // Otherwise we have a situation where we have a two-address instruction
2061 // whose mod/ref operand needs to be reloaded. This reload is already
2062 // available in some register "PhysReg", but if we used PhysReg as the
2063 // operand to our 2-addr instruction, the instruction would modify
2064 // PhysReg. This isn't cool if something later uses PhysReg and expects
2065 // to get its initial value.
2066 //
2067 // To avoid this problem, and to avoid doing a load right after a store,
2068 // we emit a copy from PhysReg into the designated register for this
2069 // operand.
2070 unsigned DesignatedReg = VRM->getPhys(VirtReg);
2071 assert(DesignatedReg && "Must map virtreg to physreg!");
Lang Hames87e3bca2009-05-06 02:36:21 +00002072
2073 // Note that, if we reused a register for a previous operand, the
2074 // register we want to reload into might not actually be
2075 // available. If this occurs, use the register indicated by the
2076 // reuser.
2077 if (ReusedOperands.hasReuses())
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002078 DesignatedReg = ReusedOperands.
2079 GetRegForReload(VirtReg, DesignatedReg, &MI, Spills,
2080 MaybeDeadStores, RegKills, KillOps, *VRM);
David Greene2d4e6d32009-07-28 16:49:24 +00002081
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002082 // If the mapped designated register is actually the physreg we have
2083 // incoming, we don't need to inserted a dead copy.
2084 if (DesignatedReg == PhysReg) {
2085 // If this stack slot value is already available, reuse it!
2086 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
2087 DEBUG(dbgs() << "Reusing RM#"
2088 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
2089 else
2090 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2091 DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
2092 << " for vreg" << VirtReg
2093 << " instead of reloading into same physreg.\n");
2094 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2095 MI.getOperand(i).setReg(RReg);
2096 MI.getOperand(i).setSubReg(0);
2097 ReusedOperands.markClobbered(RReg);
2098 ++NumReused;
2099 continue;
Lang Hames87e3bca2009-05-06 02:36:21 +00002100 }
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002101
2102 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2103 MRI->setPhysRegUsed(DesignatedReg);
2104 ReusedOperands.markClobbered(DesignatedReg);
2105
2106 // Back-schedule reloads and remats.
2107 MachineBasicBlock::iterator InsertLoc =
2108 ComputeReloadLoc(&MI, MBB->begin(), PhysReg, TRI, DoReMat,
2109 SSorRMId, TII, MF);
2110
2111 TII->copyRegToReg(*MBB, InsertLoc, DesignatedReg, PhysReg, RC, RC);
2112
2113 MachineInstr *CopyMI = prior(InsertLoc);
2114 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2115 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
2116
2117 // This invalidates DesignatedReg.
2118 Spills.ClobberPhysReg(DesignatedReg);
2119
2120 Spills.addAvailable(ReuseSlot, DesignatedReg);
2121 unsigned RReg =
2122 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
Lang Hames87e3bca2009-05-06 02:36:21 +00002123 MI.getOperand(i).setReg(RReg);
2124 MI.getOperand(i).setSubReg(0);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002125 DEBUG(dbgs() << '\t' << *prior(MII));
2126 ++NumReused;
2127 continue;
2128 } // if (PhysReg)
Lang Hames87e3bca2009-05-06 02:36:21 +00002129
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002130 // Otherwise, reload it and remember that we have it.
2131 PhysReg = VRM->getPhys(VirtReg);
2132 assert(PhysReg && "Must map virtreg to physreg!");
2133
2134 // Note that, if we reused a register for a previous operand, the
2135 // register we want to reload into might not actually be
2136 // available. If this occurs, use the register indicated by the
2137 // reuser.
2138 if (ReusedOperands.hasReuses())
2139 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2140 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2141
2142 MRI->setPhysRegUsed(PhysReg);
2143 ReusedOperands.markClobbered(PhysReg);
2144 if (AvoidReload)
2145 ++NumAvoided;
2146 else {
2147 // Back-schedule reloads and remats.
2148 MachineBasicBlock::iterator InsertLoc =
2149 ComputeReloadLoc(MII, MBB->begin(), PhysReg, TRI, DoReMat,
2150 SSorRMId, TII, MF);
2151
2152 if (DoReMat) {
2153 ReMaterialize(*MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, *VRM);
2154 } else {
2155 const TargetRegisterClass* RC = MRI->getRegClass(VirtReg);
2156 TII->loadRegFromStackSlot(*MBB, InsertLoc, PhysReg, SSorRMId, RC);
2157 MachineInstr *LoadMI = prior(InsertLoc);
2158 VRM->addSpillSlotUse(SSorRMId, LoadMI);
2159 ++NumLoads;
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00002160 DistanceMap.insert(std::make_pair(LoadMI, DistanceMap.size()));
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002161 }
2162 // This invalidates PhysReg.
2163 Spills.ClobberPhysReg(PhysReg);
2164
2165 // Any stores to this stack slot are not dead anymore.
2166 if (!DoReMat)
2167 MaybeDeadStores[SSorRMId] = NULL;
2168 Spills.addAvailable(SSorRMId, PhysReg);
2169 // Assumes this is the last use. IsKill will be unset if reg is reused
2170 // unless it's a two-address operand.
2171 if (!MI.isRegTiedToDefOperand(i) &&
2172 KilledMIRegs.count(VirtReg) == 0) {
2173 MI.getOperand(i).setIsKill();
2174 KilledMIRegs.insert(VirtReg);
2175 }
2176
2177 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
2178 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
2179 }
2180 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2181 MI.getOperand(i).setReg(RReg);
2182 MI.getOperand(i).setSubReg(0);
2183 }
2184
2185 // Ok - now we can remove stores that have been confirmed dead.
2186 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2187 // This was the last use and the spilled value is still available
2188 // for reuse. That means the spill was unnecessary!
2189 int PDSSlot = PotentialDeadStoreSlots[j];
2190 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2191 if (DeadStore) {
2192 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2193 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2194 VRM->RemoveMachineInstrFromMaps(DeadStore);
2195 MBB->erase(DeadStore);
2196 MaybeDeadStores[PDSSlot] = NULL;
2197 ++NumDSE;
2198 }
2199 }
2200
2201
2202 DEBUG(dbgs() << '\t' << MI);
2203
2204
2205 // If we have folded references to memory operands, make sure we clear all
2206 // physical registers that may contain the value of the spilled virtual
2207 // register
2208 SmallSet<int, 2> FoldedSS;
2209 for (tie(I, End) = VRM->getFoldedVirts(&MI); I != End; ) {
2210 unsigned VirtReg = I->second.first;
2211 VirtRegMap::ModRef MR = I->second.second;
2212 DEBUG(dbgs() << "Folded vreg: " << VirtReg << " MR: " << MR);
2213
2214 // MI2VirtMap be can updated which invalidate the iterator.
2215 // Increment the iterator first.
2216 ++I;
2217 int SS = VRM->getStackSlot(VirtReg);
2218 if (SS == VirtRegMap::NO_STACK_SLOT)
2219 continue;
2220 FoldedSS.insert(SS);
2221 DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
2222
2223 // If this folded instruction is just a use, check to see if it's a
2224 // straight load from the virt reg slot.
2225 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2226 int FrameIdx;
2227 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2228 if (DestReg && FrameIdx == SS) {
2229 // If this spill slot is available, turn it into a copy (or nothing)
2230 // instead of leaving it as a load!
2231 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
2232 DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
2233 if (DestReg != InReg) {
2234 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2235 TII->copyRegToReg(*MBB, &MI, DestReg, InReg, RC, RC);
2236 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2237 unsigned SubIdx = DefMO->getSubReg();
2238 // Revisit the copy so we make sure to notice the effects of the
2239 // operation on the destreg (either needing to RA it if it's
2240 // virtual or needing to clobber any values if it's physical).
2241 NextMII = &MI;
2242 --NextMII; // backtrack to the copy.
2243 NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
2244 // Propagate the sub-register index over.
2245 if (SubIdx) {
2246 DefMO = NextMII->findRegisterDefOperand(DestReg);
2247 DefMO->setSubReg(SubIdx);
2248 }
2249
2250 // Mark is killed.
2251 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
2252 KillOpnd->setIsKill();
2253
2254 BackTracked = true;
2255 } else {
2256 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2257 // Unset last kill since it's being reused.
2258 InvalidateKill(InReg, TRI, RegKills, KillOps);
2259 Spills.disallowClobberPhysReg(InReg);
2260 }
2261
2262 InvalidateKills(MI, TRI, RegKills, KillOps);
2263 VRM->RemoveMachineInstrFromMaps(&MI);
2264 MBB->erase(&MI);
2265 Erased = true;
2266 goto ProcessNextInst;
2267 }
2268 } else {
2269 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2270 SmallVector<MachineInstr*, 4> NewMIs;
2271 if (PhysReg &&
2272 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2273 MBB->insert(MII, NewMIs[0]);
2274 InvalidateKills(MI, TRI, RegKills, KillOps);
2275 VRM->RemoveMachineInstrFromMaps(&MI);
2276 MBB->erase(&MI);
2277 Erased = true;
2278 --NextMII; // backtrack to the unfolded instruction.
2279 BackTracked = true;
2280 goto ProcessNextInst;
2281 }
Lang Hames87e3bca2009-05-06 02:36:21 +00002282 }
2283 }
2284
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002285 // If this reference is not a use, any previous store is now dead.
2286 // Otherwise, the store to this stack slot is not dead anymore.
2287 MachineInstr* DeadStore = MaybeDeadStores[SS];
2288 if (DeadStore) {
2289 bool isDead = !(MR & VirtRegMap::isRef);
2290 MachineInstr *NewStore = NULL;
2291 if (MR & VirtRegMap::isModRef) {
2292 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2293 SmallVector<MachineInstr*, 4> NewMIs;
2294 // We can reuse this physreg as long as we are allowed to clobber
2295 // the value and there isn't an earlier def that has already clobbered
2296 // the physreg.
2297 if (PhysReg &&
2298 !ReusedOperands.isClobbered(PhysReg) &&
2299 Spills.canClobberPhysReg(PhysReg) &&
2300 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2301 MachineOperand *KillOpnd =
2302 DeadStore->findRegisterUseOperand(PhysReg, true);
2303 // Note, if the store is storing a sub-register, it's possible the
2304 // super-register is needed below.
2305 if (KillOpnd && !KillOpnd->getSubReg() &&
2306 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2307 MBB->insert(MII, NewMIs[0]);
2308 NewStore = NewMIs[1];
2309 MBB->insert(MII, NewStore);
2310 VRM->addSpillSlotUse(SS, NewStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002311 InvalidateKills(MI, TRI, RegKills, KillOps);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002312 VRM->RemoveMachineInstrFromMaps(&MI);
2313 MBB->erase(&MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002314 Erased = true;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002315 --NextMII;
Lang Hames87e3bca2009-05-06 02:36:21 +00002316 --NextMII; // backtrack to the unfolded instruction.
2317 BackTracked = true;
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002318 isDead = true;
2319 ++NumSUnfold;
2320 }
2321 }
2322 }
2323
2324 if (isDead) { // Previous store is dead.
2325 // If we get here, the store is dead, nuke it now.
2326 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
2327 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
2328 VRM->RemoveMachineInstrFromMaps(DeadStore);
2329 MBB->erase(DeadStore);
2330 if (!NewStore)
2331 ++NumDSE;
2332 }
2333
2334 MaybeDeadStores[SS] = NULL;
2335 if (NewStore) {
2336 // Treat this store as a spill merged into a copy. That makes the
2337 // stack slot value available.
2338 VRM->virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2339 goto ProcessNextInst;
2340 }
2341 }
2342
2343 // If the spill slot value is available, and this is a new definition of
2344 // the value, the value is not available anymore.
2345 if (MR & VirtRegMap::isMod) {
2346 // Notice that the value in this stack slot has been modified.
2347 Spills.ModifyStackSlotOrReMat(SS);
2348
2349 // If this is *just* a mod of the value, check to see if this is just a
2350 // store to the spill slot (i.e. the spill got merged into the copy). If
2351 // so, realize that the vreg is available now, and add the store to the
2352 // MaybeDeadStore info.
2353 int StackSlot;
2354 if (!(MR & VirtRegMap::isRef)) {
2355 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2356 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2357 "Src hasn't been allocated yet?");
2358
2359 if (CommuteToFoldReload(MII, VirtReg, SrcReg, StackSlot,
2360 Spills, RegKills, KillOps, TRI)) {
2361 NextMII = llvm::next(MII);
2362 BackTracked = true;
Lang Hames87e3bca2009-05-06 02:36:21 +00002363 goto ProcessNextInst;
2364 }
Lang Hames87e3bca2009-05-06 02:36:21 +00002365
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002366 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2367 // this as a potentially dead store in case there is a subsequent
2368 // store into the stack slot without a read from it.
2369 MaybeDeadStores[StackSlot] = &MI;
Lang Hames87e3bca2009-05-06 02:36:21 +00002370
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002371 // If the stack slot value was previously available in some other
2372 // register, change it now. Otherwise, make the register
2373 // available in PhysReg.
2374 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
Lang Hames87e3bca2009-05-06 02:36:21 +00002375 }
2376 }
2377 }
Lang Hames87e3bca2009-05-06 02:36:21 +00002378 }
2379
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002380 // Process all of the spilled defs.
2381 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2382 MachineOperand &MO = MI.getOperand(i);
2383 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2384 continue;
Lang Hames87e3bca2009-05-06 02:36:21 +00002385
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002386 unsigned VirtReg = MO.getReg();
2387 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2388 // Check to see if this is a noop copy. If so, eliminate the
2389 // instruction before considering the dest reg to be changed.
2390 // Also check if it's copying from an "undef", if so, we can't
2391 // eliminate this or else the undef marker is lost and it will
2392 // confuses the scavenger. This is extremely rare.
2393 unsigned Src, Dst, SrcSR, DstSR;
2394 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
2395 !MI.findRegisterUseOperand(Src)->isUndef()) {
2396 ++NumDCE;
2397 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2398 SmallVector<unsigned, 2> KillRegs;
2399 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
2400 if (MO.isDead() && !KillRegs.empty()) {
2401 // Source register or an implicit super/sub-register use is killed.
2402 assert(KillRegs[0] == Dst ||
2403 TRI->isSubRegister(KillRegs[0], Dst) ||
2404 TRI->isSuperRegister(KillRegs[0], Dst));
2405 // Last def is now dead.
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00002406 TransferDeadness(Src, RegKills, KillOps);
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002407 }
2408 VRM->RemoveMachineInstrFromMaps(&MI);
2409 MBB->erase(&MI);
2410 Erased = true;
2411 Spills.disallowClobberPhysReg(VirtReg);
2412 goto ProcessNextInst;
2413 }
2414
2415 // If it's not a no-op copy, it clobbers the value in the destreg.
2416 Spills.ClobberPhysReg(VirtReg);
2417 ReusedOperands.markClobbered(VirtReg);
2418
2419 // Check to see if this instruction is a load from a stack slot into
2420 // a register. If so, this provides the stack slot value in the reg.
2421 int FrameIdx;
2422 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2423 assert(DestReg == VirtReg && "Unknown load situation!");
2424
2425 // If it is a folded reference, then it's not safe to clobber.
2426 bool Folded = FoldedSS.count(FrameIdx);
2427 // Otherwise, if it wasn't available, remember that it is now!
2428 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2429 goto ProcessNextInst;
2430 }
2431
2432 continue;
2433 }
2434
2435 unsigned SubIdx = MO.getSubReg();
2436 bool DoReMat = VRM->isReMaterialized(VirtReg);
2437 if (DoReMat)
2438 ReMatDefs.insert(&MI);
2439
2440 // The only vregs left are stack slot definitions.
2441 int StackSlot = VRM->getStackSlot(VirtReg);
2442 const TargetRegisterClass *RC = MRI->getRegClass(VirtReg);
2443
2444 // If this def is part of a two-address operand, make sure to execute
2445 // the store from the correct physical register.
2446 unsigned PhysReg;
2447 unsigned TiedOp;
2448 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2449 PhysReg = MI.getOperand(TiedOp).getReg();
2450 if (SubIdx) {
2451 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2452 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2453 "Can't find corresponding super-register!");
2454 PhysReg = SuperReg;
2455 }
2456 } else {
2457 PhysReg = VRM->getPhys(VirtReg);
2458 if (ReusedOperands.isClobbered(PhysReg)) {
2459 // Another def has taken the assigned physreg. It must have been a
2460 // use&def which got it due to reuse. Undo the reuse!
2461 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2462 Spills, MaybeDeadStores, RegKills, KillOps, *VRM);
2463 }
2464 }
2465
2466 assert(PhysReg && "VR not assigned a physical register?");
2467 MRI->setPhysRegUsed(PhysReg);
2468 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2469 ReusedOperands.markClobbered(RReg);
2470 MI.getOperand(i).setReg(RReg);
2471 MI.getOperand(i).setSubReg(0);
2472
2473 if (!MO.isDead()) {
2474 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2475 SpillRegToStackSlot(MII, -1, PhysReg, StackSlot, RC, true,
2476 LastStore, Spills, ReMatDefs, RegKills, KillOps);
2477 NextMII = llvm::next(MII);
2478
2479 // Check to see if this is a noop copy. If so, eliminate the
2480 // instruction before considering the dest reg to be changed.
2481 {
2482 unsigned Src, Dst, SrcSR, DstSR;
2483 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
2484 ++NumDCE;
2485 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
2486 InvalidateKills(MI, TRI, RegKills, KillOps);
2487 VRM->RemoveMachineInstrFromMaps(&MI);
2488 MBB->erase(&MI);
2489 Erased = true;
2490 UpdateKills(*LastStore, TRI, RegKills, KillOps);
2491 goto ProcessNextInst;
2492 }
2493 }
2494 }
2495 }
2496 ProcessNextInst:
2497 // Delete dead instructions without side effects.
2498 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
2499 InvalidateKills(MI, TRI, RegKills, KillOps);
2500 VRM->RemoveMachineInstrFromMaps(&MI);
2501 MBB->erase(&MI);
2502 Erased = true;
2503 }
2504 if (!Erased)
Jakob Stoklund Olesen56698802010-03-11 23:04:34 +00002505 DistanceMap.insert(std::make_pair(&MI, DistanceMap.size()));
Jakob Stoklund Olesen2cb42022010-03-11 00:11:33 +00002506 if (!Erased && !BackTracked) {
2507 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
2508 UpdateKills(*II, TRI, RegKills, KillOps);
2509 }
2510 MII = NextMII;
2511 }
Lang Hames87e3bca2009-05-06 02:36:21 +00002512
Dan Gohman7db949d2009-08-07 01:32:21 +00002513}
2514
Lang Hames87e3bca2009-05-06 02:36:21 +00002515llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2516 switch (RewriterOpt) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002517 default: llvm_unreachable("Unreachable!");
Lang Hames87e3bca2009-05-06 02:36:21 +00002518 case local:
2519 return new LocalRewriter();
Lang Hamesf41538d2009-06-02 16:53:25 +00002520 case trivial:
2521 return new TrivialRewriter();
Lang Hames87e3bca2009-05-06 02:36:21 +00002522 }
2523}