blob: ce625948424197c003104a1505f31a90fb55e988 [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",
49 cl::desc("Rewriter to use: (default: local)"),
50 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.
65static void substitutePhysReg(MachineOperand &MO, unsigned Reg,
66 const TargetRegisterInfo &TRI) {
67 if (unsigned SubIdx = MO.getSubReg()) {
68 // Insert the physical subreg and reset the subreg field.
69 MO.setReg(TRI.getSubReg(Reg, SubIdx));
70 MO.setSubReg(0);
71
72 // Any def, dead, and kill flags apply to the full virtual register, so they
73 // also apply to the full physical register. Add imp-def/dead and imp-kill
74 // as needed.
75 MachineInstr &MI = *MO.getParent();
76 if (MO.isDef())
77 if (MO.isDead())
78 MI.addRegisterDead(Reg, &TRI, /*AddIfNotFound=*/ true);
79 else
80 MI.addRegisterDefined(Reg, &TRI);
81 else if (!MO.isUndef() &&
82 (MO.isKill() ||
83 MI.isRegTiedToDefOperand(&MO-&MI.getOperand(0))))
84 MI.addRegisterKilled(Reg, &TRI, /*AddIfNotFound=*/ true);
85 } else {
86 MO.setReg(Reg);
87 }
88}
89
Dan Gohman7db949d2009-08-07 01:32:21 +000090namespace {
Lang Hames87e3bca2009-05-06 02:36:21 +000091
Lang Hamesf41538d2009-06-02 16:53:25 +000092/// This class is intended for use with the new spilling framework only. It
93/// rewrites vreg def/uses to use the assigned preg, but does not insert any
94/// spill code.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000095struct TrivialRewriter : public VirtRegRewriter {
Lang Hamesf41538d2009-06-02 16:53:25 +000096
97 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
98 LiveIntervals* LIs) {
David Greene0ee52182010-01-05 01:25:52 +000099 DEBUG(dbgs() << "********** REWRITE MACHINE CODE **********\n");
100 DEBUG(dbgs() << "********** Function: "
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000101 << MF.getFunction()->getName() << '\n');
David Greene0ee52182010-01-05 01:25:52 +0000102 DEBUG(dbgs() << "**** Machine Instrs"
Chris Lattner6456d382009-08-23 03:20:44 +0000103 << "(NOTE! Does not include spills and reloads!) ****\n");
David Greene2d4e6d32009-07-28 16:49:24 +0000104 DEBUG(MF.dump());
105
Lang Hamesf41538d2009-06-02 16:53:25 +0000106 MachineRegisterInfo *mri = &MF.getRegInfo();
Lang Hames38283e22009-11-18 20:31:20 +0000107 const TargetRegisterInfo *tri = MF.getTarget().getRegisterInfo();
Lang Hamesf41538d2009-06-02 16:53:25 +0000108
109 bool changed = false;
110
111 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
112 liItr != liEnd; ++liItr) {
113
Lang Hames38283e22009-11-18 20:31:20 +0000114 const LiveInterval *li = liItr->second;
115 unsigned reg = li->reg;
116
117 if (TargetRegisterInfo::isPhysicalRegister(reg)) {
118 if (!li->empty())
119 mri->setPhysRegUsed(reg);
120 }
121 else {
122 if (!VRM.hasPhys(reg))
123 continue;
124 unsigned pReg = VRM.getPhys(reg);
125 mri->setPhysRegUsed(pReg);
126 for (MachineRegisterInfo::reg_iterator regItr = mri->reg_begin(reg),
127 regEnd = mri->reg_end(); regItr != regEnd;) {
128 MachineOperand &mop = regItr.getOperand();
129 assert(mop.isReg() && mop.getReg() == reg && "reg_iterator broken?");
130 ++regItr;
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +0000131 substitutePhysReg(mop, pReg, *tri);
Lang Hamesf41538d2009-06-02 16:53:25 +0000132 changed = true;
133 }
134 }
Lang Hamesf41538d2009-06-02 16:53:25 +0000135 }
David Greene2d4e6d32009-07-28 16:49:24 +0000136
David Greene0ee52182010-01-05 01:25:52 +0000137 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
David Greene2d4e6d32009-07-28 16:49:24 +0000138 DEBUG(MF.dump());
Lang Hamesf41538d2009-06-02 16:53:25 +0000139
140 return changed;
141 }
142
143};
144
Dan Gohman7db949d2009-08-07 01:32:21 +0000145}
146
Lang Hames87e3bca2009-05-06 02:36:21 +0000147// ************************************************************************ //
148
Dan Gohman7db949d2009-08-07 01:32:21 +0000149namespace {
150
Lang Hames87e3bca2009-05-06 02:36:21 +0000151/// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
152/// from top down, keep track of which spill slots or remat are available in
153/// each register.
154///
155/// Note that not all physregs are created equal here. In particular, some
156/// physregs are reloads that we are allowed to clobber or ignore at any time.
157/// Other physregs are values that the register allocated program is using
158/// that we cannot CHANGE, but we can read if we like. We keep track of this
159/// on a per-stack-slot / remat id basis as the low bit in the value of the
160/// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
161/// this bit and addAvailable sets it if.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000162class AvailableSpills {
Lang Hames87e3bca2009-05-06 02:36:21 +0000163 const TargetRegisterInfo *TRI;
164 const TargetInstrInfo *TII;
165
166 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
167 // or remat'ed virtual register values that are still available, due to
168 // being loaded or stored to, but not invalidated yet.
169 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
170
171 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
172 // indicating which stack slot values are currently held by a physreg. This
173 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
174 // physreg is modified.
175 std::multimap<unsigned, int> PhysRegsAvailable;
176
177 void disallowClobberPhysRegOnly(unsigned PhysReg);
178
179 void ClobberPhysRegOnly(unsigned PhysReg);
180public:
181 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
182 : TRI(tri), TII(tii) {
183 }
184
185 /// clear - Reset the state.
186 void clear() {
187 SpillSlotsOrReMatsAvailable.clear();
188 PhysRegsAvailable.clear();
189 }
190
191 const TargetRegisterInfo *getRegInfo() const { return TRI; }
192
193 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
194 /// available in a physical register, return that PhysReg, otherwise
195 /// return 0.
196 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
197 std::map<int, unsigned>::const_iterator I =
198 SpillSlotsOrReMatsAvailable.find(Slot);
199 if (I != SpillSlotsOrReMatsAvailable.end()) {
200 return I->second >> 1; // Remove the CanClobber bit.
201 }
202 return 0;
203 }
204
205 /// addAvailable - Mark that the specified stack slot / remat is available
206 /// in the specified physreg. If CanClobber is true, the physreg can be
207 /// modified at any time without changing the semantics of the program.
208 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
209 // If this stack slot is thought to be available in some other physreg,
210 // remove its record.
211 ModifyStackSlotOrReMat(SlotOrReMat);
212
213 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
214 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
215 (unsigned)CanClobber;
216
217 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
David Greene0ee52182010-01-05 01:25:52 +0000218 DEBUG(dbgs() << "Remembering RM#"
Chris Lattner6456d382009-08-23 03:20:44 +0000219 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +0000220 else
David Greene0ee52182010-01-05 01:25:52 +0000221 DEBUG(dbgs() << "Remembering SS#" << SlotOrReMat);
222 DEBUG(dbgs() << " in physreg " << TRI->getName(Reg) << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000223 }
224
225 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
226 /// the value of the specified stackslot register if it desires. The
227 /// specified stack slot must be available in a physreg for this query to
228 /// make sense.
229 bool canClobberPhysRegForSS(int SlotOrReMat) const {
230 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
231 "Value not available!");
232 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
233 }
234
235 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
236 /// physical register where values for some stack slot(s) might be
237 /// available.
238 bool canClobberPhysReg(unsigned PhysReg) const {
239 std::multimap<unsigned, int>::const_iterator I =
240 PhysRegsAvailable.lower_bound(PhysReg);
241 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
242 int SlotOrReMat = I->second;
243 I++;
244 if (!canClobberPhysRegForSS(SlotOrReMat))
245 return false;
246 }
247 return true;
248 }
249
250 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
251 /// stackslot register. The register is still available but is no longer
252 /// allowed to be modifed.
253 void disallowClobberPhysReg(unsigned PhysReg);
254
255 /// ClobberPhysReg - This is called when the specified physreg changes
256 /// value. We use this to invalidate any info about stuff that lives in
257 /// it and any of its aliases.
258 void ClobberPhysReg(unsigned PhysReg);
259
260 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
261 /// slot changes. This removes information about which register the
262 /// previous value for this slot lives in (as the previous value is dead
263 /// now).
264 void ModifyStackSlotOrReMat(int SlotOrReMat);
265
266 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
267 /// into the specified MBB. Add available physical registers as potential
268 /// live-in's. If they are reused in the MBB, they will be added to the
269 /// live-in set to make register scavenger and post-allocation scheduler.
270 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
271 std::vector<MachineOperand*> &KillOps);
272};
273
Dan Gohman7db949d2009-08-07 01:32:21 +0000274}
275
Lang Hames87e3bca2009-05-06 02:36:21 +0000276// ************************************************************************ //
277
David Greene2d4e6d32009-07-28 16:49:24 +0000278// Given a location where a reload of a spilled register or a remat of
279// a constant is to be inserted, attempt to find a safe location to
280// insert the load at an earlier point in the basic-block, to hide
281// latency of the load and to avoid address-generation interlock
282// issues.
283static MachineBasicBlock::iterator
284ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
285 MachineBasicBlock::iterator const Begin,
286 unsigned PhysReg,
287 const TargetRegisterInfo *TRI,
288 bool DoReMat,
289 int SSorRMId,
290 const TargetInstrInfo *TII,
291 const MachineFunction &MF)
292{
293 if (!ScheduleSpills)
294 return InsertLoc;
295
296 // Spill backscheduling is of primary interest to addresses, so
297 // don't do anything if the register isn't in the register class
298 // used for pointers.
299
300 const TargetLowering *TL = MF.getTarget().getTargetLowering();
301
302 if (!TL->isTypeLegal(TL->getPointerTy()))
303 // Believe it or not, this is true on PIC16.
304 return InsertLoc;
305
306 const TargetRegisterClass *ptrRegClass =
307 TL->getRegClassFor(TL->getPointerTy());
308 if (!ptrRegClass->contains(PhysReg))
309 return InsertLoc;
310
311 // Scan upwards through the preceding instructions. If an instruction doesn't
312 // reference the stack slot or the register we're loading, we can
313 // backschedule the reload up past it.
314 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
315 while (NewInsertLoc != Begin) {
316 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
317 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
318 MachineOperand &Op = Prev->getOperand(i);
319 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
320 goto stop;
321 }
322 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
323 Prev->findRegisterDefOperand(PhysReg))
324 goto stop;
325 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
326 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
327 Prev->findRegisterDefOperand(*Alias))
328 goto stop;
329 NewInsertLoc = Prev;
330 }
331stop:;
332
333 // If we made it to the beginning of the block, turn around and move back
334 // down just past any existing reloads. They're likely to be reloads/remats
335 // for instructions earlier than what our current reload/remat is for, so
336 // they should be scheduled earlier.
337 if (NewInsertLoc == Begin) {
338 int FrameIdx;
339 while (InsertLoc != NewInsertLoc &&
340 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
341 TII->isTriviallyReMaterializable(NewInsertLoc)))
342 ++NewInsertLoc;
343 }
344
345 return NewInsertLoc;
346}
Dan Gohman7db949d2009-08-07 01:32:21 +0000347
348namespace {
349
Lang Hames87e3bca2009-05-06 02:36:21 +0000350// ReusedOp - For each reused operand, we keep track of a bit of information,
351// in case we need to rollback upon processing a new operand. See comments
352// below.
353struct ReusedOp {
354 // The MachineInstr operand that reused an available value.
355 unsigned Operand;
356
357 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
358 unsigned StackSlotOrReMat;
359
360 // PhysRegReused - The physical register the value was available in.
361 unsigned PhysRegReused;
362
363 // AssignedPhysReg - The physreg that was assigned for use by the reload.
364 unsigned AssignedPhysReg;
365
366 // VirtReg - The virtual register itself.
367 unsigned VirtReg;
368
369 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
370 unsigned vreg)
371 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
372 AssignedPhysReg(apr), VirtReg(vreg) {}
373};
374
375/// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
376/// is reused instead of reloaded.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000377class ReuseInfo {
Lang Hames87e3bca2009-05-06 02:36:21 +0000378 MachineInstr &MI;
379 std::vector<ReusedOp> Reuses;
380 BitVector PhysRegsClobbered;
381public:
382 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
383 PhysRegsClobbered.resize(tri->getNumRegs());
384 }
385
386 bool hasReuses() const {
387 return !Reuses.empty();
388 }
389
390 /// addReuse - If we choose to reuse a virtual register that is already
391 /// available instead of reloading it, remember that we did so.
392 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
393 unsigned PhysRegReused, unsigned AssignedPhysReg,
394 unsigned VirtReg) {
395 // If the reload is to the assigned register anyway, no undo will be
396 // required.
397 if (PhysRegReused == AssignedPhysReg) return;
398
399 // Otherwise, remember this.
400 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
401 AssignedPhysReg, VirtReg));
402 }
403
404 void markClobbered(unsigned PhysReg) {
405 PhysRegsClobbered.set(PhysReg);
406 }
407
408 bool isClobbered(unsigned PhysReg) const {
409 return PhysRegsClobbered.test(PhysReg);
410 }
411
412 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
413 /// is some other operand that is using the specified register, either pick
414 /// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000415 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
416 MachineFunction &MF, MachineInstr *MI,
Lang Hames87e3bca2009-05-06 02:36:21 +0000417 AvailableSpills &Spills,
418 std::vector<MachineInstr*> &MaybeDeadStores,
419 SmallSet<unsigned, 8> &Rejected,
420 BitVector &RegKills,
421 std::vector<MachineOperand*> &KillOps,
422 VirtRegMap &VRM);
423
424 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
425 /// 'Rejected' set to remember which registers have been considered and
426 /// rejected for the reload. This avoids infinite looping in case like
427 /// this:
428 /// t1 := op t2, t3
429 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
430 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
431 /// t1 <- desires r1
432 /// sees r1 is taken by t2, tries t2's reload register r0
433 /// sees r0 is taken by t3, tries t3's reload register r1
434 /// sees r1 is taken by t2, tries t2's reload register r0 ...
Evan Cheng5d885022009-07-21 09:15:00 +0000435 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
Lang Hames87e3bca2009-05-06 02:36:21 +0000436 AvailableSpills &Spills,
437 std::vector<MachineInstr*> &MaybeDeadStores,
438 BitVector &RegKills,
439 std::vector<MachineOperand*> &KillOps,
440 VirtRegMap &VRM) {
441 SmallSet<unsigned, 8> Rejected;
Evan Cheng5d885022009-07-21 09:15:00 +0000442 MachineFunction &MF = *MI->getParent()->getParent();
443 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
444 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
445 Rejected, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +0000446 }
447};
448
Dan Gohman7db949d2009-08-07 01:32:21 +0000449}
Lang Hames87e3bca2009-05-06 02:36:21 +0000450
451// ****************** //
452// Utility Functions //
453// ****************** //
454
Lang Hames87e3bca2009-05-06 02:36:21 +0000455/// findSinglePredSuccessor - Return via reference a vector of machine basic
456/// blocks each of which is a successor of the specified BB and has no other
457/// predecessor.
458static void findSinglePredSuccessor(MachineBasicBlock *MBB,
459 SmallVectorImpl<MachineBasicBlock *> &Succs) {
460 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
461 SE = MBB->succ_end(); SI != SE; ++SI) {
462 MachineBasicBlock *SuccMBB = *SI;
463 if (SuccMBB->pred_size() == 1)
464 Succs.push_back(SuccMBB);
465 }
466}
467
Evan Cheng427a6b62009-05-15 06:48:19 +0000468/// InvalidateKill - Invalidate register kill information for a specific
469/// register. This also unsets the kills marker on the last kill operand.
470static void InvalidateKill(unsigned Reg,
471 const TargetRegisterInfo* TRI,
472 BitVector &RegKills,
473 std::vector<MachineOperand*> &KillOps) {
474 if (RegKills[Reg]) {
475 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000476 // KillOps[Reg] might be a def of a super-register.
477 unsigned KReg = KillOps[Reg]->getReg();
478 KillOps[KReg] = NULL;
479 RegKills.reset(KReg);
480 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
Evan Cheng427a6b62009-05-15 06:48:19 +0000481 if (RegKills[*SR]) {
482 KillOps[*SR]->setIsKill(false);
483 KillOps[*SR] = NULL;
484 RegKills.reset(*SR);
485 }
486 }
487 }
488}
489
Lang Hames87e3bca2009-05-06 02:36:21 +0000490/// InvalidateKills - MI is going to be deleted. If any of its operands are
491/// marked kill, then invalidate the information.
Evan Cheng427a6b62009-05-15 06:48:19 +0000492static void InvalidateKills(MachineInstr &MI,
493 const TargetRegisterInfo* TRI,
494 BitVector &RegKills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000495 std::vector<MachineOperand*> &KillOps,
496 SmallVector<unsigned, 2> *KillRegs = NULL) {
497 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
498 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000499 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000500 continue;
501 unsigned Reg = MO.getReg();
502 if (TargetRegisterInfo::isVirtualRegister(Reg))
503 continue;
504 if (KillRegs)
505 KillRegs->push_back(Reg);
506 assert(Reg < KillOps.size());
507 if (KillOps[Reg] == &MO) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000508 KillOps[Reg] = NULL;
Evan Cheng427a6b62009-05-15 06:48:19 +0000509 RegKills.reset(Reg);
510 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
511 if (RegKills[*SR]) {
512 KillOps[*SR] = NULL;
513 RegKills.reset(*SR);
514 }
515 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000516 }
517 }
518}
519
520/// InvalidateRegDef - If the def operand of the specified def MI is now dead
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000521/// (since its spill instruction is removed), mark it isDead. Also checks if
Lang Hames87e3bca2009-05-06 02:36:21 +0000522/// the def MI has other definition operands that are not dead. Returns it by
523/// reference.
524static bool InvalidateRegDef(MachineBasicBlock::iterator I,
525 MachineInstr &NewDef, unsigned Reg,
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000526 bool &HasLiveDef,
527 const TargetRegisterInfo *TRI) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000528 // Due to remat, it's possible this reg isn't being reused. That is,
529 // the def of this reg (by prev MI) is now dead.
530 MachineInstr *DefMI = I;
531 MachineOperand *DefOp = NULL;
532 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
533 MachineOperand &MO = DefMI->getOperand(i);
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000534 if (!MO.isReg() || !MO.isDef() || !MO.isKill() || MO.isUndef())
Evan Cheng4784f1f2009-06-30 08:49:04 +0000535 continue;
536 if (MO.getReg() == Reg)
537 DefOp = &MO;
538 else if (!MO.isDead())
539 HasLiveDef = true;
Lang Hames87e3bca2009-05-06 02:36:21 +0000540 }
541 if (!DefOp)
542 return false;
543
544 bool FoundUse = false, Done = false;
545 MachineBasicBlock::iterator E = &NewDef;
546 ++I; ++E;
547 for (; !Done && I != E; ++I) {
548 MachineInstr *NMI = I;
549 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
550 MachineOperand &MO = NMI->getOperand(j);
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000551 if (!MO.isReg() || MO.getReg() == 0 ||
552 (MO.getReg() != Reg && !TRI->isSubRegister(Reg, MO.getReg())))
Lang Hames87e3bca2009-05-06 02:36:21 +0000553 continue;
554 if (MO.isUse())
555 FoundUse = true;
556 Done = true; // Stop after scanning all the operands of this MI.
557 }
558 }
559 if (!FoundUse) {
560 // Def is dead!
561 DefOp->setIsDead();
562 return true;
563 }
564 return false;
565}
566
567/// UpdateKills - Track and update kill info. If a MI reads a register that is
568/// marked kill, then it must be due to register reuse. Transfer the kill info
569/// over.
Evan Cheng427a6b62009-05-15 06:48:19 +0000570static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
571 BitVector &RegKills,
572 std::vector<MachineOperand*> &KillOps) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000573 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
574 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000575 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000576 continue;
577 unsigned Reg = MO.getReg();
578 if (Reg == 0)
579 continue;
580
581 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
582 // That can't be right. Register is killed but not re-defined and it's
583 // being reused. Let's fix that.
584 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000585 // KillOps[Reg] might be a def of a super-register.
586 unsigned KReg = KillOps[Reg]->getReg();
587 KillOps[KReg] = NULL;
588 RegKills.reset(KReg);
589
590 // Must be a def of a super-register. Its other sub-regsters are no
591 // longer killed as well.
592 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
593 KillOps[*SR] = NULL;
594 RegKills.reset(*SR);
595 }
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000596 } else {
597 // Check for subreg kills as well.
598 // d4 =
599 // store d4, fi#0
600 // ...
601 // = s8<kill>
602 // ...
603 // = d4 <avoiding reload>
604 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
605 unsigned SReg = *SR;
606 if (RegKills[SReg] && KillOps[SReg]->getParent() != &MI) {
607 KillOps[SReg]->setIsKill(false);
608 unsigned KReg = KillOps[SReg]->getReg();
609 KillOps[KReg] = NULL;
610 RegKills.reset(KReg);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000611
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000612 for (const unsigned *SSR = TRI->getSubRegisters(KReg); *SSR; ++SSR) {
613 KillOps[*SSR] = NULL;
614 RegKills.reset(*SSR);
615 }
616 }
617 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000618 }
Evan Cheng8fdd84c2009-11-14 02:09:09 +0000619
Lang Hames87e3bca2009-05-06 02:36:21 +0000620 if (MO.isKill()) {
621 RegKills.set(Reg);
622 KillOps[Reg] = &MO;
Evan Cheng427a6b62009-05-15 06:48:19 +0000623 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
624 RegKills.set(*SR);
625 KillOps[*SR] = &MO;
626 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000627 }
628 }
629
630 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
631 const MachineOperand &MO = MI.getOperand(i);
Evan Chengd57cdd52009-11-14 02:55:43 +0000632 if (!MO.isReg() || !MO.getReg() || !MO.isDef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000633 continue;
634 unsigned Reg = MO.getReg();
635 RegKills.reset(Reg);
636 KillOps[Reg] = NULL;
637 // It also defines (or partially define) aliases.
Evan Cheng427a6b62009-05-15 06:48:19 +0000638 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
639 RegKills.reset(*SR);
640 KillOps[*SR] = NULL;
Lang Hames87e3bca2009-05-06 02:36:21 +0000641 }
Evan Cheng1f6a3c82009-11-13 23:16:41 +0000642 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
643 RegKills.reset(*SR);
644 KillOps[*SR] = NULL;
645 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000646 }
647}
648
649/// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
650///
651static void ReMaterialize(MachineBasicBlock &MBB,
652 MachineBasicBlock::iterator &MII,
653 unsigned DestReg, unsigned Reg,
654 const TargetInstrInfo *TII,
655 const TargetRegisterInfo *TRI,
656 VirtRegMap &VRM) {
Evan Cheng5f159922009-07-16 20:15:00 +0000657 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
Daniel Dunbar24cd3c42009-07-16 22:08:25 +0000658#ifndef NDEBUG
Evan Cheng5f159922009-07-16 20:15:00 +0000659 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
Evan Chengc1b46f92009-07-17 00:32:06 +0000660 assert(TID.getNumDefs() == 1 &&
Evan Cheng5f159922009-07-16 20:15:00 +0000661 "Don't know how to remat instructions that define > 1 values!");
662#endif
663 TII->reMaterialize(MBB, MII, DestReg,
Evan Chengd57cdd52009-11-14 02:55:43 +0000664 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI, TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +0000665 MachineInstr *NewMI = prior(MII);
666 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
667 MachineOperand &MO = NewMI->getOperand(i);
668 if (!MO.isReg() || MO.getReg() == 0)
669 continue;
670 unsigned VirtReg = MO.getReg();
671 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
672 continue;
673 assert(MO.isUse());
Lang Hames87e3bca2009-05-06 02:36:21 +0000674 unsigned Phys = VRM.getPhys(VirtReg);
Evan Cheng427c3ba2009-10-25 07:51:47 +0000675 assert(Phys && "Virtual register is not assigned a register?");
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +0000676 substitutePhysReg(MO, Phys, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +0000677 }
678 ++NumReMats;
679}
680
681/// findSuperReg - Find the SubReg's super-register of given register class
682/// where its SubIdx sub-register is SubReg.
683static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
684 unsigned SubIdx, const TargetRegisterInfo *TRI) {
685 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
686 I != E; ++I) {
687 unsigned Reg = *I;
688 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
689 return Reg;
690 }
691 return 0;
692}
693
694// ******************************** //
695// Available Spills Implementation //
696// ******************************** //
697
698/// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
699/// stackslot register. The register is still available but is no longer
700/// allowed to be modifed.
701void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
702 std::multimap<unsigned, int>::iterator I =
703 PhysRegsAvailable.lower_bound(PhysReg);
704 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
705 int SlotOrReMat = I->second;
706 I++;
707 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
708 "Bidirectional map mismatch!");
709 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
David Greene0ee52182010-01-05 01:25:52 +0000710 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
Chris Lattner6456d382009-08-23 03:20:44 +0000711 << " copied, it is available for use but can no longer be modified\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000712 }
713}
714
715/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
716/// stackslot register and its aliases. The register and its aliases may
717/// still available but is no longer allowed to be modifed.
718void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
719 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
720 disallowClobberPhysRegOnly(*AS);
721 disallowClobberPhysRegOnly(PhysReg);
722}
723
724/// ClobberPhysRegOnly - This is called when the specified physreg changes
725/// value. We use this to invalidate any info about stuff we thing lives in it.
726void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
727 std::multimap<unsigned, int>::iterator I =
728 PhysRegsAvailable.lower_bound(PhysReg);
729 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
730 int SlotOrReMat = I->second;
731 PhysRegsAvailable.erase(I++);
732 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
733 "Bidirectional map mismatch!");
734 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
David Greene0ee52182010-01-05 01:25:52 +0000735 DEBUG(dbgs() << "PhysReg " << TRI->getName(PhysReg)
Chris Lattner6456d382009-08-23 03:20:44 +0000736 << " clobbered, invalidating ");
Lang Hames87e3bca2009-05-06 02:36:21 +0000737 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
David Greene0ee52182010-01-05 01:25:52 +0000738 DEBUG(dbgs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000739 else
David Greene0ee52182010-01-05 01:25:52 +0000740 DEBUG(dbgs() << "SS#" << SlotOrReMat << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000741 }
742}
743
744/// ClobberPhysReg - This is called when the specified physreg changes
745/// value. We use this to invalidate any info about stuff we thing lives in
746/// it and any of its aliases.
747void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
748 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
749 ClobberPhysRegOnly(*AS);
750 ClobberPhysRegOnly(PhysReg);
751}
752
753/// AddAvailableRegsToLiveIn - Availability information is being kept coming
754/// into the specified MBB. Add available physical registers as potential
755/// live-in's. If they are reused in the MBB, they will be added to the
756/// live-in set to make register scavenger and post-allocation scheduler.
757void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
758 BitVector &RegKills,
759 std::vector<MachineOperand*> &KillOps) {
760 std::set<unsigned> NotAvailable;
761 for (std::multimap<unsigned, int>::iterator
762 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
763 I != E; ++I) {
764 unsigned Reg = I->first;
765 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
766 // FIXME: A temporary workaround. We can't reuse available value if it's
767 // not safe to move the def of the virtual register's class. e.g.
768 // X86::RFP* register classes. Do not add it as a live-in.
769 if (!TII->isSafeToMoveRegClassDefs(RC))
770 // This is no longer available.
771 NotAvailable.insert(Reg);
772 else {
773 MBB.addLiveIn(Reg);
Evan Cheng427a6b62009-05-15 06:48:19 +0000774 InvalidateKill(Reg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +0000775 }
776
777 // Skip over the same register.
Chris Lattner7896c9f2009-12-03 00:50:42 +0000778 std::multimap<unsigned, int>::iterator NI = llvm::next(I);
Lang Hames87e3bca2009-05-06 02:36:21 +0000779 while (NI != E && NI->first == Reg) {
780 ++I;
781 ++NI;
782 }
783 }
784
785 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
786 E = NotAvailable.end(); I != E; ++I) {
787 ClobberPhysReg(*I);
788 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
789 *SubRegs; ++SubRegs)
790 ClobberPhysReg(*SubRegs);
791 }
792}
793
794/// ModifyStackSlotOrReMat - This method is called when the value in a stack
795/// slot changes. This removes information about which register the previous
796/// value for this slot lives in (as the previous value is dead now).
797void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
798 std::map<int, unsigned>::iterator It =
799 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
800 if (It == SpillSlotsOrReMatsAvailable.end()) return;
801 unsigned Reg = It->second >> 1;
802 SpillSlotsOrReMatsAvailable.erase(It);
803
804 // This register may hold the value of multiple stack slots, only remove this
805 // stack slot from the set of values the register contains.
806 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
807 for (; ; ++I) {
808 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
809 "Map inverse broken!");
810 if (I->second == SlotOrReMat) break;
811 }
812 PhysRegsAvailable.erase(I);
813}
814
815// ************************** //
816// Reuse Info Implementation //
817// ************************** //
818
819/// GetRegForReload - We are about to emit a reload into PhysReg. If there
820/// is some other operand that is using the specified register, either pick
821/// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000822unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
823 unsigned PhysReg,
824 MachineFunction &MF,
825 MachineInstr *MI, AvailableSpills &Spills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000826 std::vector<MachineInstr*> &MaybeDeadStores,
827 SmallSet<unsigned, 8> &Rejected,
828 BitVector &RegKills,
829 std::vector<MachineOperand*> &KillOps,
830 VirtRegMap &VRM) {
Evan Cheng5d885022009-07-21 09:15:00 +0000831 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
832 const TargetRegisterInfo *TRI = Spills.getRegInfo();
Lang Hames87e3bca2009-05-06 02:36:21 +0000833
834 if (Reuses.empty()) return PhysReg; // This is most often empty.
835
836 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
837 ReusedOp &Op = Reuses[ro];
838 // If we find some other reuse that was supposed to use this register
839 // exactly for its reload, we can change this reload to use ITS reload
840 // register. That is, unless its reload register has already been
841 // considered and subsequently rejected because it has also been reused
842 // by another operand.
843 if (Op.PhysRegReused == PhysReg &&
Evan Cheng5d885022009-07-21 09:15:00 +0000844 Rejected.count(Op.AssignedPhysReg) == 0 &&
845 RC->contains(Op.AssignedPhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000846 // Yup, use the reload register that we didn't use before.
847 unsigned NewReg = Op.AssignedPhysReg;
848 Rejected.insert(PhysReg);
Evan Cheng5d885022009-07-21 09:15:00 +0000849 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
Lang Hames87e3bca2009-05-06 02:36:21 +0000850 RegKills, KillOps, VRM);
851 } else {
852 // Otherwise, we might also have a problem if a previously reused
Evan Cheng5d885022009-07-21 09:15:00 +0000853 // value aliases the new register. If so, codegen the previous reload
Lang Hames87e3bca2009-05-06 02:36:21 +0000854 // and use this one.
855 unsigned PRRU = Op.PhysRegReused;
Lang Hames3f2f3f52009-09-03 02:52:02 +0000856 if (TRI->regsOverlap(PRRU, PhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000857 // Okay, we found out that an alias of a reused register
858 // was used. This isn't good because it means we have
859 // to undo a previous reuse.
860 MachineBasicBlock *MBB = MI->getParent();
861 const TargetRegisterClass *AliasRC =
862 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
863
864 // Copy Op out of the vector and remove it, we're going to insert an
865 // explicit load for it.
866 ReusedOp NewOp = Op;
867 Reuses.erase(Reuses.begin()+ro);
868
Jakob Stoklund Olesen46ff9692009-08-23 13:01:45 +0000869 // MI may be using only a sub-register of PhysRegUsed.
870 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
871 unsigned SubIdx = 0;
872 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
873 "A reuse cannot be a virtual register");
874 if (PRRU != RealPhysRegUsed) {
875 // What was the sub-register index?
Evan Chengfae3e922009-11-14 03:42:17 +0000876 SubIdx = TRI->getSubRegIndex(PRRU, RealPhysRegUsed);
877 assert(SubIdx &&
Jakob Stoklund Olesen46ff9692009-08-23 13:01:45 +0000878 "Operand physreg is not a sub-register of PhysRegUsed");
879 }
880
Lang Hames87e3bca2009-05-06 02:36:21 +0000881 // Ok, we're going to try to reload the assigned physreg into the
882 // slot that we were supposed to in the first place. However, that
883 // register could hold a reuse. Check to see if it conflicts or
884 // would prefer us to use a different register.
Evan Cheng5d885022009-07-21 09:15:00 +0000885 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
886 MF, MI, Spills, MaybeDeadStores,
887 Rejected, RegKills, KillOps, VRM);
David Greene2d4e6d32009-07-28 16:49:24 +0000888
889 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
890 int SSorRMId = DoReMat
891 ? VRM.getReMatId(NewOp.VirtReg) : NewOp.StackSlotOrReMat;
892
893 // Back-schedule reloads and remats.
894 MachineBasicBlock::iterator InsertLoc =
895 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
896 DoReMat, SSorRMId, TII, MF);
897
898 if (DoReMat) {
899 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
900 TRI, VRM);
901 } else {
902 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
Lang Hames87e3bca2009-05-06 02:36:21 +0000903 NewOp.StackSlotOrReMat, AliasRC);
David Greene2d4e6d32009-07-28 16:49:24 +0000904 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +0000905 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
906 // Any stores to this stack slot are not dead anymore.
907 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
908 ++NumLoads;
909 }
910 Spills.ClobberPhysReg(NewPhysReg);
911 Spills.ClobberPhysReg(NewOp.PhysRegReused);
912
Evan Cheng427c3ba2009-10-25 07:51:47 +0000913 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
Lang Hames87e3bca2009-05-06 02:36:21 +0000914 MI->getOperand(NewOp.Operand).setReg(RReg);
915 MI->getOperand(NewOp.Operand).setSubReg(0);
916
917 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
David Greene2d4e6d32009-07-28 16:49:24 +0000918 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
David Greene0ee52182010-01-05 01:25:52 +0000919 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
Lang Hames87e3bca2009-05-06 02:36:21 +0000920
David Greene0ee52182010-01-05 01:25:52 +0000921 DEBUG(dbgs() << "Reuse undone!\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000922 --NumReused;
923
924 // Finally, PhysReg is now available, go ahead and use it.
925 return PhysReg;
926 }
927 }
928 }
929 return PhysReg;
930}
931
932// ************************************************************************ //
933
934/// FoldsStackSlotModRef - Return true if the specified MI folds the specified
935/// stack slot mod/ref. It also checks if it's possible to unfold the
936/// instruction by having it define a specified physical register instead.
937static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
938 const TargetInstrInfo *TII,
939 const TargetRegisterInfo *TRI,
940 VirtRegMap &VRM) {
941 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
942 return false;
943
944 bool Found = false;
945 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
946 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
947 unsigned VirtReg = I->second.first;
948 VirtRegMap::ModRef MR = I->second.second;
949 if (MR & VirtRegMap::isModRef)
950 if (VRM.getStackSlot(VirtReg) == SS) {
951 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
952 break;
953 }
954 }
955 if (!Found)
956 return false;
957
958 // Does the instruction uses a register that overlaps the scratch register?
959 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
960 MachineOperand &MO = MI.getOperand(i);
961 if (!MO.isReg() || MO.getReg() == 0)
962 continue;
963 unsigned Reg = MO.getReg();
964 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
965 if (!VRM.hasPhys(Reg))
966 continue;
967 Reg = VRM.getPhys(Reg);
968 }
969 if (TRI->regsOverlap(PhysReg, Reg))
970 return false;
971 }
972 return true;
973}
974
975/// FindFreeRegister - Find a free register of a given register class by looking
976/// at (at most) the last two machine instructions.
977static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
978 MachineBasicBlock &MBB,
979 const TargetRegisterClass *RC,
980 const TargetRegisterInfo *TRI,
981 BitVector &AllocatableRegs) {
982 BitVector Defs(TRI->getNumRegs());
983 BitVector Uses(TRI->getNumRegs());
984 SmallVector<unsigned, 4> LocalUses;
985 SmallVector<unsigned, 4> Kills;
986
987 // Take a look at 2 instructions at most.
988 for (unsigned Count = 0; Count < 2; ++Count) {
989 if (MII == MBB.begin())
990 break;
991 MachineInstr *PrevMI = prior(MII);
992 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
993 MachineOperand &MO = PrevMI->getOperand(i);
994 if (!MO.isReg() || MO.getReg() == 0)
995 continue;
996 unsigned Reg = MO.getReg();
997 if (MO.isDef()) {
998 Defs.set(Reg);
999 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1000 Defs.set(*AS);
1001 } else {
1002 LocalUses.push_back(Reg);
1003 if (MO.isKill() && AllocatableRegs[Reg])
1004 Kills.push_back(Reg);
1005 }
1006 }
1007
1008 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
1009 unsigned Kill = Kills[i];
1010 if (!Defs[Kill] && !Uses[Kill] &&
1011 TRI->getPhysicalRegisterRegClass(Kill) == RC)
1012 return Kill;
1013 }
1014 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
1015 unsigned Reg = LocalUses[i];
1016 Uses.set(Reg);
1017 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
1018 Uses.set(*AS);
1019 }
1020
1021 MII = PrevMI;
1022 }
1023
1024 return 0;
1025}
1026
1027static
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001028void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg,
1029 const TargetRegisterInfo &TRI) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001030 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1031 MachineOperand &MO = MI->getOperand(i);
1032 if (MO.isReg() && MO.getReg() == VirtReg)
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001033 substitutePhysReg(MO, PhysReg, TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001034 }
1035}
1036
Evan Chengeca24fb2009-05-12 23:07:00 +00001037namespace {
1038 struct RefSorter {
1039 bool operator()(const std::pair<MachineInstr*, int> &A,
1040 const std::pair<MachineInstr*, int> &B) {
1041 return A.second < B.second;
1042 }
1043 };
1044}
Lang Hames87e3bca2009-05-06 02:36:21 +00001045
1046// ***************************** //
1047// Local Spiller Implementation //
1048// ***************************** //
1049
Dan Gohman7db949d2009-08-07 01:32:21 +00001050namespace {
1051
Nick Lewycky6726b6d2009-10-25 06:33:48 +00001052class LocalRewriter : public VirtRegRewriter {
Lang Hames87e3bca2009-05-06 02:36:21 +00001053 MachineRegisterInfo *RegInfo;
1054 const TargetRegisterInfo *TRI;
1055 const TargetInstrInfo *TII;
1056 BitVector AllocatableRegs;
1057 DenseMap<MachineInstr*, unsigned> DistanceMap;
1058public:
1059
1060 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1061 LiveIntervals* LIs) {
1062 RegInfo = &MF.getRegInfo();
1063 TRI = MF.getTarget().getRegisterInfo();
1064 TII = MF.getTarget().getInstrInfo();
1065 AllocatableRegs = TRI->getAllocatableSet(MF);
David Greene0ee52182010-01-05 01:25:52 +00001066 DEBUG(dbgs() << "\n**** Local spiller rewriting function '"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001067 << MF.getFunction()->getName() << "':\n");
David Greene0ee52182010-01-05 01:25:52 +00001068 DEBUG(dbgs() << "**** Machine Instrs (NOTE! Does not include spills and"
Chris Lattner6456d382009-08-23 03:20:44 +00001069 " reloads!) ****\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001070 DEBUG(MF.dump());
1071
1072 // Spills - Keep track of which spilled values are available in physregs
1073 // so that we can choose to reuse the physregs instead of emitting
1074 // reloads. This is usually refreshed per basic block.
1075 AvailableSpills Spills(TRI, TII);
1076
1077 // Keep track of kill information.
1078 BitVector RegKills(TRI->getNumRegs());
1079 std::vector<MachineOperand*> KillOps;
1080 KillOps.resize(TRI->getNumRegs(), NULL);
1081
1082 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1083 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1084 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1085
1086 // Traverse the basic blocks depth first.
1087 MachineBasicBlock *Entry = MF.begin();
1088 SmallPtrSet<MachineBasicBlock*,16> Visited;
1089 for (df_ext_iterator<MachineBasicBlock*,
1090 SmallPtrSet<MachineBasicBlock*,16> >
1091 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1092 DFI != E; ++DFI) {
1093 MachineBasicBlock *MBB = *DFI;
1094 if (!EarlyVisited.count(MBB))
1095 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1096
1097 // If this MBB is the only predecessor of a successor. Keep the
1098 // availability information and visit it next.
1099 do {
1100 // Keep visiting single predecessor successor as long as possible.
1101 SinglePredSuccs.clear();
1102 findSinglePredSuccessor(MBB, SinglePredSuccs);
1103 if (SinglePredSuccs.empty())
1104 MBB = 0;
1105 else {
1106 // FIXME: More than one successors, each of which has MBB has
1107 // the only predecessor.
1108 MBB = SinglePredSuccs[0];
1109 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1110 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1111 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1112 }
1113 }
1114 } while (MBB);
1115
1116 // Clear the availability info.
1117 Spills.clear();
1118 }
1119
David Greene0ee52182010-01-05 01:25:52 +00001120 DEBUG(dbgs() << "**** Post Machine Instrs ****\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001121 DEBUG(MF.dump());
1122
1123 // Mark unused spill slots.
1124 MachineFrameInfo *MFI = MF.getFrameInfo();
1125 int SS = VRM.getLowSpillSlot();
1126 if (SS != VirtRegMap::NO_STACK_SLOT)
1127 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
1128 if (!VRM.isSpillSlotUsed(SS)) {
1129 MFI->RemoveStackObject(SS);
1130 ++NumDSS;
1131 }
1132
1133 return true;
1134 }
1135
1136private:
1137
1138 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1139 /// a scratch register is available.
1140 /// xorq %r12<kill>, %r13
1141 /// addq %rax, -184(%rbp)
1142 /// addq %r13, -184(%rbp)
1143 /// ==>
1144 /// xorq %r12<kill>, %r13
1145 /// movq -184(%rbp), %r12
1146 /// addq %rax, %r12
1147 /// addq %r13, %r12
1148 /// movq %r12, -184(%rbp)
1149 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1150 MachineBasicBlock &MBB,
1151 MachineBasicBlock::iterator &MII,
1152 std::vector<MachineInstr*> &MaybeDeadStores,
1153 AvailableSpills &Spills,
1154 BitVector &RegKills,
1155 std::vector<MachineOperand*> &KillOps,
1156 VirtRegMap &VRM) {
1157
Chris Lattner7896c9f2009-12-03 00:50:42 +00001158 MachineBasicBlock::iterator NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001159 if (NextMII == MBB.end())
1160 return false;
1161
1162 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1163 return false;
1164
1165 // Now let's see if the last couple of instructions happens to have freed up
1166 // a register.
1167 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1168 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
1169 if (!PhysReg)
1170 return false;
1171
1172 MachineFunction &MF = *MBB.getParent();
1173 TRI = MF.getTarget().getRegisterInfo();
1174 MachineInstr &MI = *MII;
1175 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
1176 return false;
1177
1178 // If the next instruction also folds the same SS modref and can be unfoled,
1179 // then it's worthwhile to issue a load from SS into the free register and
1180 // then unfold these instructions.
1181 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
1182 return false;
1183
David Greene2d4e6d32009-07-28 16:49:24 +00001184 // Back-schedule reloads and remats.
Duncan Sandsb7c5bdf2009-09-06 08:33:48 +00001185 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, false, SS, TII, MF);
David Greene2d4e6d32009-07-28 16:49:24 +00001186
Lang Hames87e3bca2009-05-06 02:36:21 +00001187 // Load from SS to the spare physical register.
1188 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
1189 // This invalidates Phys.
1190 Spills.ClobberPhysReg(PhysReg);
1191 // Remember it's available.
1192 Spills.addAvailable(SS, PhysReg);
1193 MaybeDeadStores[SS] = NULL;
1194
1195 // Unfold current MI.
1196 SmallVector<MachineInstr*, 4> NewMIs;
1197 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
Torok Edwinc23197a2009-07-14 16:55:14 +00001198 llvm_unreachable("Unable unfold the load / store folding instruction!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001199 assert(NewMIs.size() == 1);
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001200 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001201 VRM.transferRestorePts(&MI, NewMIs[0]);
1202 MII = MBB.insert(MII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00001203 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001204 VRM.RemoveMachineInstrFromMaps(&MI);
1205 MBB.erase(&MI);
1206 ++NumModRefUnfold;
1207
1208 // Unfold next instructions that fold the same SS.
1209 do {
1210 MachineInstr &NextMI = *NextMII;
Chris Lattner7896c9f2009-12-03 00:50:42 +00001211 NextMII = llvm::next(NextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001212 NewMIs.clear();
1213 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
Torok Edwinc23197a2009-07-14 16:55:14 +00001214 llvm_unreachable("Unable unfold the load / store folding instruction!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001215 assert(NewMIs.size() == 1);
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001216 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001217 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1218 MBB.insert(NextMII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00001219 InvalidateKills(NextMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001220 VRM.RemoveMachineInstrFromMaps(&NextMI);
1221 MBB.erase(&NextMI);
1222 ++NumModRefUnfold;
Evan Cheng2c48fe62009-06-03 09:00:27 +00001223 if (NextMII == MBB.end())
1224 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001225 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1226
1227 // Store the value back into SS.
1228 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1229 MachineInstr *StoreMI = prior(NextMII);
1230 VRM.addSpillSlotUse(SS, StoreMI);
1231 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1232
1233 return true;
1234 }
1235
1236 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1237 /// instruction. e.g.
1238 /// xorl %edi, %eax
1239 /// movl %eax, -32(%ebp)
1240 /// movl -36(%ebp), %eax
1241 /// orl %eax, -32(%ebp)
1242 /// ==>
1243 /// xorl %edi, %eax
1244 /// orl -36(%ebp), %eax
1245 /// mov %eax, -32(%ebp)
1246 /// This enables unfolding optimization for a subsequent instruction which will
1247 /// also eliminate the newly introduced store instruction.
1248 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1249 MachineBasicBlock::iterator &MII,
1250 std::vector<MachineInstr*> &MaybeDeadStores,
1251 AvailableSpills &Spills,
1252 BitVector &RegKills,
1253 std::vector<MachineOperand*> &KillOps,
1254 VirtRegMap &VRM) {
1255 MachineFunction &MF = *MBB.getParent();
1256 MachineInstr &MI = *MII;
1257 unsigned UnfoldedOpc = 0;
1258 unsigned UnfoldPR = 0;
1259 unsigned UnfoldVR = 0;
1260 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1261 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1262 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1263 // Only transform a MI that folds a single register.
1264 if (UnfoldedOpc)
1265 return false;
1266 UnfoldVR = I->second.first;
1267 VirtRegMap::ModRef MR = I->second.second;
1268 // MI2VirtMap be can updated which invalidate the iterator.
1269 // Increment the iterator first.
1270 ++I;
1271 if (VRM.isAssignedReg(UnfoldVR))
1272 continue;
1273 // If this reference is not a use, any previous store is now dead.
1274 // Otherwise, the store to this stack slot is not dead anymore.
1275 FoldedSS = VRM.getStackSlot(UnfoldVR);
1276 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1277 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1278 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1279 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1280 continue;
1281 UnfoldPR = PhysReg;
1282 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1283 false, true);
1284 }
1285 }
1286
1287 if (!UnfoldedOpc) {
1288 if (!UnfoldVR)
1289 return false;
1290
1291 // Look for other unfolding opportunities.
1292 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1293 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1294 }
1295
1296 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1297 MachineOperand &MO = MI.getOperand(i);
1298 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1299 continue;
1300 unsigned VirtReg = MO.getReg();
1301 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1302 continue;
1303 if (VRM.isAssignedReg(VirtReg)) {
1304 unsigned PhysReg = VRM.getPhys(VirtReg);
1305 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1306 return false;
1307 } else if (VRM.isReMaterialized(VirtReg))
1308 continue;
1309 int SS = VRM.getStackSlot(VirtReg);
1310 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1311 if (PhysReg) {
1312 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1313 return false;
1314 continue;
1315 }
1316 if (VRM.hasPhys(VirtReg)) {
1317 PhysReg = VRM.getPhys(VirtReg);
1318 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1319 continue;
1320 }
1321
1322 // Ok, we'll need to reload the value into a register which makes
1323 // it impossible to perform the store unfolding optimization later.
1324 // Let's see if it is possible to fold the load if the store is
1325 // unfolded. This allows us to perform the store unfolding
1326 // optimization.
1327 SmallVector<MachineInstr*, 4> NewMIs;
1328 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1329 assert(NewMIs.size() == 1);
1330 MachineInstr *NewMI = NewMIs.back();
1331 NewMIs.clear();
1332 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1333 assert(Idx != -1);
1334 SmallVector<unsigned, 1> Ops;
1335 Ops.push_back(Idx);
1336 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1337 if (FoldedMI) {
1338 VRM.addSpillSlotUse(SS, FoldedMI);
1339 if (!VRM.hasPhys(UnfoldVR))
1340 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1341 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1342 MII = MBB.insert(MII, FoldedMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001343 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001344 VRM.RemoveMachineInstrFromMaps(&MI);
1345 MBB.erase(&MI);
1346 MF.DeleteMachineInstr(NewMI);
1347 return true;
1348 }
1349 MF.DeleteMachineInstr(NewMI);
1350 }
1351 }
1352
1353 return false;
1354 }
1355
Evan Cheng261ce1d2009-07-10 19:15:51 +00001356 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1357 /// where SrcReg is r1 and it is tied to r0. Return true if after
1358 /// commuting this instruction it will be r0 = op r2, r1.
1359 static bool CommuteChangesDestination(MachineInstr *DefMI,
1360 const TargetInstrDesc &TID,
1361 unsigned SrcReg,
1362 const TargetInstrInfo *TII,
1363 unsigned &DstIdx) {
1364 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1365 return false;
1366 if (!DefMI->getOperand(1).isReg() ||
1367 DefMI->getOperand(1).getReg() != SrcReg)
1368 return false;
1369 unsigned DefIdx;
1370 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1371 return false;
1372 unsigned SrcIdx1, SrcIdx2;
1373 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1374 return false;
1375 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1376 DstIdx = 2;
1377 return true;
1378 }
1379 return false;
1380 }
1381
Lang Hames87e3bca2009-05-06 02:36:21 +00001382 /// CommuteToFoldReload -
1383 /// Look for
1384 /// r1 = load fi#1
1385 /// r1 = op r1, r2<kill>
1386 /// store r1, fi#1
1387 ///
1388 /// If op is commutable and r2 is killed, then we can xform these to
1389 /// r2 = op r2, fi#1
1390 /// store r2, fi#1
1391 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1392 MachineBasicBlock::iterator &MII,
1393 unsigned VirtReg, unsigned SrcReg, int SS,
1394 AvailableSpills &Spills,
1395 BitVector &RegKills,
1396 std::vector<MachineOperand*> &KillOps,
1397 const TargetRegisterInfo *TRI,
1398 VirtRegMap &VRM) {
1399 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1400 return false;
1401
1402 MachineFunction &MF = *MBB.getParent();
1403 MachineInstr &MI = *MII;
1404 MachineBasicBlock::iterator DefMII = prior(MII);
1405 MachineInstr *DefMI = DefMII;
1406 const TargetInstrDesc &TID = DefMI->getDesc();
1407 unsigned NewDstIdx;
1408 if (DefMII != MBB.begin() &&
1409 TID.isCommutable() &&
Evan Cheng261ce1d2009-07-10 19:15:51 +00001410 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001411 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1412 unsigned NewReg = NewDstMO.getReg();
1413 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1414 return false;
1415 MachineInstr *ReloadMI = prior(DefMII);
1416 int FrameIdx;
1417 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1418 if (DestReg != SrcReg || FrameIdx != SS)
1419 return false;
1420 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1421 if (UseIdx == -1)
1422 return false;
1423 unsigned DefIdx;
1424 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1425 return false;
1426 assert(DefMI->getOperand(DefIdx).isReg() &&
1427 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1428
1429 // Now commute def instruction.
1430 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1431 if (!CommutedMI)
1432 return false;
1433 SmallVector<unsigned, 1> Ops;
1434 Ops.push_back(NewDstIdx);
1435 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1436 // Not needed since foldMemoryOperand returns new MI.
1437 MF.DeleteMachineInstr(CommutedMI);
1438 if (!FoldedMI)
1439 return false;
1440
1441 VRM.addSpillSlotUse(SS, FoldedMI);
1442 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1443 // Insert new def MI and spill MI.
1444 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1445 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1446 MII = prior(MII);
1447 MachineInstr *StoreMI = MII;
1448 VRM.addSpillSlotUse(SS, StoreMI);
1449 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1450 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1451
1452 // Delete all 3 old instructions.
Evan Cheng427a6b62009-05-15 06:48:19 +00001453 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001454 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1455 MBB.erase(ReloadMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001456 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001457 VRM.RemoveMachineInstrFromMaps(DefMI);
1458 MBB.erase(DefMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001459 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001460 VRM.RemoveMachineInstrFromMaps(&MI);
1461 MBB.erase(&MI);
1462
1463 // If NewReg was previously holding value of some SS, it's now clobbered.
1464 // This has to be done now because it's a physical register. When this
1465 // instruction is re-visited, it's ignored.
1466 Spills.ClobberPhysReg(NewReg);
1467
1468 ++NumCommutes;
1469 return true;
1470 }
1471
1472 return false;
1473 }
1474
1475 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1476 /// the last store to the same slot is now dead. If so, remove the last store.
1477 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1478 MachineBasicBlock::iterator &MII,
1479 int Idx, unsigned PhysReg, int StackSlot,
1480 const TargetRegisterClass *RC,
1481 bool isAvailable, MachineInstr *&LastStore,
1482 AvailableSpills &Spills,
1483 SmallSet<MachineInstr*, 4> &ReMatDefs,
1484 BitVector &RegKills,
1485 std::vector<MachineOperand*> &KillOps,
1486 VirtRegMap &VRM) {
1487
Chris Lattner7896c9f2009-12-03 00:50:42 +00001488 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1489 TII->storeRegToStackSlot(MBB, llvm::next(MII), PhysReg, true, StackSlot, RC);
Dale Johannesen78c5cda2009-10-29 01:15:40 +00001490 MachineInstr *StoreMI = prior(oldNextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001491 VRM.addSpillSlotUse(StackSlot, StoreMI);
David Greene0ee52182010-01-05 01:25:52 +00001492 DEBUG(dbgs() << "Store:\t" << *StoreMI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001493
1494 // If there is a dead store to this stack slot, nuke it now.
1495 if (LastStore) {
David Greene0ee52182010-01-05 01:25:52 +00001496 DEBUG(dbgs() << "Removed dead store:\t" << *LastStore);
Lang Hames87e3bca2009-05-06 02:36:21 +00001497 ++NumDSE;
1498 SmallVector<unsigned, 2> KillRegs;
Evan Cheng427a6b62009-05-15 06:48:19 +00001499 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
Lang Hames87e3bca2009-05-06 02:36:21 +00001500 MachineBasicBlock::iterator PrevMII = LastStore;
1501 bool CheckDef = PrevMII != MBB.begin();
1502 if (CheckDef)
1503 --PrevMII;
1504 VRM.RemoveMachineInstrFromMaps(LastStore);
1505 MBB.erase(LastStore);
1506 if (CheckDef) {
1507 // Look at defs of killed registers on the store. Mark the defs
1508 // as dead since the store has been deleted and they aren't
1509 // being reused.
1510 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1511 bool HasOtherDef = false;
Evan Cheng8fdd84c2009-11-14 02:09:09 +00001512 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef, TRI)) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001513 MachineInstr *DeadDef = PrevMII;
1514 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
Evan Cheng4784f1f2009-06-30 08:49:04 +00001515 // FIXME: This assumes a remat def does not have side effects.
Lang Hames87e3bca2009-05-06 02:36:21 +00001516 VRM.RemoveMachineInstrFromMaps(DeadDef);
1517 MBB.erase(DeadDef);
1518 ++NumDRM;
1519 }
1520 }
1521 }
1522 }
1523 }
1524
Dale Johannesene841d2f2009-10-28 21:56:18 +00001525 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1526 // the last of multiple instructions is the actual store.
1527 LastStore = prior(oldNextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001528
1529 // If the stack slot value was previously available in some other
1530 // register, change it now. Otherwise, make the register available,
1531 // in PhysReg.
1532 Spills.ModifyStackSlotOrReMat(StackSlot);
1533 Spills.ClobberPhysReg(PhysReg);
1534 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1535 ++NumStores;
1536 }
1537
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001538 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1539 /// effect and all of its defs are dead.
1540 static bool isSafeToDelete(MachineInstr &MI) {
1541 const TargetInstrDesc &TID = MI.getDesc();
1542 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1543 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1544 TID.hasUnmodeledSideEffects())
1545 return false;
1546 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1547 MachineOperand &MO = MI.getOperand(i);
1548 if (!MO.isReg() || !MO.getReg())
1549 continue;
1550 if (MO.isDef() && !MO.isDead())
1551 return false;
1552 if (MO.isUse() && MO.isKill())
1553 // FIXME: We can't remove kill markers or else the scavenger will assert.
1554 // An alternative is to add a ADD pseudo instruction to replace kill
1555 // markers.
1556 return false;
1557 }
1558 return true;
1559 }
1560
Lang Hames87e3bca2009-05-06 02:36:21 +00001561 /// TransferDeadness - A identity copy definition is dead and it's being
1562 /// removed. Find the last def or use and mark it as dead / kill.
1563 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1564 unsigned Reg, BitVector &RegKills,
Evan Chengeca24fb2009-05-12 23:07:00 +00001565 std::vector<MachineOperand*> &KillOps,
1566 VirtRegMap &VRM) {
1567 SmallPtrSet<MachineInstr*, 4> Seens;
1568 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
Lang Hames87e3bca2009-05-06 02:36:21 +00001569 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1570 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1571 MachineInstr *UDMI = &*RI;
1572 if (UDMI->getParent() != MBB)
1573 continue;
1574 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1575 if (DI == DistanceMap.end() || DI->second > CurDist)
1576 continue;
Evan Chengeca24fb2009-05-12 23:07:00 +00001577 if (Seens.insert(UDMI))
1578 Refs.push_back(std::make_pair(UDMI, DI->second));
Lang Hames87e3bca2009-05-06 02:36:21 +00001579 }
1580
Evan Chengeca24fb2009-05-12 23:07:00 +00001581 if (Refs.empty())
1582 return;
1583 std::sort(Refs.begin(), Refs.end(), RefSorter());
1584
1585 while (!Refs.empty()) {
1586 MachineInstr *LastUDMI = Refs.back().first;
1587 Refs.pop_back();
1588
Lang Hames87e3bca2009-05-06 02:36:21 +00001589 MachineOperand *LastUD = NULL;
1590 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1591 MachineOperand &MO = LastUDMI->getOperand(i);
1592 if (!MO.isReg() || MO.getReg() != Reg)
1593 continue;
1594 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1595 LastUD = &MO;
1596 if (LastUDMI->isRegTiedToDefOperand(i))
Evan Chengeca24fb2009-05-12 23:07:00 +00001597 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001598 }
Evan Chengeca24fb2009-05-12 23:07:00 +00001599 if (LastUD->isDef()) {
1600 // If the instruction has no side effect, delete it and propagate
1601 // backward further. Otherwise, mark is dead and we are done.
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001602 if (!isSafeToDelete(*LastUDMI)) {
Evan Chengeca24fb2009-05-12 23:07:00 +00001603 LastUD->setIsDead();
1604 break;
1605 }
1606 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1607 MBB->erase(LastUDMI);
1608 } else {
Lang Hames87e3bca2009-05-06 02:36:21 +00001609 LastUD->setIsKill();
1610 RegKills.set(Reg);
1611 KillOps[Reg] = LastUD;
Evan Chengeca24fb2009-05-12 23:07:00 +00001612 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001613 }
1614 }
1615 }
1616
1617 /// rewriteMBB - Keep track of which spills are available even after the
1618 /// register allocator is done with them. If possible, avid reloading vregs.
1619 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1620 LiveIntervals *LIs,
1621 AvailableSpills &Spills, BitVector &RegKills,
1622 std::vector<MachineOperand*> &KillOps) {
1623
David Greene0ee52182010-01-05 01:25:52 +00001624 DEBUG(dbgs() << "\n**** Local spiller rewriting MBB '"
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001625 << MBB.getName() << "':\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001626
1627 MachineFunction &MF = *MBB.getParent();
1628
1629 // MaybeDeadStores - When we need to write a value back into a stack slot,
1630 // keep track of the inserted store. If the stack slot value is never read
1631 // (because the value was used from some available register, for example), and
1632 // subsequently stored to, the original store is dead. This map keeps track
1633 // of inserted stores that are not used. If we see a subsequent store to the
1634 // same stack slot, the original store is deleted.
1635 std::vector<MachineInstr*> MaybeDeadStores;
1636 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1637
1638 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1639 SmallSet<MachineInstr*, 4> ReMatDefs;
1640
1641 // Clear kill info.
1642 SmallSet<unsigned, 2> KilledMIRegs;
1643 RegKills.reset();
1644 KillOps.clear();
1645 KillOps.resize(TRI->getNumRegs(), NULL);
1646
1647 unsigned Dist = 0;
1648 DistanceMap.clear();
1649 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1650 MII != E; ) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00001651 MachineBasicBlock::iterator NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001652
1653 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1654 bool Erased = false;
1655 bool BackTracked = false;
1656 if (OptimizeByUnfold(MBB, MII,
1657 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
Chris Lattner7896c9f2009-12-03 00:50:42 +00001658 NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001659
1660 MachineInstr &MI = *MII;
1661
1662 if (VRM.hasEmergencySpills(&MI)) {
1663 // Spill physical register(s) in the rare case the allocator has run out
1664 // of registers to allocate.
1665 SmallSet<int, 4> UsedSS;
1666 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1667 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1668 unsigned PhysReg = EmSpills[i];
1669 const TargetRegisterClass *RC =
1670 TRI->getPhysicalRegisterRegClass(PhysReg);
1671 assert(RC && "Unable to determine register class!");
1672 int SS = VRM.getEmergencySpillSlot(RC);
1673 if (UsedSS.count(SS))
Torok Edwinc23197a2009-07-14 16:55:14 +00001674 llvm_unreachable("Need to spill more than one physical registers!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001675 UsedSS.insert(SS);
1676 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1677 MachineInstr *StoreMI = prior(MII);
1678 VRM.addSpillSlotUse(SS, StoreMI);
David Greene2d4e6d32009-07-28 16:49:24 +00001679
1680 // Back-schedule reloads and remats.
1681 MachineBasicBlock::iterator InsertLoc =
Chris Lattner7896c9f2009-12-03 00:50:42 +00001682 ComputeReloadLoc(llvm::next(MII), MBB.begin(), PhysReg, TRI, false,
David Greene2d4e6d32009-07-28 16:49:24 +00001683 SS, TII, MF);
1684
1685 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SS, RC);
1686
1687 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00001688 VRM.addSpillSlotUse(SS, LoadMI);
1689 ++NumPSpills;
Jakob Stoklund Olesen7a1e8722009-08-15 11:03:03 +00001690 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00001691 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001692 NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001693 }
1694
1695 // Insert restores here if asked to.
1696 if (VRM.isRestorePt(&MI)) {
1697 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1698 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1699 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1700 if (!VRM.getPreSplitReg(VirtReg))
1701 continue; // Split interval spilled again.
1702 unsigned Phys = VRM.getPhys(VirtReg);
1703 RegInfo->setPhysRegUsed(Phys);
1704
1705 // Check if the value being restored if available. If so, it must be
1706 // from a predecessor BB that fallthrough into this BB. We do not
1707 // expect:
1708 // BB1:
1709 // r1 = load fi#1
1710 // ...
1711 // = r1<kill>
1712 // ... # r1 not clobbered
1713 // ...
1714 // = load fi#1
1715 bool DoReMat = VRM.isReMaterialized(VirtReg);
1716 int SSorRMId = DoReMat
1717 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1718 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1719 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1720 if (InReg == Phys) {
1721 // If the value is already available in the expected register, save
1722 // a reload / remat.
1723 if (SSorRMId)
David Greene0ee52182010-01-05 01:25:52 +00001724 DEBUG(dbgs() << "Reusing RM#"
Chris Lattner6456d382009-08-23 03:20:44 +00001725 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001726 else
David Greene0ee52182010-01-05 01:25:52 +00001727 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1728 DEBUG(dbgs() << " from physreg "
Chris Lattner6456d382009-08-23 03:20:44 +00001729 << TRI->getName(InReg) << " for vreg"
1730 << VirtReg <<" instead of reloading into physreg "
1731 << TRI->getName(Phys) << '\n');
Lang Hames87e3bca2009-05-06 02:36:21 +00001732 ++NumOmitted;
1733 continue;
1734 } else if (InReg && InReg != Phys) {
1735 if (SSorRMId)
David Greene0ee52182010-01-05 01:25:52 +00001736 DEBUG(dbgs() << "Reusing RM#"
Chris Lattner6456d382009-08-23 03:20:44 +00001737 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001738 else
David Greene0ee52182010-01-05 01:25:52 +00001739 DEBUG(dbgs() << "Reusing SS#" << SSorRMId);
1740 DEBUG(dbgs() << " from physreg "
Chris Lattner6456d382009-08-23 03:20:44 +00001741 << TRI->getName(InReg) << " for vreg"
1742 << VirtReg <<" by copying it into physreg "
1743 << TRI->getName(Phys) << '\n');
Lang Hames87e3bca2009-05-06 02:36:21 +00001744
1745 // If the reloaded / remat value is available in another register,
1746 // copy it to the desired register.
David Greene2d4e6d32009-07-28 16:49:24 +00001747
1748 // Back-schedule reloads and remats.
1749 MachineBasicBlock::iterator InsertLoc =
1750 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1751 SSorRMId, TII, MF);
1752
1753 TII->copyRegToReg(MBB, InsertLoc, Phys, InReg, RC, RC);
Lang Hames87e3bca2009-05-06 02:36:21 +00001754
1755 // This invalidates Phys.
1756 Spills.ClobberPhysReg(Phys);
1757 // Remember it's available.
1758 Spills.addAvailable(SSorRMId, Phys);
1759
1760 // Mark is killed.
David Greene2d4e6d32009-07-28 16:49:24 +00001761 MachineInstr *CopyMI = prior(InsertLoc);
Chris Lattner45282ae2010-02-10 01:23:18 +00001762 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
Lang Hames87e3bca2009-05-06 02:36:21 +00001763 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1764 KillOpnd->setIsKill();
Evan Cheng427a6b62009-05-15 06:48:19 +00001765 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001766
David Greene0ee52182010-01-05 01:25:52 +00001767 DEBUG(dbgs() << '\t' << *CopyMI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001768 ++NumCopified;
1769 continue;
1770 }
1771
David Greene2d4e6d32009-07-28 16:49:24 +00001772 // Back-schedule reloads and remats.
1773 MachineBasicBlock::iterator InsertLoc =
1774 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1775 SSorRMId, TII, MF);
1776
Lang Hames87e3bca2009-05-06 02:36:21 +00001777 if (VRM.isReMaterialized(VirtReg)) {
David Greene2d4e6d32009-07-28 16:49:24 +00001778 ReMaterialize(MBB, InsertLoc, Phys, VirtReg, TII, TRI, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00001779 } else {
1780 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
David Greene2d4e6d32009-07-28 16:49:24 +00001781 TII->loadRegFromStackSlot(MBB, InsertLoc, Phys, SSorRMId, RC);
1782 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00001783 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1784 ++NumLoads;
Jakob Stoklund Olesen7a1e8722009-08-15 11:03:03 +00001785 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00001786 }
1787
1788 // This invalidates Phys.
1789 Spills.ClobberPhysReg(Phys);
1790 // Remember it's available.
1791 Spills.addAvailable(SSorRMId, Phys);
1792
David Greene2d4e6d32009-07-28 16:49:24 +00001793 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
David Greene0ee52182010-01-05 01:25:52 +00001794 DEBUG(dbgs() << '\t' << *prior(MII));
Lang Hames87e3bca2009-05-06 02:36:21 +00001795 }
1796 }
1797
1798 // Insert spills here if asked to.
1799 if (VRM.isSpillPt(&MI)) {
1800 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1801 VRM.getSpillPtSpills(&MI);
1802 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1803 unsigned VirtReg = SpillRegs[i].first;
1804 bool isKill = SpillRegs[i].second;
1805 if (!VRM.getPreSplitReg(VirtReg))
1806 continue; // Split interval spilled again.
1807 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1808 unsigned Phys = VRM.getPhys(VirtReg);
1809 int StackSlot = VRM.getStackSlot(VirtReg);
Chris Lattner7896c9f2009-12-03 00:50:42 +00001810 MachineBasicBlock::iterator oldNextMII = llvm::next(MII);
1811 TII->storeRegToStackSlot(MBB, llvm::next(MII), Phys, isKill, StackSlot, RC);
Dale Johannesen78c5cda2009-10-29 01:15:40 +00001812 MachineInstr *StoreMI = prior(oldNextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001813 VRM.addSpillSlotUse(StackSlot, StoreMI);
David Greene0ee52182010-01-05 01:25:52 +00001814 DEBUG(dbgs() << "Store:\t" << *StoreMI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001815 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1816 }
Chris Lattner7896c9f2009-12-03 00:50:42 +00001817 NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001818 }
1819
1820 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1821 /// reuse.
1822 ReuseInfo ReusedOperands(MI, TRI);
1823 SmallVector<unsigned, 4> VirtUseOps;
1824 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1825 MachineOperand &MO = MI.getOperand(i);
1826 if (!MO.isReg() || MO.getReg() == 0)
1827 continue; // Ignore non-register operands.
1828
1829 unsigned VirtReg = MO.getReg();
1830 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1831 // Ignore physregs for spilling, but remember that it is used by this
1832 // function.
1833 RegInfo->setPhysRegUsed(VirtReg);
1834 continue;
1835 }
1836
1837 // We want to process implicit virtual register uses first.
1838 if (MO.isImplicit())
1839 // If the virtual register is implicitly defined, emit a implicit_def
1840 // before so scavenger knows it's "defined".
Evan Cheng4784f1f2009-06-30 08:49:04 +00001841 // FIXME: This is a horrible hack done the by register allocator to
1842 // remat a definition with virtual register operand.
Lang Hames87e3bca2009-05-06 02:36:21 +00001843 VirtUseOps.insert(VirtUseOps.begin(), i);
1844 else
1845 VirtUseOps.push_back(i);
1846 }
1847
1848 // Process all of the spilled uses and all non spilled reg references.
1849 SmallVector<int, 2> PotentialDeadStoreSlots;
1850 KilledMIRegs.clear();
1851 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1852 unsigned i = VirtUseOps[j];
1853 MachineOperand &MO = MI.getOperand(i);
1854 unsigned VirtReg = MO.getReg();
1855 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1856 "Not a virtual register?");
1857
1858 unsigned SubIdx = MO.getSubReg();
1859 if (VRM.isAssignedReg(VirtReg)) {
1860 // This virtual register was assigned a physreg!
1861 unsigned Phys = VRM.getPhys(VirtReg);
1862 RegInfo->setPhysRegUsed(Phys);
1863 if (MO.isDef())
1864 ReusedOperands.markClobbered(Phys);
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001865 substitutePhysReg(MO, Phys, *TRI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001866 if (VRM.isImplicitlyDefined(VirtReg))
Evan Cheng4784f1f2009-06-30 08:49:04 +00001867 // FIXME: Is this needed?
Lang Hames87e3bca2009-05-06 02:36:21 +00001868 BuildMI(MBB, &MI, MI.getDebugLoc(),
Chris Lattner518bb532010-02-09 19:54:29 +00001869 TII->get(TargetOpcode::IMPLICIT_DEF), Phys);
Lang Hames87e3bca2009-05-06 02:36:21 +00001870 continue;
1871 }
Jakob Stoklund Olesen8efadf92010-01-06 00:29:28 +00001872
Lang Hames87e3bca2009-05-06 02:36:21 +00001873 // This virtual register is now known to be a spilled value.
1874 if (!MO.isUse())
1875 continue; // Handle defs in the loop below (handle use&def here though)
1876
Evan Cheng4784f1f2009-06-30 08:49:04 +00001877 bool AvoidReload = MO.isUndef();
1878 // Check if it is defined by an implicit def. It should not be spilled.
1879 // Note, this is for correctness reason. e.g.
1880 // 8 %reg1024<def> = IMPLICIT_DEF
1881 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1882 // The live range [12, 14) are not part of the r1024 live interval since
1883 // it's defined by an implicit def. It will not conflicts with live
1884 // interval of r1025. Now suppose both registers are spilled, you can
1885 // easily see a situation where both registers are reloaded before
1886 // the INSERT_SUBREG and both target registers that would overlap.
Lang Hames87e3bca2009-05-06 02:36:21 +00001887 bool DoReMat = VRM.isReMaterialized(VirtReg);
1888 int SSorRMId = DoReMat
1889 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1890 int ReuseSlot = SSorRMId;
1891
1892 // Check to see if this stack slot is available.
1893 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1894
1895 // If this is a sub-register use, make sure the reuse register is in the
1896 // right register class. For example, for x86 not all of the 32-bit
1897 // registers have accessible sub-registers.
1898 // Similarly so for EXTRACT_SUBREG. Consider this:
1899 // EDI = op
1900 // MOV32_mr fi#1, EDI
1901 // ...
1902 // = EXTRACT_SUBREG fi#1
1903 // fi#1 is available in EDI, but it cannot be reused because it's not in
1904 // the right register file.
Chris Lattner518bb532010-02-09 19:54:29 +00001905 if (PhysReg && !AvoidReload && (SubIdx || MI.isExtractSubreg())) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001906 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1907 if (!RC->contains(PhysReg))
1908 PhysReg = 0;
1909 }
1910
1911 if (PhysReg && !AvoidReload) {
1912 // This spilled operand might be part of a two-address operand. If this
1913 // is the case, then changing it will necessarily require changing the
1914 // def part of the instruction as well. However, in some cases, we
1915 // aren't allowed to modify the reused register. If none of these cases
1916 // apply, reuse it.
1917 bool CanReuse = true;
1918 bool isTied = MI.isRegTiedToDefOperand(i);
1919 if (isTied) {
1920 // Okay, we have a two address operand. We can reuse this physreg as
1921 // long as we are allowed to clobber the value and there isn't an
1922 // earlier def that has already clobbered the physreg.
1923 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1924 Spills.canClobberPhysReg(PhysReg);
1925 }
1926
1927 if (CanReuse) {
1928 // If this stack slot value is already available, reuse it!
1929 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
David Greene0ee52182010-01-05 01:25:52 +00001930 DEBUG(dbgs() << "Reusing RM#"
Chris Lattner6456d382009-08-23 03:20:44 +00001931 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001932 else
David Greene0ee52182010-01-05 01:25:52 +00001933 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
1934 DEBUG(dbgs() << " from physreg "
Chris Lattner6456d382009-08-23 03:20:44 +00001935 << TRI->getName(PhysReg) << " for vreg"
1936 << VirtReg <<" instead of reloading into physreg "
1937 << TRI->getName(VRM.getPhys(VirtReg)) << '\n');
Lang Hames87e3bca2009-05-06 02:36:21 +00001938 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1939 MI.getOperand(i).setReg(RReg);
1940 MI.getOperand(i).setSubReg(0);
1941
1942 // The only technical detail we have is that we don't know that
1943 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1944 // later in the instruction. In particular, consider 'op V1, V2'.
1945 // If V1 is available in physreg R0, we would choose to reuse it
1946 // here, instead of reloading it into the register the allocator
1947 // indicated (say R1). However, V2 might have to be reloaded
1948 // later, and it might indicate that it needs to live in R0. When
1949 // this occurs, we need to have information available that
1950 // indicates it is safe to use R1 for the reload instead of R0.
1951 //
1952 // To further complicate matters, we might conflict with an alias,
1953 // or R0 and R1 might not be compatible with each other. In this
1954 // case, we actually insert a reload for V1 in R1, ensuring that
1955 // we can get at R0 or its alias.
1956 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1957 VRM.getPhys(VirtReg), VirtReg);
1958 if (isTied)
1959 // Only mark it clobbered if this is a use&def operand.
1960 ReusedOperands.markClobbered(PhysReg);
1961 ++NumReused;
1962
1963 if (MI.getOperand(i).isKill() &&
1964 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1965
1966 // The store of this spilled value is potentially dead, but we
1967 // won't know for certain until we've confirmed that the re-use
1968 // above is valid, which means waiting until the other operands
1969 // are processed. For now we just track the spill slot, we'll
1970 // remove it after the other operands are processed if valid.
1971
1972 PotentialDeadStoreSlots.push_back(ReuseSlot);
1973 }
1974
1975 // Mark is isKill if it's there no other uses of the same virtual
1976 // register and it's not a two-address operand. IsKill will be
1977 // unset if reg is reused.
1978 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1979 MI.getOperand(i).setIsKill();
1980 KilledMIRegs.insert(VirtReg);
1981 }
1982
1983 continue;
1984 } // CanReuse
1985
1986 // Otherwise we have a situation where we have a two-address instruction
1987 // whose mod/ref operand needs to be reloaded. This reload is already
1988 // available in some register "PhysReg", but if we used PhysReg as the
1989 // operand to our 2-addr instruction, the instruction would modify
1990 // PhysReg. This isn't cool if something later uses PhysReg and expects
1991 // to get its initial value.
1992 //
1993 // To avoid this problem, and to avoid doing a load right after a store,
1994 // we emit a copy from PhysReg into the designated register for this
1995 // operand.
1996 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1997 assert(DesignatedReg && "Must map virtreg to physreg!");
1998
1999 // Note that, if we reused a register for a previous operand, the
2000 // register we want to reload into might not actually be
2001 // available. If this occurs, use the register indicated by the
2002 // reuser.
2003 if (ReusedOperands.hasReuses())
Evan Cheng5d885022009-07-21 09:15:00 +00002004 DesignatedReg = ReusedOperands.GetRegForReload(VirtReg,
2005 DesignatedReg, &MI,
2006 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002007
2008 // If the mapped designated register is actually the physreg we have
2009 // incoming, we don't need to inserted a dead copy.
2010 if (DesignatedReg == PhysReg) {
2011 // If this stack slot value is already available, reuse it!
2012 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
David Greene0ee52182010-01-05 01:25:52 +00002013 DEBUG(dbgs() << "Reusing RM#"
Chris Lattner6456d382009-08-23 03:20:44 +00002014 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00002015 else
David Greene0ee52182010-01-05 01:25:52 +00002016 DEBUG(dbgs() << "Reusing SS#" << ReuseSlot);
2017 DEBUG(dbgs() << " from physreg " << TRI->getName(PhysReg)
Chris Lattner6456d382009-08-23 03:20:44 +00002018 << " for vreg" << VirtReg
2019 << " instead of reloading into same physreg.\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00002020 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2021 MI.getOperand(i).setReg(RReg);
2022 MI.getOperand(i).setSubReg(0);
2023 ReusedOperands.markClobbered(RReg);
2024 ++NumReused;
2025 continue;
2026 }
2027
2028 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
2029 RegInfo->setPhysRegUsed(DesignatedReg);
2030 ReusedOperands.markClobbered(DesignatedReg);
Lang Hames87e3bca2009-05-06 02:36:21 +00002031
David Greene2d4e6d32009-07-28 16:49:24 +00002032 // Back-schedule reloads and remats.
2033 MachineBasicBlock::iterator InsertLoc =
2034 ComputeReloadLoc(&MI, MBB.begin(), PhysReg, TRI, DoReMat,
2035 SSorRMId, TII, MF);
2036
2037 TII->copyRegToReg(MBB, InsertLoc, DesignatedReg, PhysReg, RC, RC);
2038
2039 MachineInstr *CopyMI = prior(InsertLoc);
Chris Lattner45282ae2010-02-10 01:23:18 +00002040 CopyMI->setAsmPrinterFlag(MachineInstr::ReloadReuse);
Evan Cheng427a6b62009-05-15 06:48:19 +00002041 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002042
2043 // This invalidates DesignatedReg.
2044 Spills.ClobberPhysReg(DesignatedReg);
2045
2046 Spills.addAvailable(ReuseSlot, DesignatedReg);
2047 unsigned RReg =
2048 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2049 MI.getOperand(i).setReg(RReg);
2050 MI.getOperand(i).setSubReg(0);
David Greene0ee52182010-01-05 01:25:52 +00002051 DEBUG(dbgs() << '\t' << *prior(MII));
Lang Hames87e3bca2009-05-06 02:36:21 +00002052 ++NumReused;
2053 continue;
2054 } // if (PhysReg)
2055
2056 // Otherwise, reload it and remember that we have it.
2057 PhysReg = VRM.getPhys(VirtReg);
2058 assert(PhysReg && "Must map virtreg to physreg!");
2059
2060 // Note that, if we reused a register for a previous operand, the
2061 // register we want to reload into might not actually be
2062 // available. If this occurs, use the register indicated by the
2063 // reuser.
2064 if (ReusedOperands.hasReuses())
Evan Cheng5d885022009-07-21 09:15:00 +00002065 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2066 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002067
2068 RegInfo->setPhysRegUsed(PhysReg);
2069 ReusedOperands.markClobbered(PhysReg);
2070 if (AvoidReload)
2071 ++NumAvoided;
2072 else {
David Greene2d4e6d32009-07-28 16:49:24 +00002073 // Back-schedule reloads and remats.
2074 MachineBasicBlock::iterator InsertLoc =
2075 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, DoReMat,
2076 SSorRMId, TII, MF);
2077
Lang Hames87e3bca2009-05-06 02:36:21 +00002078 if (DoReMat) {
David Greene2d4e6d32009-07-28 16:49:24 +00002079 ReMaterialize(MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002080 } else {
2081 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
David Greene2d4e6d32009-07-28 16:49:24 +00002082 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SSorRMId, RC);
2083 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00002084 VRM.addSpillSlotUse(SSorRMId, LoadMI);
2085 ++NumLoads;
Jakob Stoklund Olesen7a1e8722009-08-15 11:03:03 +00002086 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00002087 }
2088 // This invalidates PhysReg.
2089 Spills.ClobberPhysReg(PhysReg);
2090
2091 // Any stores to this stack slot are not dead anymore.
2092 if (!DoReMat)
2093 MaybeDeadStores[SSorRMId] = NULL;
2094 Spills.addAvailable(SSorRMId, PhysReg);
2095 // Assumes this is the last use. IsKill will be unset if reg is reused
2096 // unless it's a two-address operand.
2097 if (!MI.isRegTiedToDefOperand(i) &&
2098 KilledMIRegs.count(VirtReg) == 0) {
2099 MI.getOperand(i).setIsKill();
2100 KilledMIRegs.insert(VirtReg);
2101 }
2102
David Greene2d4e6d32009-07-28 16:49:24 +00002103 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
David Greene0ee52182010-01-05 01:25:52 +00002104 DEBUG(dbgs() << '\t' << *prior(InsertLoc));
Lang Hames87e3bca2009-05-06 02:36:21 +00002105 }
2106 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2107 MI.getOperand(i).setReg(RReg);
2108 MI.getOperand(i).setSubReg(0);
2109 }
2110
2111 // Ok - now we can remove stores that have been confirmed dead.
2112 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2113 // This was the last use and the spilled value is still available
2114 // for reuse. That means the spill was unnecessary!
2115 int PDSSlot = PotentialDeadStoreSlots[j];
2116 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2117 if (DeadStore) {
David Greene0ee52182010-01-05 01:25:52 +00002118 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002119 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002120 VRM.RemoveMachineInstrFromMaps(DeadStore);
2121 MBB.erase(DeadStore);
2122 MaybeDeadStores[PDSSlot] = NULL;
2123 ++NumDSE;
2124 }
2125 }
2126
2127
David Greene0ee52182010-01-05 01:25:52 +00002128 DEBUG(dbgs() << '\t' << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002129
2130
2131 // If we have folded references to memory operands, make sure we clear all
2132 // physical registers that may contain the value of the spilled virtual
2133 // register
2134 SmallSet<int, 2> FoldedSS;
2135 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
2136 unsigned VirtReg = I->second.first;
2137 VirtRegMap::ModRef MR = I->second.second;
David Greene0ee52182010-01-05 01:25:52 +00002138 DEBUG(dbgs() << "Folded vreg: " << VirtReg << " MR: " << MR);
Lang Hames87e3bca2009-05-06 02:36:21 +00002139
2140 // MI2VirtMap be can updated which invalidate the iterator.
2141 // Increment the iterator first.
2142 ++I;
2143 int SS = VRM.getStackSlot(VirtReg);
2144 if (SS == VirtRegMap::NO_STACK_SLOT)
2145 continue;
2146 FoldedSS.insert(SS);
David Greene0ee52182010-01-05 01:25:52 +00002147 DEBUG(dbgs() << " - StackSlot: " << SS << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00002148
2149 // If this folded instruction is just a use, check to see if it's a
2150 // straight load from the virt reg slot.
2151 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2152 int FrameIdx;
2153 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2154 if (DestReg && FrameIdx == SS) {
2155 // If this spill slot is available, turn it into a copy (or nothing)
2156 // instead of leaving it as a load!
2157 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
David Greene0ee52182010-01-05 01:25:52 +00002158 DEBUG(dbgs() << "Promoted Load To Copy: " << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002159 if (DestReg != InReg) {
2160 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2161 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
2162 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2163 unsigned SubIdx = DefMO->getSubReg();
2164 // Revisit the copy so we make sure to notice the effects of the
2165 // operation on the destreg (either needing to RA it if it's
2166 // virtual or needing to clobber any values if it's physical).
2167 NextMII = &MI;
2168 --NextMII; // backtrack to the copy.
Chris Lattner45282ae2010-02-10 01:23:18 +00002169 NextMII->setAsmPrinterFlag(MachineInstr::ReloadReuse);
Lang Hames87e3bca2009-05-06 02:36:21 +00002170 // Propagate the sub-register index over.
2171 if (SubIdx) {
2172 DefMO = NextMII->findRegisterDefOperand(DestReg);
2173 DefMO->setSubReg(SubIdx);
2174 }
2175
2176 // Mark is killed.
2177 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
2178 KillOpnd->setIsKill();
2179
2180 BackTracked = true;
2181 } else {
David Greene0ee52182010-01-05 01:25:52 +00002182 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002183 // Unset last kill since it's being reused.
Evan Cheng427a6b62009-05-15 06:48:19 +00002184 InvalidateKill(InReg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002185 Spills.disallowClobberPhysReg(InReg);
2186 }
2187
Evan Cheng427a6b62009-05-15 06:48:19 +00002188 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002189 VRM.RemoveMachineInstrFromMaps(&MI);
2190 MBB.erase(&MI);
2191 Erased = true;
2192 goto ProcessNextInst;
2193 }
2194 } else {
2195 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2196 SmallVector<MachineInstr*, 4> NewMIs;
2197 if (PhysReg &&
2198 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2199 MBB.insert(MII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00002200 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002201 VRM.RemoveMachineInstrFromMaps(&MI);
2202 MBB.erase(&MI);
2203 Erased = true;
2204 --NextMII; // backtrack to the unfolded instruction.
2205 BackTracked = true;
2206 goto ProcessNextInst;
2207 }
2208 }
2209 }
2210
2211 // If this reference is not a use, any previous store is now dead.
2212 // Otherwise, the store to this stack slot is not dead anymore.
2213 MachineInstr* DeadStore = MaybeDeadStores[SS];
2214 if (DeadStore) {
2215 bool isDead = !(MR & VirtRegMap::isRef);
2216 MachineInstr *NewStore = NULL;
2217 if (MR & VirtRegMap::isModRef) {
2218 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2219 SmallVector<MachineInstr*, 4> NewMIs;
2220 // We can reuse this physreg as long as we are allowed to clobber
2221 // the value and there isn't an earlier def that has already clobbered
2222 // the physreg.
2223 if (PhysReg &&
2224 !ReusedOperands.isClobbered(PhysReg) &&
2225 Spills.canClobberPhysReg(PhysReg) &&
2226 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2227 MachineOperand *KillOpnd =
2228 DeadStore->findRegisterUseOperand(PhysReg, true);
2229 // Note, if the store is storing a sub-register, it's possible the
2230 // super-register is needed below.
2231 if (KillOpnd && !KillOpnd->getSubReg() &&
2232 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2233 MBB.insert(MII, NewMIs[0]);
2234 NewStore = NewMIs[1];
2235 MBB.insert(MII, NewStore);
2236 VRM.addSpillSlotUse(SS, NewStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002237 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002238 VRM.RemoveMachineInstrFromMaps(&MI);
2239 MBB.erase(&MI);
2240 Erased = true;
2241 --NextMII;
2242 --NextMII; // backtrack to the unfolded instruction.
2243 BackTracked = true;
2244 isDead = true;
2245 ++NumSUnfold;
2246 }
2247 }
2248 }
2249
2250 if (isDead) { // Previous store is dead.
2251 // If we get here, the store is dead, nuke it now.
David Greene0ee52182010-01-05 01:25:52 +00002252 DEBUG(dbgs() << "Removed dead store:\t" << *DeadStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002253 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002254 VRM.RemoveMachineInstrFromMaps(DeadStore);
2255 MBB.erase(DeadStore);
2256 if (!NewStore)
2257 ++NumDSE;
2258 }
2259
2260 MaybeDeadStores[SS] = NULL;
2261 if (NewStore) {
2262 // Treat this store as a spill merged into a copy. That makes the
2263 // stack slot value available.
2264 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2265 goto ProcessNextInst;
2266 }
2267 }
2268
2269 // If the spill slot value is available, and this is a new definition of
2270 // the value, the value is not available anymore.
2271 if (MR & VirtRegMap::isMod) {
2272 // Notice that the value in this stack slot has been modified.
2273 Spills.ModifyStackSlotOrReMat(SS);
2274
2275 // If this is *just* a mod of the value, check to see if this is just a
2276 // store to the spill slot (i.e. the spill got merged into the copy). If
2277 // so, realize that the vreg is available now, and add the store to the
2278 // MaybeDeadStore info.
2279 int StackSlot;
2280 if (!(MR & VirtRegMap::isRef)) {
2281 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2282 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2283 "Src hasn't been allocated yet?");
2284
2285 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2286 Spills, RegKills, KillOps, TRI, VRM)) {
Chris Lattner7896c9f2009-12-03 00:50:42 +00002287 NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00002288 BackTracked = true;
2289 goto ProcessNextInst;
2290 }
2291
2292 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2293 // this as a potentially dead store in case there is a subsequent
2294 // store into the stack slot without a read from it.
2295 MaybeDeadStores[StackSlot] = &MI;
2296
2297 // If the stack slot value was previously available in some other
2298 // register, change it now. Otherwise, make the register
2299 // available in PhysReg.
2300 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2301 }
2302 }
2303 }
2304 }
2305
2306 // Process all of the spilled defs.
2307 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2308 MachineOperand &MO = MI.getOperand(i);
2309 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2310 continue;
2311
2312 unsigned VirtReg = MO.getReg();
2313 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2314 // Check to see if this is a noop copy. If so, eliminate the
2315 // instruction before considering the dest reg to be changed.
Evan Cheng2578ba22009-07-01 01:59:31 +00002316 // Also check if it's copying from an "undef", if so, we can't
2317 // eliminate this or else the undef marker is lost and it will
2318 // confuses the scavenger. This is extremely rare.
Lang Hames87e3bca2009-05-06 02:36:21 +00002319 unsigned Src, Dst, SrcSR, DstSR;
Evan Chenga5dc45e2009-10-26 04:56:07 +00002320 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
Evan Cheng2578ba22009-07-01 01:59:31 +00002321 !MI.findRegisterUseOperand(Src)->isUndef()) {
Lang Hames87e3bca2009-05-06 02:36:21 +00002322 ++NumDCE;
David Greene0ee52182010-01-05 01:25:52 +00002323 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002324 SmallVector<unsigned, 2> KillRegs;
Evan Cheng427a6b62009-05-15 06:48:19 +00002325 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
Lang Hames87e3bca2009-05-06 02:36:21 +00002326 if (MO.isDead() && !KillRegs.empty()) {
2327 // Source register or an implicit super/sub-register use is killed.
2328 assert(KillRegs[0] == Dst ||
2329 TRI->isSubRegister(KillRegs[0], Dst) ||
2330 TRI->isSuperRegister(KillRegs[0], Dst));
2331 // Last def is now dead.
Evan Chengeca24fb2009-05-12 23:07:00 +00002332 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002333 }
2334 VRM.RemoveMachineInstrFromMaps(&MI);
2335 MBB.erase(&MI);
2336 Erased = true;
2337 Spills.disallowClobberPhysReg(VirtReg);
2338 goto ProcessNextInst;
2339 }
Evan Cheng2578ba22009-07-01 01:59:31 +00002340
Lang Hames87e3bca2009-05-06 02:36:21 +00002341 // If it's not a no-op copy, it clobbers the value in the destreg.
2342 Spills.ClobberPhysReg(VirtReg);
2343 ReusedOperands.markClobbered(VirtReg);
2344
2345 // Check to see if this instruction is a load from a stack slot into
2346 // a register. If so, this provides the stack slot value in the reg.
2347 int FrameIdx;
2348 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2349 assert(DestReg == VirtReg && "Unknown load situation!");
2350
2351 // If it is a folded reference, then it's not safe to clobber.
2352 bool Folded = FoldedSS.count(FrameIdx);
2353 // Otherwise, if it wasn't available, remember that it is now!
2354 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2355 goto ProcessNextInst;
2356 }
2357
2358 continue;
2359 }
2360
2361 unsigned SubIdx = MO.getSubReg();
2362 bool DoReMat = VRM.isReMaterialized(VirtReg);
2363 if (DoReMat)
2364 ReMatDefs.insert(&MI);
2365
2366 // The only vregs left are stack slot definitions.
2367 int StackSlot = VRM.getStackSlot(VirtReg);
2368 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2369
2370 // If this def is part of a two-address operand, make sure to execute
2371 // the store from the correct physical register.
2372 unsigned PhysReg;
2373 unsigned TiedOp;
2374 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2375 PhysReg = MI.getOperand(TiedOp).getReg();
2376 if (SubIdx) {
2377 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2378 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2379 "Can't find corresponding super-register!");
2380 PhysReg = SuperReg;
2381 }
2382 } else {
2383 PhysReg = VRM.getPhys(VirtReg);
2384 if (ReusedOperands.isClobbered(PhysReg)) {
2385 // Another def has taken the assigned physreg. It must have been a
2386 // use&def which got it due to reuse. Undo the reuse!
Evan Cheng5d885022009-07-21 09:15:00 +00002387 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2388 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002389 }
2390 }
2391
2392 assert(PhysReg && "VR not assigned a physical register?");
2393 RegInfo->setPhysRegUsed(PhysReg);
2394 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2395 ReusedOperands.markClobbered(RReg);
2396 MI.getOperand(i).setReg(RReg);
2397 MI.getOperand(i).setSubReg(0);
2398
2399 if (!MO.isDead()) {
2400 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2401 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2402 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
Chris Lattner7896c9f2009-12-03 00:50:42 +00002403 NextMII = llvm::next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00002404
2405 // Check to see if this is a noop copy. If so, eliminate the
2406 // instruction before considering the dest reg to be changed.
2407 {
2408 unsigned Src, Dst, SrcSR, DstSR;
Evan Chenga5dc45e2009-10-26 04:56:07 +00002409 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
Lang Hames87e3bca2009-05-06 02:36:21 +00002410 ++NumDCE;
David Greene0ee52182010-01-05 01:25:52 +00002411 DEBUG(dbgs() << "Removing now-noop copy: " << MI);
Evan Cheng427a6b62009-05-15 06:48:19 +00002412 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002413 VRM.RemoveMachineInstrFromMaps(&MI);
2414 MBB.erase(&MI);
2415 Erased = true;
Evan Cheng427a6b62009-05-15 06:48:19 +00002416 UpdateKills(*LastStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002417 goto ProcessNextInst;
2418 }
2419 }
2420 }
2421 }
2422 ProcessNextInst:
Evan Cheng52484682009-07-18 02:10:10 +00002423 // Delete dead instructions without side effects.
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00002424 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
Evan Cheng52484682009-07-18 02:10:10 +00002425 InvalidateKills(MI, TRI, RegKills, KillOps);
2426 VRM.RemoveMachineInstrFromMaps(&MI);
2427 MBB.erase(&MI);
2428 Erased = true;
2429 }
2430 if (!Erased)
2431 DistanceMap.insert(std::make_pair(&MI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00002432 if (!Erased && !BackTracked) {
2433 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
Evan Cheng427a6b62009-05-15 06:48:19 +00002434 UpdateKills(*II, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002435 }
2436 MII = NextMII;
2437 }
2438
2439 }
2440
2441};
2442
Dan Gohman7db949d2009-08-07 01:32:21 +00002443}
2444
Lang Hames87e3bca2009-05-06 02:36:21 +00002445llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2446 switch (RewriterOpt) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002447 default: llvm_unreachable("Unreachable!");
Lang Hames87e3bca2009-05-06 02:36:21 +00002448 case local:
2449 return new LocalRewriter();
Lang Hamesf41538d2009-06-02 16:53:25 +00002450 case trivial:
2451 return new TrivialRewriter();
Lang Hames87e3bca2009-05-06 02:36:21 +00002452 }
2453}