blob: 7aa0a9153524ff81f326af5752a8515ad6113a2d [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");
101 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 }
David Greene2d4e6d32009-07-28 16:49:24 +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());
Lang Hamesf41538d2009-06-02 16:53:25 +0000141
142 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) {
211 // If this stack slot is thought to be available in some other physreg,
212 // 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;
367
368 // 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 }
387
388 bool hasReuses() const {
389 return !Reuses.empty();
390 }
391
392 /// 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;
400
401 // Otherwise, remember this.
402 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
403 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 }
413
414 /// 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
416 /// 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,
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000528 bool &HasLiveDef,
529 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) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000575 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
576 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000577 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000578 continue;
579 unsigned Reg = MO.getReg();
580 if (Reg == 0)
581 continue;
582
583 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
584 // That can't be right. Register is killed but not re-defined and it's
585 // being reused. Let's fix that.
586 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000587 // KillOps[Reg] might be a def of a super-register.
588 unsigned KReg = KillOps[Reg]->getReg();
589 KillOps[KReg] = NULL;
590 RegKills.reset(KReg);
591
592 // Must be a def of a super-register. Its other sub-regsters are no
593 // longer killed as well.
594 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
595 KillOps[*SR] = NULL;
596 RegKills.reset(*SR);
597 }
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000598 } else {
599 // Check for subreg kills as well.
600 // d4 =
601 // store d4, fi#0
602 // ...
603 // = s8<kill>
604 // ...
605 // = d4 <avoiding reload>
606 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
607 unsigned SReg = *SR;
608 if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
609 KillOps[SReg]->setIsKill(false);
610 unsigned KReg = KillOps[SReg]->getReg();
611 KillOps[KReg] = NULL;
612 RegKills.reset(KReg);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000613
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000614 for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
615 KillOps[*SSR] = NULL;
616 RegKills.reset(*SSR);
617 }
618 }
619 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000620 }
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000621
Lang Hames87e3bca2009-05-06 02:36:21 +0000622 if (MO.isKill()) {
623 RegKills.set(Reg);
624 KillOps[Reg] = &MO;
Evan Cheng427a6b62009-05-15 06:48:19 +0000625 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
626 RegKills.set(*SR);
627 KillOps[*SR] = &MO;
628 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000629 }
630 }
631
632 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
633 const MachineOperand &MO = MI.getOperand(i);
Evan Chengd57cdd52009-11-14 02:55:43 +0000634 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000635 continue;
636 unsigned Reg = MO.getReg();
637 RegKills.reset(Reg);
638 KillOps[Reg] = NULL;
639 // It also defines (or partially define) aliases.
Evan Cheng427a6b62009-05-15 06:48:19 +0000640 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
641 RegKills.reset(*SR);
642 KillOps[*SR] = NULL;
Lang Hames87e3bca2009-05-06 02:36:21 +0000643 }
Evan Cheng1f6a3c82009-11-13 23:16:41 +0000644 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
645 RegKills.reset(*SR);
646 KillOps[*SR] = NULL;
647 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000648 }
649}
650
651/// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
652///
653static void ReMaterialize(MachineBasicBlock &MBB,
654 MachineBasicBlock::iterator &MII,
655 unsigned DestReg, unsigned Reg,
656 const TargetInstrInfo *TII,
657 const TargetRegisterInfo *TRI,
658 VirtRegMap &VRM) {
Evan Cheng5f159922009-07-16 20:15:00 +0000659 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
Daniel Dunbar24cd3c42009-07-16 22:08:25 +0000660#ifndef NDEBUG
Evan Cheng5f159922009-07-16 20:15:00 +0000661 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
Evan Chengc1b46f92009-07-17 00:32:06 +0000662 assert(TID.getNumDefs() == 1 &&
Evan Cheng5f159922009-07-16 20:15:00 +0000663 "Don't know how to remat instructions that define > 1 values!");
664#endif
665 TII->reMaterialize(MBB, MII, DestReg,
Evan Chengd57cdd52009-11-14 02:55:43 +0000666 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI, TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +0000667 MachineInstr *NewMI = prior(MII);
668 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
669 MachineOperand &MO = NewMI->getOperand(i);
670 if (!MO.isReg() || MO.getReg() == 0)
671 continue;
672 unsigned VirtReg = MO.getReg();
673 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
674 continue;
675 assert(MO.isUse());
Lang Hames87e3bca2009-05-06 02:36:21 +0000676 unsigned Phys = VRM.getPhys(VirtReg);
Evan Cheng427c3ba2009-10-25 07:51:47 +0000677 assert(Phys && "Virtual register is not assigned a register?");
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +0000678 substitutePhysReg(MO, Phys, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +0000679 }
680 ++NumReMats;
681}
682
683/// findSuperReg - Find the SubReg's super-register of given register class
684/// where its SubIdx sub-register is SubReg.
685static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
686 unsigned SubIdx, const TargetRegisterInfo *TRI) {
687 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
688 I != E; ++I) {
689 unsigned Reg = *I;
690 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
691 return Reg;
692 }
693 return 0;
694}
695
696// ******************************** //
697// Available Spills Implementation //
698// ******************************** //
699
700/// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
701/// stackslot register. The register is still available but is no longer
702/// allowed to be modifed.
703void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
704 std::multimap<unsigned, int>::iterator I =
705 PhysRegsAvailable.lower_bound(PhysReg);
706 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
707 int SlotOrReMat = I->second;
708 I++;
709 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
710 "Bidirectional map mismatch!");
711 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
David Greene0ee52182010-01-05 01:25:52 +0000712 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
Chris Lattner6456d382009-08-23 03:20:44 +0000713 << " copied, it is available for use but can no longer be modified\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000714 }
715}
716
717/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
718/// stackslot register and its aliases. The register and its aliases may
719/// still available but is no longer allowed to be modifed.
720void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
721 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
722 disallowClobberPhysRegOnly(*AS);
723 disallowClobberPhysRegOnly(PhysReg);
724}
725
726/// ClobberPhysRegOnly - This is called when the specified physreg changes
727/// value. We use this to invalidate any info about stuff we thing lives in it.
728void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
729 std::multimap<unsigned, int>::iterator I =
730 PhysRegsAvailable.lower_bound(PhysReg);
731 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
732 int SlotOrReMat = I->second;
733 PhysRegsAvailable.erase(I++);
734 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
735 "Bidirectional map mismatch!");
736 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
David Greene0ee52182010-01-05 01:25:52 +0000737 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
Chris Lattner6456d382009-08-23 03:20:44 +0000738 << " clobbered, invalidating ");
Lang Hames87e3bca2009-05-06 02:36:21 +0000739 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
David Greene0ee52182010-01-05 01:25:52 +0000740 DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000741 else
David Greene0ee52182010-01-05 01:25:52 +0000742 DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000743 }
744}
745
746/// ClobberPhysReg - This is called when the specified physreg changes
747/// value. We use this to invalidate any info about stuff we thing lives in
748/// it and any of its aliases.
749void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
750 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
751 ClobberPhysRegOnly(*AS);
752 ClobberPhysRegOnly(PhysReg);
753}
754
755/// AddAvailableRegsToLiveIn - Availability information is being kept coming
756/// into the specified MBB. Add available physical registers as potential
757/// live-in's. If they are reused in the MBB, they will be added to the
758/// live-in set to make register scavenger and post-allocation scheduler.
759void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
760 BitVector &RegKills,
761 std::vector<MachineOperand*> &KillOps) {
762 std::set<unsigned> NotAvailable;
763 for (std::multimap<unsigned, int>::iterator
764 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
765 I != E; ++I) {
766 unsigned Reg = I->first;
767 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
768 // FIXME: A temporary workaround. We can't reuse available value if it's
769 // not safe to move the def of the virtual register's class. e.g.
770 // X86::RFP* register classes. Do not add it as a live-in.
771 if (!TII->isSafeToMoveRegClassDefs(RC))
772 // This is no longer available.
773 NotAvailable.insert(Reg);
774 else {
775 MBB.addLiveIn(Reg);
Evan Cheng427a6b62009-05-15 06:48:19 +0000776 InvalidateKill(Reg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +0000777 }
778
779 // Skip over the same register.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000780 std::multimap<unsigned, int>::iterator NI = llvm::next(I);
Lang Hames87e3bca2009-05-06 02:36:21 +0000781 while (NI != E && NI->first == Reg) {
782 ++I;
783 ++NI;
784 }
785 }
786
787 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
788 E = NotAvailable.end(); I != E; ++I) {
789 ClobberPhysReg(*I);
790 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
791 *SubRegs; ++SubRegs)
792 ClobberPhysReg(*SubRegs);
793 }
794}
795
796/// ModifyStackSlotOrReMat - This method is called when the value in a stack
797/// slot changes. This removes information about which register the previous
798/// value for this slot lives in (as the previous value is dead now).
799void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
800 std::map<int, unsigned>::iterator It =
801 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
802 if (It == SpillSlotsOrReMatsAvailable.end()) return;
803 unsigned Reg = It->second >> 1;
804 SpillSlotsOrReMatsAvailable.erase(It);
805
806 // This register may hold the value of multiple stack slots, only remove this
807 // stack slot from the set of values the register contains.
808 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
809 for (; ; ++I) {
810 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
811 "Map inverse broken!");
812 if (I->second == SlotOrReMat) break;
813 }
814 PhysRegsAvailable.erase(I);
815}
816
817// ************************** //
818// Reuse Info Implementation //
819// ************************** //
820
821/// GetRegForReload - We are about to emit a reload into PhysReg. If there
822/// is some other operand that is using the specified register, either pick
823/// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000824unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
825 unsigned PhysReg,
826 MachineFunction &MF,
827 MachineInstr *MI, AvailableSpills &Spills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000828 std::vector<MachineInstr*> &MaybeDeadStores,
829 SmallSet<unsigned, 8> &Rejected,
830 BitVector &RegKills,
831 std::vector<MachineOperand*> &KillOps,
832 VirtRegMap &VRM) {
Evan Cheng5d885022009-07-21 09:15:00 +0000833 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
834 const TargetRegisterInfo *TRI = Spills.getRegInfo();
Lang Hames87e3bca2009-05-06 02:36:21 +0000835
836 if (Reuses.empty()) return PhysReg; // This is most often empty.
837
838 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
839 ReusedOp &Op = Reuses[ro];
840 // If we find some other reuse that was supposed to use this register
841 // exactly for its reload, we can change this reload to use ITS reload
842 // register. That is, unless its reload register has already been
843 // considered and subsequently rejected because it has also been reused
844 // by another operand.
845 if (Op.PhysRegReused == PhysReg &&
Evan Cheng5d885022009-07-21 09:15:00 +0000846 Rejected.count(Op.AssignedPhysReg) == 0 &&
847 RC->contains(Op.AssignedPhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000848 // Yup, use the reload register that we didn't use before.
849 unsigned NewReg = Op.AssignedPhysReg;
850 Rejected.insert(PhysReg);
Evan Cheng5d885022009-07-21 09:15:00 +0000851 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
Lang Hames87e3bca2009-05-06 02:36:21 +0000852 RegKills, KillOps, VRM);
853 } else {
854 // Otherwise, we might also have a problem if a previously reused
Evan Cheng5d885022009-07-21 09:15:00 +0000855 // value aliases the new register. If so, codegen the previous reload
Lang Hames87e3bca2009-05-06 02:36:21 +0000856 // and use this one.
857 unsigned PRRU = Op.PhysRegReused;
Lang Hames3f2f3f52009-09-03 02:52:02 +0000858 if (TRI->regsOverlap(PRRU, PhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000859 // Okay, we found out that an alias of a reused register
860 // was used. This isn't good because it means we have
861 // to undo a previous reuse.
862 MachineBasicBlock *MBB = MI->getParent();
863 const TargetRegisterClass *AliasRC =
864 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
865
866 // Copy Op out of the vector and remove it, we're going to insert an
867 // explicit load for it.
868 ReusedOp NewOp = Op;
869 Reuses.erase(Reuses.begin()+ro);
870
Jakob Stoklund Olesen46ff9692009-08-23 13:01:45 +0000871 // MI may be using only a sub-register of PhysRegUsed.
872 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
873 unsigned SubIdx = 0;
874 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
875 "A reuse cannot be a virtual register");
876 if (PRRU != RealPhysRegUsed) {
877 // What was the sub-register index?
Evan Chengfae3e922009-11-14 03:42:17 +0000878 SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
879 assert(SubIdx &&
Jakob Stoklund Olesen46ff9692009-08-23 13:01:45 +0000880 "Operand physreg is not a sub-register of PhysRegUsed");
881 }
882
Lang Hames87e3bca2009-05-06 02:36:21 +0000883 // Ok, we're going to try to reload the assigned physreg into the
884 // slot that we were supposed to in the first place. However, that
885 // register could hold a reuse. Check to see if it conflicts or
886 // would prefer us to use a different register.
Evan Cheng5d885022009-07-21 09:15:00 +0000887 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
888 MF, MI, Spills, MaybeDeadStores,
889 Rejected, RegKills, KillOps, VRM);
David Greene2d4e6d32009-07-28 16:49:24 +0000890
891 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
892 int SSorRMId = DoReMat
893 ? VRM.getReMatId(NewOp.VirtReg) : NewOp.StackSlotOrReMat;
894
895 // Back-schedule reloads and remats.
896 MachineBasicBlock::iterator InsertLoc =
897 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
898 DoReMat, SSorRMId, TII, MF);
899
900 if (DoReMat) {
901 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
902 TRI, VRM);
903 } else {
904 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
Lang Hames87e3bca2009-05-06 02:36:21 +0000905 NewOp.StackSlotOrReMat, AliasRC);
David Greene2d4e6d32009-07-28 16:49:24 +0000906 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +0000907 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
908 // Any stores to this stack slot are not dead anymore.
909 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
910 ++NumLoads;
911 }
912 Spills.ClobberPhysReg(NewPhysReg);
913 Spills.ClobberPhysReg(NewOp.PhysRegReused);
914
Evan Cheng427c3ba2009-10-25 07:51:47 +0000915 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
Lang Hames87e3bca2009-05-06 02:36:21 +0000916 MI->getOperand(NewOp.Operand).setReg(RReg);
917 MI->getOperand(NewOp.Operand).setSubReg(0);
918
919 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
David Greene2d4e6d32009-07-28 16:49:24 +0000920 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
David Greene0ee52182010-01-05 01:25:52 +0000921 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
Lang Hames87e3bca2009-05-06 02:36:21 +0000922
David Greene0ee52182010-01-05 01:25:52 +0000923 DEBUG(dbgs() << "Reuse undone!\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000924 --NumReused;
925
926 // Finally, PhysReg is now available, go ahead and use it.
927 return PhysReg;
928 }
929 }
930 }
931 return PhysReg;
932}
933
934// ************************************************************************ //
935
936/// FoldsStackSlotModRef - Return true if the specified MI folds the specified
937/// stack slot mod/ref. It also checks if it's possible to unfold the
938/// instruction by having it define a specified physical register instead.
939static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
940 const TargetInstrInfo *TII,
941 const TargetRegisterInfo *TRI,
942 VirtRegMap &VRM) {
943 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
944 return false;
945
946 bool Found = false;
947 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
948 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
949 unsigned VirtReg = I->second.first;
950 VirtRegMap::ModRef MR = I->second.second;
951 if (MR & VirtRegMap::isModRef)
952 if (VRM.getStackSlot(VirtReg) == SS) {
953 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
954 break;
955 }
956 }
957 if (!Found)
958 return false;
959
960 // Does the instruction uses a register that overlaps the scratch register?
961 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
962 MachineOperand &MO = MI.getOperand(i);
963 if (!MO.isReg() || MO.getReg() == 0)
964 continue;
965 unsigned Reg = MO.getReg();
966 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
967 if (!VRM.hasPhys(Reg))
968 continue;
969 Reg = VRM.getPhys(Reg);
970 }
971 if (TRI->regsOverlap(PhysReg, Reg))
972 return false;
973 }
974 return true;
975}
976
977/// FindFreeRegister - Find a free register of a given register class by looking
978/// at (at most) the last two machine instructions.
979static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
980 MachineBasicBlock &MBB,
981 const TargetRegisterClass *RC,
982 const TargetRegisterInfo *TRI,
983 BitVector &AllocatableRegs) {
984 BitVector Defs(TRI->getNumRegs());
985 BitVector Uses(TRI->getNumRegs());
986 SmallVector<unsigned, 4> LocalUses;
987 SmallVector<unsigned, 4> Kills;
988
989 // Take a look at 2 instructions at most.
990 for (unsigned Count = 0; Count < 2; ++Count) {
991 if (MII == MBB.begin())
992 break;
993 MachineInstr *PrevMI = prior(MII);
994 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
995 MachineOperand &MO = PrevMI->getOperand(i);
996 if (!MO.isReg() || MO.getReg() == 0)
997 continue;
998 unsigned Reg = MO.getReg();
999 if (MO.isDef()) {
1000 Defs.set(Reg);
1001 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1002 Defs.set(*AS);
1003 } else {
1004 LocalUses.push_back(Reg);
1005 if (MO.isKill() && AllocatableRegs[Reg])
1006 Kills.push_back(Reg);
1007 }
1008 }
1009
1010 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1011 unsigned Kill = Kills[i];
1012 if (!Defs[Kill] && !Uses[Kill] &&
1013 TRI->getPhysicalRegisterRegClass(Kill) == RC)
1014 return Kill;
1015 }
1016 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1017 unsigned Reg = LocalUses[i];
1018 Uses.set(Reg);
1019 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1020 Uses.set(*AS);
1021 }
1022
1023 MII = PrevMI;
1024 }
1025
1026 return 0;
1027}
1028
1029static
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001030void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1031 const TargetRegisterInfo &TRI) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001032 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1033 MachineOperand &MO = MI->getOperand(i);
1034 if (MO.isReg() && MO.getReg() == VirtReg)
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001035 substitutePhysReg(MO, PhysReg, TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001036 }
1037}
1038
Evan Chengeca24fb2009-05-12 23:07:00 +00001039namespace {
1040 struct RefSorter {
1041 bool operator()(const std::pair<MachineInstr*, int> &A,
1042 const std::pair<MachineInstr*, int> &B) {
1043 return A.second < B.second;
1044 }
1045 };
1046}
Lang Hames87e3bca2009-05-06 02:36:21 +00001047
1048// ***************************** //
1049// Local Spiller Implementation //
1050// ***************************** //
1051
Dan Gohman7db949d2009-08-07 01:32:21 +00001052namespace {
1053
Nick Lewycky6726b6d2009-10-25 06:33:48 +00001054class LocalRewriter : public VirtRegRewriter {
Lang Hames87e3bca2009-05-06 02:36:21 +00001055 MachineRegisterInfo *RegInfo;
1056 const TargetRegisterInfo *TRI;
1057 const TargetInstrInfo *TII;
1058 BitVector AllocatableRegs;
1059 DenseMap<MachineInstr*, unsigned> DistanceMap;
1060public:
1061
1062 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1063 LiveIntervals* LIs) {
1064 RegInfo = &MF.getRegInfo();
1065 TRI = MF.getTarget().getRegisterInfo();
1066 TII = MF.getTarget().getInstrInfo();
1067 AllocatableRegs = TRI->getAllocatableSet(MF);
David Greene0ee52182010-01-05 01:25:52 +00001068 DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001069 << MF.getFunction()->getName() << "':\n");
David Greene0ee52182010-01-05 01:25:52 +00001070 DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
Chris Lattner6456d382009-08-23 03:20:44 +00001071 " reloads!) ****\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001072 DEBUG(MF.dump());
1073
1074 // Spills - Keep track of which spilled values are available in physregs
1075 // so that we can choose to reuse the physregs instead of emitting
1076 // reloads. This is usually refreshed per basic block.
1077 AvailableSpills Spills(TRI, TII);
1078
1079 // Keep track of kill information.
1080 BitVector RegKills(TRI->getNumRegs());
1081 std::vector<MachineOperand*> KillOps;
1082 KillOps.resize(TRI->getNumRegs(), NULL);
1083
1084 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1085 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1086 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1087
1088 // Traverse the basic blocks depth first.
1089 MachineBasicBlock *Entry = MF.begin();
1090 SmallPtrSet<MachineBasicBlock*,16> Visited;
1091 for (df_ext_iterator<MachineBasicBlock*,
1092 SmallPtrSet<MachineBasicBlock*,16> >
1093 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1094 DFI != E; ++DFI) {
1095 MachineBasicBlock *MBB = *DFI;
1096 if (!EarlyVisited.count(MBB))
1097 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1098
1099 // If this MBB is the only predecessor of a successor. Keep the
1100 // availability information and visit it next.
1101 do {
1102 // Keep visiting single predecessor successor as long as possible.
1103 SinglePredSuccs.clear();
1104 findSinglePredSuccessor(MBB, SinglePredSuccs);
1105 if (SinglePredSuccs.empty())
1106 MBB = 0;
1107 else {
1108 // FIXME: More than one successors, each of which has MBB has
1109 // the only predecessor.
1110 MBB = SinglePredSuccs[0];
1111 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1112 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1113 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1114 }
1115 }
1116 } while (MBB);
1117
1118 // Clear the availability info.
1119 Spills.clear();
1120 }
1121
David Greene0ee52182010-01-05 01:25:52 +00001122 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001123 DEBUG(MF.dump());
1124
1125 // Mark unused spill slots.
1126 MachineFrameInfo *MFI = MF.getFrameInfo();
1127 int SS = VRM.getLowSpillSlot();
1128 if (SS != VirtRegMap::NO_STACK_SLOT)
1129 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
1130 if (!VRM.isSpillSlotUsed(SS)) {
1131 MFI->RemoveStackObject(SS);
1132 ++NumDSS;
1133 }
1134
1135 return true;
1136 }
1137
1138private:
1139
1140 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1141 /// a scratch register is available.
1142 /// xorq %r12<kill>, %r13
1143 /// addq %rax, -184(%rbp)
1144 /// addq %r13, -184(%rbp)
1145 /// ==>
1146 /// xorq %r12<kill>, %r13
1147 /// movq -184(%rbp), %r12
1148 /// addq %rax, %r12
1149 /// addq %r13, %r12
1150 /// movq %r12, -184(%rbp)
1151 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1152 MachineBasicBlock &MBB,
1153 MachineBasicBlock::iterator &MII,
1154 std::vector<MachineInstr*> &MaybeDeadStores,
1155 AvailableSpills &Spills,
1156 BitVector &RegKills,
1157 std::vector<MachineOperand*> &KillOps,
1158 VirtRegMap &VRM) {
1159
Chris Lattner7896c9f2009-12-03 00:50:42 +00001160 MachineBasicBlock::iterator NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001161 if (NextMII == MBB.end())
1162 return false;
1163
1164 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1165 return false;
1166
1167 // Now let's see if the last couple of instructions happens to have freed up
1168 // a register.
1169 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1170 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
1171 if (!PhysReg)
1172 return false;
1173
1174 MachineFunction &MF = *MBB.getParent();
1175 TRI = MF.getTarget().getRegisterInfo();
1176 MachineInstr &MI = *MII;
1177 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
1178 return false;
1179
1180 // If the next instruction also folds the same SS modref and can be unfoled,
1181 // then it's worthwhile to issue a load from SS into the free register and
1182 // then unfold these instructions.
1183 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
1184 return false;
1185
David Greene2d4e6d32009-07-28 16:49:24 +00001186 // Back-schedule reloads and remats.
Duncan Sandsb7c5bdf2009-09-06 08:33:48 +00001187 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, false, SS, TII, MF);
David Greene2d4e6d32009-07-28 16:49:24 +00001188
Lang Hames87e3bca2009-05-06 02:36:21 +00001189 // Load from SS to the spare physical register.
1190 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
1191 // This invalidates Phys.
1192 Spills.ClobberPhysReg(PhysReg);
1193 // Remember it's available.
1194 Spills.addAvailable(SS, PhysReg);
1195 MaybeDeadStores[SS] = NULL;
1196
1197 // Unfold current MI.
1198 SmallVector<MachineInstr*, 4> NewMIs;
1199 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
Torok Edwinc23197a2009-07-14 16:55:14 +00001200 llvm_unreachable("Unable unfold the load / store folding instruction!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001201 assert(NewMIs.size() == 1);
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001202 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001203 VRM.transferRestorePts(&MI, NewMIs[0]);
1204 MII = MBB.insert(MII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00001205 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001206 VRM.RemoveMachineInstrFromMaps(&MI);
1207 MBB.erase(&MI);
1208 ++NumModRefUnfold;
1209
1210 // Unfold next instructions that fold the same SS.
1211 do {
1212 MachineInstr &NextMI = *NextMII;
Chris Lattner7896c9f2009-12-03 00:50:42 +00001213 NextMII = llvm::next(NextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001214 NewMIs.clear();
1215 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
Torok Edwinc23197a2009-07-14 16:55:14 +00001216 llvm_unreachable("Unable unfold the load / store folding instruction!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001217 assert(NewMIs.size() == 1);
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001218 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001219 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1220 MBB.insert(NextMII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00001221 InvalidateKills(NextMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001222 VRM.RemoveMachineInstrFromMaps(&NextMI);
1223 MBB.erase(&NextMI);
1224 ++NumModRefUnfold;
Evan Cheng2c48fe62009-06-03 09:00:27 +00001225 if (NextMII == MBB.end())
1226 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001227 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1228
1229 // Store the value back into SS.
1230 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1231 MachineInstr *StoreMI = prior(NextMII);
1232 VRM.addSpillSlotUse(SS, StoreMI);
1233 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1234
1235 return true;
1236 }
1237
1238 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1239 /// instruction. e.g.
1240 /// xorl %edi, %eax
1241 /// movl %eax, -32(%ebp)
1242 /// movl -36(%ebp), %eax
1243 /// orl %eax, -32(%ebp)
1244 /// ==>
1245 /// xorl %edi, %eax
1246 /// orl -36(%ebp), %eax
1247 /// mov %eax, -32(%ebp)
1248 /// This enables unfolding optimization for a subsequent instruction which will
1249 /// also eliminate the newly introduced store instruction.
1250 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1251 MachineBasicBlock::iterator &MII,
1252 std::vector<MachineInstr*> &MaybeDeadStores,
1253 AvailableSpills &Spills,
1254 BitVector &RegKills,
1255 std::vector<MachineOperand*> &KillOps,
1256 VirtRegMap &VRM) {
1257 MachineFunction &MF = *MBB.getParent();
1258 MachineInstr &MI = *MII;
1259 unsigned UnfoldedOpc = 0;
1260 unsigned UnfoldPR = 0;
1261 unsigned UnfoldVR = 0;
1262 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1263 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1264 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1265 // Only transform a MI that folds a single register.
1266 if (UnfoldedOpc)
1267 return false;
1268 UnfoldVR = I->second.first;
1269 VirtRegMap::ModRef MR = I->second.second;
1270 // MI2VirtMap be can updated which invalidate the iterator.
1271 // Increment the iterator first.
1272 ++I;
1273 if (VRM.isAssignedReg(UnfoldVR))
1274 continue;
1275 // If this reference is not a use, any previous store is now dead.
1276 // Otherwise, the store to this stack slot is not dead anymore.
1277 FoldedSS = VRM.getStackSlot(UnfoldVR);
1278 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1279 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1280 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1281 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1282 continue;
1283 UnfoldPR = PhysReg;
1284 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1285 false, true);
1286 }
1287 }
1288
1289 if (!UnfoldedOpc) {
1290 if (!UnfoldVR)
1291 return false;
1292
1293 // Look for other unfolding opportunities.
1294 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1295 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1296 }
1297
1298 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1299 MachineOperand &MO = MI.getOperand(i);
1300 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1301 continue;
1302 unsigned VirtReg = MO.getReg();
1303 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1304 continue;
1305 if (VRM.isAssignedReg(VirtReg)) {
1306 unsigned PhysReg = VRM.getPhys(VirtReg);
1307 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1308 return false;
1309 } else if (VRM.isReMaterialized(VirtReg))
1310 continue;
1311 int SS = VRM.getStackSlot(VirtReg);
1312 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1313 if (PhysReg) {
1314 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1315 return false;
1316 continue;
1317 }
1318 if (VRM.hasPhys(VirtReg)) {
1319 PhysReg = VRM.getPhys(VirtReg);
1320 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1321 continue;
1322 }
1323
1324 // Ok, we'll need to reload the value into a register which makes
1325 // it impossible to perform the store unfolding optimization later.
1326 // Let's see if it is possible to fold the load if the store is
1327 // unfolded. This allows us to perform the store unfolding
1328 // optimization.
1329 SmallVector<MachineInstr*, 4> NewMIs;
1330 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1331 assert(NewMIs.size() == 1);
1332 MachineInstr *NewMI = NewMIs.back();
1333 NewMIs.clear();
1334 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1335 assert(Idx != -1);
1336 SmallVector<unsigned, 1> Ops;
1337 Ops.push_back(Idx);
1338 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1339 if (FoldedMI) {
1340 VRM.addSpillSlotUse(SS, FoldedMI);
1341 if (!VRM.hasPhys(UnfoldVR))
1342 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1343 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1344 MII = MBB.insert(MII, FoldedMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001345 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001346 VRM.RemoveMachineInstrFromMaps(&MI);
1347 MBB.erase(&MI);
1348 MF.DeleteMachineInstr(NewMI);
1349 return true;
1350 }
1351 MF.DeleteMachineInstr(NewMI);
1352 }
1353 }
1354
1355 return false;
1356 }
1357
Evan Cheng261ce1d2009-07-10 19:15:51 +00001358 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1359 /// where SrcReg is r1 and it is tied to r0. Return true if after
1360 /// commuting this instruction it will be r0 = op r2, r1.
1361 static bool CommuteChangesDestination(MachineInstr *DefMI,
1362 const TargetInstrDesc &TID,
1363 unsigned SrcReg,
1364 const TargetInstrInfo *TII,
1365 unsigned &DstIdx) {
1366 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1367 return false;
1368 if (!DefMI->getOperand(1).isReg() ||
1369 DefMI->getOperand(1).getReg() != SrcReg)
1370 return false;
1371 unsigned DefIdx;
1372 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1373 return false;
1374 unsigned SrcIdx1, SrcIdx2;
1375 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1376 return false;
1377 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1378 DstIdx = 2;
1379 return true;
1380 }
1381 return false;
1382 }
1383
Lang Hames87e3bca2009-05-06 02:36:21 +00001384 /// CommuteToFoldReload -
1385 /// Look for
1386 /// r1 = load fi#1
1387 /// r1 = op r1, r2<kill>
1388 /// store r1, fi#1
1389 ///
1390 /// If op is commutable and r2 is killed, then we can xform these to
1391 /// r2 = op r2, fi#1
1392 /// store r2, fi#1
1393 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1394 MachineBasicBlock::iterator &MII,
1395 unsigned VirtReg, unsigned SrcReg, int SS,
1396 AvailableSpills &Spills,
1397 BitVector &RegKills,
1398 std::vector<MachineOperand*> &KillOps,
1399 const TargetRegisterInfo *TRI,
1400 VirtRegMap &VRM) {
1401 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1402 return false;
1403
1404 MachineFunction &MF = *MBB.getParent();
1405 MachineInstr &MI = *MII;
1406 MachineBasicBlock::iterator DefMII = prior(MII);
1407 MachineInstr *DefMI = DefMII;
1408 const TargetInstrDesc &TID = DefMI->getDesc();
1409 unsigned NewDstIdx;
1410 if (DefMII != MBB.begin() &&
1411 TID.isCommutable() &&
Evan Cheng261ce1d2009-07-10 19:15:51 +00001412 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001413 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1414 unsigned NewReg = NewDstMO.getReg();
1415 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1416 return false;
1417 MachineInstr *ReloadMI = prior(DefMII);
1418 int FrameIdx;
1419 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1420 if (DestReg != SrcReg || FrameIdx != SS)
1421 return false;
1422 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1423 if (UseIdx == -1)
1424 return false;
1425 unsigned DefIdx;
1426 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1427 return false;
1428 assert(DefMI->getOperand(DefIdx).isReg() &&
1429 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1430
1431 // Now commute def instruction.
1432 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1433 if (!CommutedMI)
1434 return false;
1435 SmallVector<unsigned, 1> Ops;
1436 Ops.push_back(NewDstIdx);
1437 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1438 // Not needed since foldMemoryOperand returns new MI.
1439 MF.DeleteMachineInstr(CommutedMI);
1440 if (!FoldedMI)
1441 return false;
1442
1443 VRM.addSpillSlotUse(SS, FoldedMI);
1444 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1445 // Insert new def MI and spill MI.
1446 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1447 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1448 MII = prior(MII);
1449 MachineInstr *StoreMI = MII;
1450 VRM.addSpillSlotUse(SS, StoreMI);
1451 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1452 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1453
1454 // Delete all 3 old instructions.
Evan Cheng427a6b62009-05-15 06:48:19 +00001455 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001456 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1457 MBB.erase(ReloadMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001458 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001459 VRM.RemoveMachineInstrFromMaps(DefMI);
1460 MBB.erase(DefMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001461 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001462 VRM.RemoveMachineInstrFromMaps(&MI);
1463 MBB.erase(&MI);
1464
1465 // If NewReg was previously holding value of some SS, it's now clobbered.
1466 // This has to be done now because it's a physical register. When this
1467 // instruction is re-visited, it's ignored.
1468 Spills.ClobberPhysReg(NewReg);
1469
1470 ++NumCommutes;
1471 return true;
1472 }
1473
1474 return false;
1475 }
1476
1477 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1478 /// the last store to the same slot is now dead. If so, remove the last store.
1479 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1480 MachineBasicBlock::iterator &MII,
1481 int Idx, unsigned PhysReg, int StackSlot,
1482 const TargetRegisterClass *RC,
1483 bool isAvailable, MachineInstr *&LastStore,
1484 AvailableSpills &Spills,
1485 SmallSet<MachineInstr*, 4> &ReMatDefs,
1486 BitVector &RegKills,
1487 std::vector<MachineOperand*> &KillOps,
1488 VirtRegMap &VRM) {
1489
Chris Lattner7896c9f2009-12-03 00:50:42 +00001490 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1491 TII->storeRegToStackSlot(MBB, llvm::next(MII), PhysReg, true, StackSlot, RC);
Dale Johannesen78c5cda2009-10-29 01:15:40 +00001492 MachineInstr *StoreMI = prior(oldNextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001493 VRM.addSpillSlotUse(StackSlot, StoreMI);
David Greene0ee52182010-01-05 01:25:52 +00001494 DEBUG(dbgs() << "Store:\t" << *StoreMI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001495
1496 // If there is a dead store to this stack slot, nuke it now.
1497 if (LastStore) {
David Greene0ee52182010-01-05 01:25:52 +00001498 DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
Lang Hames87e3bca2009-05-06 02:36:21 +00001499 ++NumDSE;
1500 SmallVector<unsigned, 2> KillRegs;
Evan Cheng427a6b62009-05-15 06:48:19 +00001501 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
Lang Hames87e3bca2009-05-06 02:36:21 +00001502 MachineBasicBlock::iterator PrevMII = LastStore;
1503 bool CheckDef = PrevMII != MBB.begin();
1504 if (CheckDef)
1505 --PrevMII;
1506 VRM.RemoveMachineInstrFromMaps(LastStore);
1507 MBB.erase(LastStore);
1508 if (CheckDef) {
1509 // Look at defs of killed registers on the store. Mark the defs
1510 // as dead since the store has been deleted and they aren't
1511 // being reused.
1512 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1513 bool HasOtherDef = false;
Evan Cheng8fdd84c2009-11-14 02:09:09 +00001514 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001515 MachineInstr *DeadDef = PrevMII;
1516 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
Evan Cheng4784f1f2009-06-30 08:49:04 +00001517 // FIXME: This assumes a remat def does not have side effects.
Lang Hames87e3bca2009-05-06 02:36:21 +00001518 VRM.RemoveMachineInstrFromMaps(DeadDef);
1519 MBB.erase(DeadDef);
1520 ++NumDRM;
1521 }
1522 }
1523 }
1524 }
1525 }
1526
Dale Johannesene841d2f2009-10-28 21:56:18 +00001527 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1528 // the last of multiple instructions is the actual store.
1529 LastStore = prior(oldNextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001530
1531 // If the stack slot value was previously available in some other
1532 // register, change it now. Otherwise, make the register available,
1533 // in PhysReg.
1534 Spills.ModifyStackSlotOrReMat(StackSlot);
1535 Spills.ClobberPhysReg(PhysReg);
1536 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1537 ++NumStores;
1538 }
1539
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001540 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1541 /// effect and all of its defs are dead.
1542 static bool isSafeToDelete(MachineInstr &MI) {
1543 const TargetInstrDesc &TID = MI.getDesc();
1544 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1545 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1546 TID.hasUnmodeledSideEffects())
1547 return false;
1548 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1549 MachineOperand &MO = MI.getOperand(i);
1550 if (!MO.isReg() || !MO.getReg())
1551 continue;
1552 if (MO.isDef() && !MO.isDead())
1553 return false;
1554 if (MO.isUse() && MO.isKill())
1555 // FIXME: We can't remove kill markers or else the scavenger will assert.
1556 // An alternative is to add a ADD pseudo instruction to replace kill
1557 // markers.
1558 return false;
1559 }
1560 return true;
1561 }
1562
Lang Hames87e3bca2009-05-06 02:36:21 +00001563 /// TransferDeadness - A identity copy definition is dead and it's being
1564 /// removed. Find the last def or use and mark it as dead / kill.
1565 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1566 unsigned Reg, BitVector &RegKills,
Evan Chengeca24fb2009-05-12 23:07:00 +00001567 std::vector<MachineOperand*> &KillOps,
1568 VirtRegMap &VRM) {
1569 SmallPtrSet<MachineInstr*, 4> Seens;
1570 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
Lang Hames87e3bca2009-05-06 02:36:21 +00001571 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1572 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1573 MachineInstr *UDMI = &*RI;
1574 if (UDMI->getParent() != MBB)
1575 continue;
1576 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1577 if (DI == DistanceMap.end() || DI->second > CurDist)
1578 continue;
Evan Chengeca24fb2009-05-12 23:07:00 +00001579 if (Seens.insert(UDMI))
1580 Refs.push_back(std::make_pair(UDMI, DI->second));
Lang Hames87e3bca2009-05-06 02:36:21 +00001581 }
1582
Evan Chengeca24fb2009-05-12 23:07:00 +00001583 if (Refs.empty())
1584 return;
1585 std::sort(Refs.begin(), Refs.end(), RefSorter());
1586
1587 while (!Refs.empty()) {
1588 MachineInstr *LastUDMI = Refs.back().first;
1589 Refs.pop_back();
1590
Lang Hames87e3bca2009-05-06 02:36:21 +00001591 MachineOperand *LastUD = NULL;
1592 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1593 MachineOperand &MO = LastUDMI->getOperand(i);
1594 if (!MO.isReg() || MO.getReg() != Reg)
1595 continue;
1596 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1597 LastUD = &MO;
1598 if (LastUDMI->isRegTiedToDefOperand(i))
Evan Chengeca24fb2009-05-12 23:07:00 +00001599 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001600 }
Evan Chengeca24fb2009-05-12 23:07:00 +00001601 if (LastUD->isDef()) {
1602 // If the instruction has no side effect, delete it and propagate
1603 // backward further. Otherwise, mark is dead and we are done.
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001604 if (!isSafeToDelete(*LastUDMI)) {
Evan Chengeca24fb2009-05-12 23:07:00 +00001605 LastUD->setIsDead();
1606 break;
1607 }
1608 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1609 MBB->erase(LastUDMI);
1610 } else {
Lang Hames87e3bca2009-05-06 02:36:21 +00001611 LastUD->setIsKill();
1612 RegKills.set(Reg);
1613 KillOps[Reg] = LastUD;
Evan Chengeca24fb2009-05-12 23:07:00 +00001614 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001615 }
1616 }
1617 }
1618
1619 /// rewriteMBB - Keep track of which spills are available even after the
1620 /// register allocator is done with them. If possible, avid reloading vregs.
1621 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1622 LiveIntervals *LIs,
1623 AvailableSpills &Spills, BitVector &RegKills,
1624 std::vector<MachineOperand*> &KillOps) {
1625
David Greene0ee52182010-01-05 01:25:52 +00001626 DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001627 << MBB.getName() << "':\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001628
1629 MachineFunction &MF = *MBB.getParent();
1630
1631 // MaybeDeadStores - When we need to write a value back into a stack slot,
1632 // keep track of the inserted store. If the stack slot value is never read
1633 // (because the value was used from some available register, for example), and
1634 // subsequently stored to, the original store is dead. This map keeps track
1635 // of inserted stores that are not used. If we see a subsequent store to the
1636 // same stack slot, the original store is deleted.
1637 std::vector<MachineInstr*> MaybeDeadStores;
1638 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1639
1640 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1641 SmallSet<MachineInstr*, 4> ReMatDefs;
1642
1643 // Clear kill info.
1644 SmallSet<unsigned, 2> KilledMIRegs;
1645 RegKills.reset();
1646 KillOps.clear();
1647 KillOps.resize(TRI->getNumRegs(), NULL);
1648
1649 unsigned Dist = 0;
1650 DistanceMap.clear();
1651 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1652 MII != E; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001653 MachineBasicBlock::iterator NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001654
1655 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1656 bool Erased = false;
1657 bool BackTracked = false;
1658 if (OptimizeByUnfold(MBB, MII,
1659 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
Chris Lattner7896c9f2009-12-03 00:50:42 +00001660 NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001661
1662 MachineInstr &MI = *MII;
1663
1664 if (VRM.hasEmergencySpills(&MI)) {
1665 // Spill physical register(s) in the rare case the allocator has run out
1666 // of registers to allocate.
1667 SmallSet<int, 4> UsedSS;
1668 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1669 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1670 unsigned PhysReg = EmSpills[i];
1671 const TargetRegisterClass *RC =
1672 TRI->getPhysicalRegisterRegClass(PhysReg);
1673 assert(RC && "Unable to determine register class!");
1674 int SS = VRM.getEmergencySpillSlot(RC);
1675 if (UsedSS.count(SS))
Torok Edwinc23197a2009-07-14 16:55:14 +00001676 llvm_unreachable("Need to spill more than one physical registers!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001677 UsedSS.insert(SS);
1678 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1679 MachineInstr *StoreMI = prior(MII);
1680 VRM.addSpillSlotUse(SS, StoreMI);
David Greene2d4e6d32009-07-28 16:49:24 +00001681
1682 // Back-schedule reloads and remats.
1683 MachineBasicBlock::iterator InsertLoc =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001684 ComputeReloadLoc(llvm::next(MII), MBB.begin(), PhysReg, TRI, false,
David Greene2d4e6d32009-07-28 16:49:24 +00001685 SS, TII, MF);
1686
1687 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SS, RC);
1688
1689 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00001690 VRM.addSpillSlotUse(SS, LoadMI);
1691 ++NumPSpills;
Jakob Stoklund Olesen7a1e8722009-08-15 11:03:03 +00001692 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00001693 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001694 NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001695 }
1696
1697 // Insert restores here if asked to.
1698 if (VRM.isRestorePt(&MI)) {
1699 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1700 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1701 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1702 if (!VRM.getPreSplitReg(VirtReg))
1703 continue; // Split interval spilled again.
1704 unsigned Phys = VRM.getPhys(VirtReg);
1705 RegInfo->setPhysRegUsed(Phys);
1706
1707 // Check if the value being restored if available. If so, it must be
1708 // from a predecessor BB that fallthrough into this BB. We do not
1709 // expect:
1710 // BB1:
1711 // r1 = load fi#1
1712 // ...
1713 // = r1<kill>
1714 // ... # r1 not clobbered
1715 // ...
1716 // = load fi#1
1717 bool DoReMat = VRM.isReMaterialized(VirtReg);
1718 int SSorRMId = DoReMat
1719 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1720 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1721 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1722 if (InReg == Phys) {
1723 // If the value is already available in the expected register, save
1724 // a reload / remat.
1725 if (SSorRMId)
David Greene0ee52182010-01-05 01:25:52 +00001726 DEBUG(dbgs() << "Reusing RM#"
Chris Lattner6456d382009-08-23 03:20:44 +00001727 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001728 else
David Greene0ee52182010-01-05 01:25:52 +00001729 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1730 DEBUG(dbgs() << " from physreg "
Chris Lattner6456d382009-08-23 03:20:44 +00001731 << TRI->getName(InReg) << " for vreg"
1732 << VirtReg <<" instead of reloading into physreg "
1733 << TRI->getName(Phys) << '\n');
Lang Hames87e3bca2009-05-06 02:36:21 +00001734 ++NumOmitted;
1735 continue;
1736 } else if (InReg && InReg != Phys) {
1737 if (SSorRMId)
David Greene0ee52182010-01-05 01:25:52 +00001738 DEBUG(dbgs() << "Reusing RM#"
Chris Lattner6456d382009-08-23 03:20:44 +00001739 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001740 else
David Greene0ee52182010-01-05 01:25:52 +00001741 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1742 DEBUG(dbgs() << " from physreg "
Chris Lattner6456d382009-08-23 03:20:44 +00001743 << TRI->getName(InReg) << " for vreg"
1744 << VirtReg <<" by copying it into physreg "
1745 << TRI->getName(Phys) << '\n');
Lang Hames87e3bca2009-05-06 02:36:21 +00001746
1747 // If the reloaded / remat value is available in another register,
1748 // copy it to the desired register.
David Greene2d4e6d32009-07-28 16:49:24 +00001749
1750 // Back-schedule reloads and remats.
1751 MachineBasicBlock::iterator InsertLoc =
1752 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1753 SSorRMId, TII, MF);
1754
1755 TII->copyRegToReg(MBB, InsertLoc, Phys, InReg, RC, RC);
Lang Hames87e3bca2009-05-06 02:36:21 +00001756
1757 // This invalidates Phys.
1758 Spills.ClobberPhysReg(Phys);
1759 // Remember it's available.
1760 Spills.addAvailable(SSorRMId, Phys);
1761
1762 // Mark is killed.
David Greene2d4e6d32009-07-28 16:49:24 +00001763 MachineInstr *CopyMI = prior(InsertLoc);
Chris Lattner45282ae2010-02-10 01:23:18 +00001764 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
Lang Hames87e3bca2009-05-06 02:36:21 +00001765 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1766 KillOpnd->setIsKill();
Evan Cheng427a6b62009-05-15 06:48:19 +00001767 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001768
David Greene0ee52182010-01-05 01:25:52 +00001769 DEBUG(dbgs() << '\t' << *CopyMI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001770 ++NumCopified;
1771 continue;
1772 }
1773
David Greene2d4e6d32009-07-28 16:49:24 +00001774 // Back-schedule reloads and remats.
1775 MachineBasicBlock::iterator InsertLoc =
1776 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1777 SSorRMId, TII, MF);
1778
Lang Hames87e3bca2009-05-06 02:36:21 +00001779 if (VRM.isReMaterialized(VirtReg)) {
David Greene2d4e6d32009-07-28 16:49:24 +00001780 ReMaterialize(MBB, InsertLoc, Phys, VirtReg, TII, TRI, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00001781 } else {
1782 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
David Greene2d4e6d32009-07-28 16:49:24 +00001783 TII->loadRegFromStackSlot(MBB, InsertLoc, Phys, SSorRMId, RC);
1784 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00001785 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1786 ++NumLoads;
Jakob Stoklund Olesen7a1e8722009-08-15 11:03:03 +00001787 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00001788 }
1789
1790 // This invalidates Phys.
1791 Spills.ClobberPhysReg(Phys);
1792 // Remember it's available.
1793 Spills.addAvailable(SSorRMId, Phys);
1794
David Greene2d4e6d32009-07-28 16:49:24 +00001795 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
David Greene0ee52182010-01-05 01:25:52 +00001796 DEBUG(dbgs() << '\t' << *prior(MII));
Lang Hames87e3bca2009-05-06 02:36:21 +00001797 }
1798 }
1799
1800 // Insert spills here if asked to.
1801 if (VRM.isSpillPt(&MI)) {
1802 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1803 VRM.getSpillPtSpills(&MI);
1804 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1805 unsigned VirtReg = SpillRegs[i].first;
1806 bool isKill = SpillRegs[i].second;
1807 if (!VRM.getPreSplitReg(VirtReg))
1808 continue; // Split interval spilled again.
1809 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1810 unsigned Phys = VRM.getPhys(VirtReg);
1811 int StackSlot = VRM.getStackSlot(VirtReg);
Chris Lattner7896c9f2009-12-03 00:50:42 +00001812 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1813 TII->storeRegToStackSlot(MBB, llvm::next(MII), Phys, isKill, StackSlot, RC);
Dale Johannesen78c5cda2009-10-29 01:15:40 +00001814 MachineInstr *StoreMI = prior(oldNextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001815 VRM.addSpillSlotUse(StackSlot, StoreMI);
David Greene0ee52182010-01-05 01:25:52 +00001816 DEBUG(dbgs() << "Store:\t" << *StoreMI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001817 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1818 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001819 NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001820 }
1821
1822 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1823 /// reuse.
1824 ReuseInfo ReusedOperands(MI, TRI);
1825 SmallVector<unsigned, 4> VirtUseOps;
1826 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1827 MachineOperand &MO = MI.getOperand(i);
1828 if (!MO.isReg() || MO.getReg() == 0)
1829 continue; // Ignore non-register operands.
1830
1831 unsigned VirtReg = MO.getReg();
1832 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1833 // Ignore physregs for spilling, but remember that it is used by this
1834 // function.
1835 RegInfo->setPhysRegUsed(VirtReg);
1836 continue;
1837 }
1838
1839 // We want to process implicit virtual register uses first.
1840 if (MO.isImplicit())
1841 // If the virtual register is implicitly defined, emit a implicit_def
1842 // before so scavenger knows it's "defined".
Evan Cheng4784f1f2009-06-30 08:49:04 +00001843 // FIXME: This is a horrible hack done the by register allocator to
1844 // remat a definition with virtual register operand.
Lang Hames87e3bca2009-05-06 02:36:21 +00001845 VirtUseOps.insert(VirtUseOps.begin(), i);
1846 else
1847 VirtUseOps.push_back(i);
1848 }
1849
1850 // Process all of the spilled uses and all non spilled reg references.
1851 SmallVector<int, 2> PotentialDeadStoreSlots;
1852 KilledMIRegs.clear();
1853 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1854 unsigned i = VirtUseOps[j];
Jakob Stoklund Olesend135f142010-02-13 02:06:10 +00001855 unsigned VirtReg = MI.getOperand(i).getReg();
Lang Hames87e3bca2009-05-06 02:36:21 +00001856 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1857 "Not a virtual register?");
1858
Jakob Stoklund Olesend135f142010-02-13 02:06:10 +00001859 unsigned SubIdx = MI.getOperand(i).getSubReg();
Lang Hames87e3bca2009-05-06 02:36:21 +00001860 if (VRM.isAssignedReg(VirtReg)) {
1861 // This virtual register was assigned a physreg!
1862 unsigned Phys = VRM.getPhys(VirtReg);
1863 RegInfo->setPhysRegUsed(Phys);
Jakob Stoklund Olesend135f142010-02-13 02:06:10 +00001864 if (MI.getOperand(i).isDef())
Lang Hames87e3bca2009-05-06 02:36:21 +00001865 ReusedOperands.markClobbered(Phys);
Jakob Stoklund Olesend135f142010-02-13 02:06:10 +00001866 substitutePhysReg(MI.getOperand(i), Phys, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001867 if (VRM.isImplicitlyDefined(VirtReg))
Evan Cheng4784f1f2009-06-30 08:49:04 +00001868 // FIXME: Is this needed?
Lang Hames87e3bca2009-05-06 02:36:21 +00001869 BuildMI(MBB, &MI, MI.getDebugLoc(),
Chris Lattner518bb532010-02-09 19:54:29 +00001870 TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
Lang Hames87e3bca2009-05-06 02:36:21 +00001871 continue;
1872 }
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001873
Lang Hames87e3bca2009-05-06 02:36:21 +00001874 // This virtual register is now known to be a spilled value.
Jakob Stoklund Olesend135f142010-02-13 02:06:10 +00001875 if (!MI.getOperand(i).isUse())
Lang Hames87e3bca2009-05-06 02:36:21 +00001876 continue; // Handle defs in the loop below (handle use&def here though)
1877
Jakob Stoklund Olesend135f142010-02-13 02:06:10 +00001878 bool AvoidReload = MI.getOperand(i).isUndef();
Evan Cheng4784f1f2009-06-30 08:49:04 +00001879 // Check if it is defined by an implicit def. It should not be spilled.
1880 // Note, this is for correctness reason. e.g.
1881 // 8 %reg1024<def> = IMPLICIT_DEF
1882 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1883 // The live range [12, 14) are not part of the r1024 live interval since
1884 // it's defined by an implicit def. It will not conflicts with live
1885 // interval of r1025. Now suppose both registers are spilled, you can
1886 // easily see a situation where both registers are reloaded before
1887 // the INSERT_SUBREG and both target registers that would overlap.
Lang Hames87e3bca2009-05-06 02:36:21 +00001888 bool DoReMat = VRM.isReMaterialized(VirtReg);
1889 int SSorRMId = DoReMat
1890 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1891 int ReuseSlot = SSorRMId;
1892
1893 // Check to see if this stack slot is available.
1894 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1895
1896 // If this is a sub-register use, make sure the reuse register is in the
1897 // right register class. For example, for x86 not all of the 32-bit
1898 // registers have accessible sub-registers.
1899 // Similarly so for EXTRACT_SUBREG. Consider this:
1900 // EDI = op
1901 // MOV32_mr fi#1, EDI
1902 // ...
1903 // = EXTRACT_SUBREG fi#1
1904 // fi#1 is available in EDI, but it cannot be reused because it's not in
1905 // the right register file.
Chris Lattner518bb532010-02-09 19:54:29 +00001906 if (PhysReg && !AvoidReload && (SubIdx || MI.isExtractSubreg())) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001907 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1908 if (!RC->contains(PhysReg))
1909 PhysReg = 0;
1910 }
1911
1912 if (PhysReg && !AvoidReload) {
1913 // This spilled operand might be part of a two-address operand. If this
1914 // is the case, then changing it will necessarily require changing the
1915 // def part of the instruction as well. However, in some cases, we
1916 // aren't allowed to modify the reused register. If none of these cases
1917 // apply, reuse it.
1918 bool CanReuse = true;
1919 bool isTied = MI.isRegTiedToDefOperand(i);
1920 if (isTied) {
1921 // Okay, we have a two address operand. We can reuse this physreg as
1922 // long as we are allowed to clobber the value and there isn't an
1923 // earlier def that has already clobbered the physreg.
1924 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1925 Spills.canClobberPhysReg(PhysReg);
1926 }
1927
1928 if (CanReuse) {
1929 // If this stack slot value is already available, reuse it!
1930 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
David Greene0ee52182010-01-05 01:25:52 +00001931 DEBUG(dbgs() << "Reusing RM#"
Chris Lattner6456d382009-08-23 03:20:44 +00001932 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001933 else
David Greene0ee52182010-01-05 01:25:52 +00001934 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
1935 DEBUG(dbgs() << " from physreg "
Chris Lattner6456d382009-08-23 03:20:44 +00001936 << TRI->getName(PhysReg) << " for vreg"
1937 << VirtReg <<" instead of reloading into physreg "
1938 << TRI->getName(VRM.getPhys(VirtReg)) << '\n');
Lang Hames87e3bca2009-05-06 02:36:21 +00001939 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1940 MI.getOperand(i).setReg(RReg);
1941 MI.getOperand(i).setSubReg(0);
1942
1943 // The only technical detail we have is that we don't know that
1944 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1945 // later in the instruction. In particular, consider 'op V1, V2'.
1946 // If V1 is available in physreg R0, we would choose to reuse it
1947 // here, instead of reloading it into the register the allocator
1948 // indicated (say R1). However, V2 might have to be reloaded
1949 // later, and it might indicate that it needs to live in R0. When
1950 // this occurs, we need to have information available that
1951 // indicates it is safe to use R1 for the reload instead of R0.
1952 //
1953 // To further complicate matters, we might conflict with an alias,
1954 // or R0 and R1 might not be compatible with each other. In this
1955 // case, we actually insert a reload for V1 in R1, ensuring that
1956 // we can get at R0 or its alias.
1957 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1958 VRM.getPhys(VirtReg), VirtReg);
1959 if (isTied)
1960 // Only mark it clobbered if this is a use&def operand.
1961 ReusedOperands.markClobbered(PhysReg);
1962 ++NumReused;
1963
1964 if (MI.getOperand(i).isKill() &&
1965 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1966
1967 // The store of this spilled value is potentially dead, but we
1968 // won't know for certain until we've confirmed that the re-use
1969 // above is valid, which means waiting until the other operands
1970 // are processed. For now we just track the spill slot, we'll
1971 // remove it after the other operands are processed if valid.
1972
1973 PotentialDeadStoreSlots.push_back(ReuseSlot);
1974 }
1975
1976 // Mark is isKill if it's there no other uses of the same virtual
1977 // register and it's not a two-address operand. IsKill will be
1978 // unset if reg is reused.
1979 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1980 MI.getOperand(i).setIsKill();
1981 KilledMIRegs.insert(VirtReg);
1982 }
1983
1984 continue;
1985 } // CanReuse
1986
1987 // Otherwise we have a situation where we have a two-address instruction
1988 // whose mod/ref operand needs to be reloaded. This reload is already
1989 // available in some register "PhysReg", but if we used PhysReg as the
1990 // operand to our 2-addr instruction, the instruction would modify
1991 // PhysReg. This isn't cool if something later uses PhysReg and expects
1992 // to get its initial value.
1993 //
1994 // To avoid this problem, and to avoid doing a load right after a store,
1995 // we emit a copy from PhysReg into the designated register for this
1996 // operand.
1997 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1998 assert(DesignatedReg && "Must map virtreg to physreg!");
1999
2000 // Note that, if we reused a register for a previous operand, the
2001 // register we want to reload into might not actually be
2002 // available. If this occurs, use the register indicated by the
2003 // reuser.
2004 if (ReusedOperands.hasReuses())
Evan Cheng5d885022009-07-21 09:15:00 +00002005 DesignatedReg = ReusedOperands.GetRegForReload(VirtReg,
2006 DesignatedReg, &MI,
2007 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002008
2009 // If the mapped designated register is actually the physreg we have
2010 // incoming, we don't need to inserted a dead copy.
2011 if (DesignatedReg == PhysReg) {
2012 // If this stack slot value is already available, reuse it!
2013 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
David Greene0ee52182010-01-05 01:25:52 +00002014 DEBUG(dbgs() << "Reusing RM#"
Chris Lattner6456d382009-08-23 03:20:44 +00002015 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00002016 else
David Greene0ee52182010-01-05 01:25:52 +00002017 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2018 DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
Chris Lattner6456d382009-08-23 03:20:44 +00002019 << " for vreg" << VirtReg
2020 << " instead of reloading into same physreg.\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00002021 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2022 MI.getOperand(i).setReg(RReg);
2023 MI.getOperand(i).setSubReg(0);
2024 ReusedOperands.markClobbered(RReg);
2025 ++NumReused;
2026 continue;
2027 }
2028
2029 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
2030 RegInfo->setPhysRegUsed(DesignatedReg);
2031 ReusedOperands.markClobbered(DesignatedReg);
Lang Hames87e3bca2009-05-06 02:36:21 +00002032
David Greene2d4e6d32009-07-28 16:49:24 +00002033 // Back-schedule reloads and remats.
2034 MachineBasicBlock::iterator InsertLoc =
2035 ComputeReloadLoc(&MI, MBB.begin(), PhysReg, TRI, DoReMat,
2036 SSorRMId, TII, MF);
2037
2038 TII->copyRegToReg(MBB, InsertLoc, DesignatedReg, PhysReg, RC, RC);
2039
2040 MachineInstr *CopyMI = prior(InsertLoc);
Chris Lattner45282ae2010-02-10 01:23:18 +00002041 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
Evan Cheng427a6b62009-05-15 06:48:19 +00002042 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002043
2044 // This invalidates DesignatedReg.
2045 Spills.ClobberPhysReg(DesignatedReg);
2046
2047 Spills.addAvailable(ReuseSlot, DesignatedReg);
2048 unsigned RReg =
2049 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2050 MI.getOperand(i).setReg(RReg);
2051 MI.getOperand(i).setSubReg(0);
David Greene0ee52182010-01-05 01:25:52 +00002052 DEBUG(dbgs() << '\t' << *prior(MII));
Lang Hames87e3bca2009-05-06 02:36:21 +00002053 ++NumReused;
2054 continue;
2055 } // if (PhysReg)
2056
2057 // Otherwise, reload it and remember that we have it.
2058 PhysReg = VRM.getPhys(VirtReg);
2059 assert(PhysReg && "Must map virtreg to physreg!");
2060
2061 // Note that, if we reused a register for a previous operand, the
2062 // register we want to reload into might not actually be
2063 // available. If this occurs, use the register indicated by the
2064 // reuser.
2065 if (ReusedOperands.hasReuses())
Evan Cheng5d885022009-07-21 09:15:00 +00002066 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2067 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002068
2069 RegInfo->setPhysRegUsed(PhysReg);
2070 ReusedOperands.markClobbered(PhysReg);
2071 if (AvoidReload)
2072 ++NumAvoided;
2073 else {
David Greene2d4e6d32009-07-28 16:49:24 +00002074 // Back-schedule reloads and remats.
2075 MachineBasicBlock::iterator InsertLoc =
2076 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, DoReMat,
2077 SSorRMId, TII, MF);
2078
Lang Hames87e3bca2009-05-06 02:36:21 +00002079 if (DoReMat) {
David Greene2d4e6d32009-07-28 16:49:24 +00002080 ReMaterialize(MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002081 } else {
2082 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
David Greene2d4e6d32009-07-28 16:49:24 +00002083 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SSorRMId, RC);
2084 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00002085 VRM.addSpillSlotUse(SSorRMId, LoadMI);
2086 ++NumLoads;
Jakob Stoklund Olesen7a1e8722009-08-15 11:03:03 +00002087 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00002088 }
2089 // This invalidates PhysReg.
2090 Spills.ClobberPhysReg(PhysReg);
2091
2092 // Any stores to this stack slot are not dead anymore.
2093 if (!DoReMat)
2094 MaybeDeadStores[SSorRMId] = NULL;
2095 Spills.addAvailable(SSorRMId, PhysReg);
2096 // Assumes this is the last use. IsKill will be unset if reg is reused
2097 // unless it's a two-address operand.
2098 if (!MI.isRegTiedToDefOperand(i) &&
2099 KilledMIRegs.count(VirtReg) == 0) {
2100 MI.getOperand(i).setIsKill();
2101 KilledMIRegs.insert(VirtReg);
2102 }
2103
David Greene2d4e6d32009-07-28 16:49:24 +00002104 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
David Greene0ee52182010-01-05 01:25:52 +00002105 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
Lang Hames87e3bca2009-05-06 02:36:21 +00002106 }
2107 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2108 MI.getOperand(i).setReg(RReg);
2109 MI.getOperand(i).setSubReg(0);
2110 }
2111
2112 // Ok - now we can remove stores that have been confirmed dead.
2113 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2114 // This was the last use and the spilled value is still available
2115 // for reuse. That means the spill was unnecessary!
2116 int PDSSlot = PotentialDeadStoreSlots[j];
2117 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2118 if (DeadStore) {
David Greene0ee52182010-01-05 01:25:52 +00002119 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002120 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002121 VRM.RemoveMachineInstrFromMaps(DeadStore);
2122 MBB.erase(DeadStore);
2123 MaybeDeadStores[PDSSlot] = NULL;
2124 ++NumDSE;
2125 }
2126 }
2127
2128
David Greene0ee52182010-01-05 01:25:52 +00002129 DEBUG(dbgs() << '\t' << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002130
2131
2132 // If we have folded references to memory operands, make sure we clear all
2133 // physical registers that may contain the value of the spilled virtual
2134 // register
2135 SmallSet<int, 2> FoldedSS;
2136 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
2137 unsigned VirtReg = I->second.first;
2138 VirtRegMap::ModRef MR = I->second.second;
David Greene0ee52182010-01-05 01:25:52 +00002139 DEBUG(dbgs() << "Folded vreg: " << VirtReg << " MR: " << MR);
Lang Hames87e3bca2009-05-06 02:36:21 +00002140
2141 // MI2VirtMap be can updated which invalidate the iterator.
2142 // Increment the iterator first.
2143 ++I;
2144 int SS = VRM.getStackSlot(VirtReg);
2145 if (SS == VirtRegMap::NO_STACK_SLOT)
2146 continue;
2147 FoldedSS.insert(SS);
David Greene0ee52182010-01-05 01:25:52 +00002148 DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00002149
2150 // If this folded instruction is just a use, check to see if it's a
2151 // straight load from the virt reg slot.
2152 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2153 int FrameIdx;
2154 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2155 if (DestReg && FrameIdx == SS) {
2156 // If this spill slot is available, turn it into a copy (or nothing)
2157 // instead of leaving it as a load!
2158 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
David Greene0ee52182010-01-05 01:25:52 +00002159 DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002160 if (DestReg != InReg) {
2161 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2162 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
2163 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2164 unsigned SubIdx = DefMO->getSubReg();
2165 // Revisit the copy so we make sure to notice the effects of the
2166 // operation on the destreg (either needing to RA it if it's
2167 // virtual or needing to clobber any values if it's physical).
2168 NextMII = &MI;
2169 --NextMII; // backtrack to the copy.
Chris Lattner45282ae2010-02-10 01:23:18 +00002170 NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
Lang Hames87e3bca2009-05-06 02:36:21 +00002171 // Propagate the sub-register index over.
2172 if (SubIdx) {
2173 DefMO = NextMII->findRegisterDefOperand(DestReg);
2174 DefMO->setSubReg(SubIdx);
2175 }
2176
2177 // Mark is killed.
2178 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
2179 KillOpnd->setIsKill();
2180
2181 BackTracked = true;
2182 } else {
David Greene0ee52182010-01-05 01:25:52 +00002183 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002184 // Unset last kill since it's being reused.
Evan Cheng427a6b62009-05-15 06:48:19 +00002185 InvalidateKill(InReg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002186 Spills.disallowClobberPhysReg(InReg);
2187 }
2188
Evan Cheng427a6b62009-05-15 06:48:19 +00002189 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002190 VRM.RemoveMachineInstrFromMaps(&MI);
2191 MBB.erase(&MI);
2192 Erased = true;
2193 goto ProcessNextInst;
2194 }
2195 } else {
2196 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2197 SmallVector<MachineInstr*, 4> NewMIs;
2198 if (PhysReg &&
2199 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2200 MBB.insert(MII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00002201 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002202 VRM.RemoveMachineInstrFromMaps(&MI);
2203 MBB.erase(&MI);
2204 Erased = true;
2205 --NextMII; // backtrack to the unfolded instruction.
2206 BackTracked = true;
2207 goto ProcessNextInst;
2208 }
2209 }
2210 }
2211
2212 // If this reference is not a use, any previous store is now dead.
2213 // Otherwise, the store to this stack slot is not dead anymore.
2214 MachineInstr* DeadStore = MaybeDeadStores[SS];
2215 if (DeadStore) {
2216 bool isDead = !(MR & VirtRegMap::isRef);
2217 MachineInstr *NewStore = NULL;
2218 if (MR & VirtRegMap::isModRef) {
2219 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2220 SmallVector<MachineInstr*, 4> NewMIs;
2221 // We can reuse this physreg as long as we are allowed to clobber
2222 // the value and there isn't an earlier def that has already clobbered
2223 // the physreg.
2224 if (PhysReg &&
2225 !ReusedOperands.isClobbered(PhysReg) &&
2226 Spills.canClobberPhysReg(PhysReg) &&
2227 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2228 MachineOperand *KillOpnd =
2229 DeadStore->findRegisterUseOperand(PhysReg, true);
2230 // Note, if the store is storing a sub-register, it's possible the
2231 // super-register is needed below.
2232 if (KillOpnd && !KillOpnd->getSubReg() &&
2233 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2234 MBB.insert(MII, NewMIs[0]);
2235 NewStore = NewMIs[1];
2236 MBB.insert(MII, NewStore);
2237 VRM.addSpillSlotUse(SS, NewStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002238 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002239 VRM.RemoveMachineInstrFromMaps(&MI);
2240 MBB.erase(&MI);
2241 Erased = true;
2242 --NextMII;
2243 --NextMII; // backtrack to the unfolded instruction.
2244 BackTracked = true;
2245 isDead = true;
2246 ++NumSUnfold;
2247 }
2248 }
2249 }
2250
2251 if (isDead) { // Previous store is dead.
2252 // If we get here, the store is dead, nuke it now.
David Greene0ee52182010-01-05 01:25:52 +00002253 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002254 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002255 VRM.RemoveMachineInstrFromMaps(DeadStore);
2256 MBB.erase(DeadStore);
2257 if (!NewStore)
2258 ++NumDSE;
2259 }
2260
2261 MaybeDeadStores[SS] = NULL;
2262 if (NewStore) {
2263 // Treat this store as a spill merged into a copy. That makes the
2264 // stack slot value available.
2265 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2266 goto ProcessNextInst;
2267 }
2268 }
2269
2270 // If the spill slot value is available, and this is a new definition of
2271 // the value, the value is not available anymore.
2272 if (MR & VirtRegMap::isMod) {
2273 // Notice that the value in this stack slot has been modified.
2274 Spills.ModifyStackSlotOrReMat(SS);
2275
2276 // If this is *just* a mod of the value, check to see if this is just a
2277 // store to the spill slot (i.e. the spill got merged into the copy). If
2278 // so, realize that the vreg is available now, and add the store to the
2279 // MaybeDeadStore info.
2280 int StackSlot;
2281 if (!(MR & VirtRegMap::isRef)) {
2282 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2283 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2284 "Src hasn't been allocated yet?");
2285
2286 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2287 Spills, RegKills, KillOps, TRI, VRM)) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00002288 NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00002289 BackTracked = true;
2290 goto ProcessNextInst;
2291 }
2292
2293 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2294 // this as a potentially dead store in case there is a subsequent
2295 // store into the stack slot without a read from it.
2296 MaybeDeadStores[StackSlot] = &MI;
2297
2298 // If the stack slot value was previously available in some other
2299 // register, change it now. Otherwise, make the register
2300 // available in PhysReg.
2301 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2302 }
2303 }
2304 }
2305 }
2306
2307 // Process all of the spilled defs.
2308 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2309 MachineOperand &MO = MI.getOperand(i);
2310 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2311 continue;
2312
2313 unsigned VirtReg = MO.getReg();
2314 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2315 // Check to see if this is a noop copy. If so, eliminate the
2316 // instruction before considering the dest reg to be changed.
Evan Cheng2578ba22009-07-01 01:59:31 +00002317 // Also check if it's copying from an "undef", if so, we can't
2318 // eliminate this or else the undef marker is lost and it will
2319 // confuses the scavenger. This is extremely rare.
Lang Hames87e3bca2009-05-06 02:36:21 +00002320 unsigned Src, Dst, SrcSR, DstSR;
Evan Chenga5dc45e2009-10-26 04:56:07 +00002321 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
Evan Cheng2578ba22009-07-01 01:59:31 +00002322 !MI.findRegisterUseOperand(Src)->isUndef()) {
Lang Hames87e3bca2009-05-06 02:36:21 +00002323 ++NumDCE;
David Greene0ee52182010-01-05 01:25:52 +00002324 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002325 SmallVector<unsigned, 2> KillRegs;
Evan Cheng427a6b62009-05-15 06:48:19 +00002326 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
Lang Hames87e3bca2009-05-06 02:36:21 +00002327 if (MO.isDead() && !KillRegs.empty()) {
2328 // Source register or an implicit super/sub-register use is killed.
2329 assert(KillRegs[0] == Dst ||
2330 TRI->isSubRegister(KillRegs[0], Dst) ||
2331 TRI->isSuperRegister(KillRegs[0], Dst));
2332 // Last def is now dead.
Evan Chengeca24fb2009-05-12 23:07:00 +00002333 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002334 }
2335 VRM.RemoveMachineInstrFromMaps(&MI);
2336 MBB.erase(&MI);
2337 Erased = true;
2338 Spills.disallowClobberPhysReg(VirtReg);
2339 goto ProcessNextInst;
2340 }
Evan Cheng2578ba22009-07-01 01:59:31 +00002341
Lang Hames87e3bca2009-05-06 02:36:21 +00002342 // If it's not a no-op copy, it clobbers the value in the destreg.
2343 Spills.ClobberPhysReg(VirtReg);
2344 ReusedOperands.markClobbered(VirtReg);
2345
2346 // Check to see if this instruction is a load from a stack slot into
2347 // a register. If so, this provides the stack slot value in the reg.
2348 int FrameIdx;
2349 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2350 assert(DestReg == VirtReg && "Unknown load situation!");
2351
2352 // If it is a folded reference, then it's not safe to clobber.
2353 bool Folded = FoldedSS.count(FrameIdx);
2354 // Otherwise, if it wasn't available, remember that it is now!
2355 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2356 goto ProcessNextInst;
2357 }
2358
2359 continue;
2360 }
2361
2362 unsigned SubIdx = MO.getSubReg();
2363 bool DoReMat = VRM.isReMaterialized(VirtReg);
2364 if (DoReMat)
2365 ReMatDefs.insert(&MI);
2366
2367 // The only vregs left are stack slot definitions.
2368 int StackSlot = VRM.getStackSlot(VirtReg);
2369 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2370
2371 // If this def is part of a two-address operand, make sure to execute
2372 // the store from the correct physical register.
2373 unsigned PhysReg;
2374 unsigned TiedOp;
2375 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2376 PhysReg = MI.getOperand(TiedOp).getReg();
2377 if (SubIdx) {
2378 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2379 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2380 "Can't find corresponding super-register!");
2381 PhysReg = SuperReg;
2382 }
2383 } else {
2384 PhysReg = VRM.getPhys(VirtReg);
2385 if (ReusedOperands.isClobbered(PhysReg)) {
2386 // Another def has taken the assigned physreg. It must have been a
2387 // use&def which got it due to reuse. Undo the reuse!
Evan Cheng5d885022009-07-21 09:15:00 +00002388 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2389 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002390 }
2391 }
2392
2393 assert(PhysReg && "VR not assigned a physical register?");
2394 RegInfo->setPhysRegUsed(PhysReg);
2395 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2396 ReusedOperands.markClobbered(RReg);
2397 MI.getOperand(i).setReg(RReg);
2398 MI.getOperand(i).setSubReg(0);
2399
2400 if (!MO.isDead()) {
2401 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2402 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2403 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
Chris Lattner7896c9f2009-12-03 00:50:42 +00002404 NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00002405
2406 // Check to see if this is a noop copy. If so, eliminate the
2407 // instruction before considering the dest reg to be changed.
2408 {
2409 unsigned Src, Dst, SrcSR, DstSR;
Evan Chenga5dc45e2009-10-26 04:56:07 +00002410 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
Lang Hames87e3bca2009-05-06 02:36:21 +00002411 ++NumDCE;
David Greene0ee52182010-01-05 01:25:52 +00002412 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
Evan Cheng427a6b62009-05-15 06:48:19 +00002413 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002414 VRM.RemoveMachineInstrFromMaps(&MI);
2415 MBB.erase(&MI);
2416 Erased = true;
Evan Cheng427a6b62009-05-15 06:48:19 +00002417 UpdateKills(*LastStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002418 goto ProcessNextInst;
2419 }
2420 }
2421 }
2422 }
2423 ProcessNextInst:
Evan Cheng52484682009-07-18 02:10:10 +00002424 // Delete dead instructions without side effects.
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00002425 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
Evan Cheng52484682009-07-18 02:10:10 +00002426 InvalidateKills(MI, TRI, RegKills, KillOps);
2427 VRM.RemoveMachineInstrFromMaps(&MI);
2428 MBB.erase(&MI);
2429 Erased = true;
2430 }
2431 if (!Erased)
2432 DistanceMap.insert(std::make_pair(&MI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00002433 if (!Erased && !BackTracked) {
2434 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
Evan Cheng427a6b62009-05-15 06:48:19 +00002435 UpdateKills(*II, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002436 }
2437 MII = NextMII;
2438 }
2439
2440 }
2441
2442};
2443
Dan Gohman7db949d2009-08-07 01:32:21 +00002444}
2445
Lang Hames87e3bca2009-05-06 02:36:21 +00002446llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2447 switch (RewriterOpt) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002448 default: llvm_unreachable("Unreachable!");
Lang Hames87e3bca2009-05-06 02:36:21 +00002449 case local:
2450 return new LocalRewriter();
Lang Hamesf41538d2009-06-02 16:53:25 +00002451 case trivial:
2452 return new TrivialRewriter();
Lang Hames87e3bca2009-05-06 02:36:21 +00002453 }
2454}