blob: dcd2a75ae0e700d20546c6e89bfbc7760d9e7d3b [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
Dan Gohman7db949d2009-08-07 01:32:21 +000063namespace {
Lang Hames87e3bca2009-05-06 02:36:21 +000064
Lang Hamesf41538d2009-06-02 16:53:25 +000065/// This class is intended for use with the new spilling framework only. It
66/// rewrites vreg def/uses to use the assigned preg, but does not insert any
67/// spill code.
Nick Lewycky6726b6d2009-10-25 06:33:48 +000068struct TrivialRewriter : public VirtRegRewriter {
Lang Hamesf41538d2009-06-02 16:53:25 +000069
70 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
71 LiveIntervals* LIs) {
Chris Lattner6456d382009-08-23 03:20:44 +000072 DEBUG(errs() << "********** REWRITE MACHINE CODE **********\n");
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000073 DEBUG(errs() << "********** Function: "
74 << MF.getFunction()->getName() << '\n');
Chris Lattner6456d382009-08-23 03:20:44 +000075 DEBUG(errs() << "**** Machine Instrs"
76 << "(NOTE! Does not include spills and reloads!) ****\n");
David Greene2d4e6d32009-07-28 16:49:24 +000077 DEBUG(MF.dump());
78
Lang Hamesf41538d2009-06-02 16:53:25 +000079 MachineRegisterInfo *mri = &MF.getRegInfo();
80
81 bool changed = false;
82
83 for (LiveIntervals::iterator liItr = LIs->begin(), liEnd = LIs->end();
84 liItr != liEnd; ++liItr) {
85
86 if (TargetRegisterInfo::isVirtualRegister(liItr->first)) {
87 if (VRM.hasPhys(liItr->first)) {
88 unsigned preg = VRM.getPhys(liItr->first);
89 mri->replaceRegWith(liItr->first, preg);
90 mri->setPhysRegUsed(preg);
91 changed = true;
92 }
93 }
94 else {
95 if (!liItr->second->empty()) {
96 mri->setPhysRegUsed(liItr->first);
97 }
98 }
99 }
David Greene2d4e6d32009-07-28 16:49:24 +0000100
101
Chris Lattner6456d382009-08-23 03:20:44 +0000102 DEBUG(errs() << "**** Post Machine Instrs ****\n");
David Greene2d4e6d32009-07-28 16:49:24 +0000103 DEBUG(MF.dump());
Lang Hamesf41538d2009-06-02 16:53:25 +0000104
105 return changed;
106 }
107
108};
109
Dan Gohman7db949d2009-08-07 01:32:21 +0000110}
111
Lang Hames87e3bca2009-05-06 02:36:21 +0000112// ************************************************************************ //
113
Dan Gohman7db949d2009-08-07 01:32:21 +0000114namespace {
115
Lang Hames87e3bca2009-05-06 02:36:21 +0000116/// AvailableSpills - As the local rewriter is scanning and rewriting an MBB
117/// from top down, keep track of which spill slots or remat are available in
118/// each register.
119///
120/// Note that not all physregs are created equal here. In particular, some
121/// physregs are reloads that we are allowed to clobber or ignore at any time.
122/// Other physregs are values that the register allocated program is using
123/// that we cannot CHANGE, but we can read if we like. We keep track of this
124/// on a per-stack-slot / remat id basis as the low bit in the value of the
125/// SpillSlotsAvailable entries. The predicate 'canClobberPhysReg()' checks
126/// this bit and addAvailable sets it if.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000127class AvailableSpills {
Lang Hames87e3bca2009-05-06 02:36:21 +0000128 const TargetRegisterInfo *TRI;
129 const TargetInstrInfo *TII;
130
131 // SpillSlotsOrReMatsAvailable - This map keeps track of all of the spilled
132 // or remat'ed virtual register values that are still available, due to
133 // being loaded or stored to, but not invalidated yet.
134 std::map<int, unsigned> SpillSlotsOrReMatsAvailable;
135
136 // PhysRegsAvailable - This is the inverse of SpillSlotsOrReMatsAvailable,
137 // indicating which stack slot values are currently held by a physreg. This
138 // is used to invalidate entries in SpillSlotsOrReMatsAvailable when a
139 // physreg is modified.
140 std::multimap<unsigned, int> PhysRegsAvailable;
141
142 void disallowClobberPhysRegOnly(unsigned PhysReg);
143
144 void ClobberPhysRegOnly(unsigned PhysReg);
145public:
146 AvailableSpills(const TargetRegisterInfo *tri, const TargetInstrInfo *tii)
147 : TRI(tri), TII(tii) {
148 }
149
150 /// clear - Reset the state.
151 void clear() {
152 SpillSlotsOrReMatsAvailable.clear();
153 PhysRegsAvailable.clear();
154 }
155
156 const TargetRegisterInfo *getRegInfo() const { return TRI; }
157
158 /// getSpillSlotOrReMatPhysReg - If the specified stack slot or remat is
159 /// available in a physical register, return that PhysReg, otherwise
160 /// return 0.
161 unsigned getSpillSlotOrReMatPhysReg(int Slot) const {
162 std::map<int, unsigned>::const_iterator I =
163 SpillSlotsOrReMatsAvailable.find(Slot);
164 if (I != SpillSlotsOrReMatsAvailable.end()) {
165 return I->second >> 1; // Remove the CanClobber bit.
166 }
167 return 0;
168 }
169
170 /// addAvailable - Mark that the specified stack slot / remat is available
171 /// in the specified physreg. If CanClobber is true, the physreg can be
172 /// modified at any time without changing the semantics of the program.
173 void addAvailable(int SlotOrReMat, unsigned Reg, bool CanClobber = true) {
174 // If this stack slot is thought to be available in some other physreg,
175 // remove its record.
176 ModifyStackSlotOrReMat(SlotOrReMat);
177
178 PhysRegsAvailable.insert(std::make_pair(Reg, SlotOrReMat));
179 SpillSlotsOrReMatsAvailable[SlotOrReMat]= (Reg << 1) |
180 (unsigned)CanClobber;
181
182 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
Chris Lattner6456d382009-08-23 03:20:44 +0000183 DEBUG(errs() << "Remembering RM#"
184 << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +0000185 else
Chris Lattner6456d382009-08-23 03:20:44 +0000186 DEBUG(errs() << "Remembering SS#" << SlotOrReMat);
187 DEBUG(errs() << " in physreg " << TRI->getName(Reg) << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000188 }
189
190 /// canClobberPhysRegForSS - Return true if the spiller is allowed to change
191 /// the value of the specified stackslot register if it desires. The
192 /// specified stack slot must be available in a physreg for this query to
193 /// make sense.
194 bool canClobberPhysRegForSS(int SlotOrReMat) const {
195 assert(SpillSlotsOrReMatsAvailable.count(SlotOrReMat) &&
196 "Value not available!");
197 return SpillSlotsOrReMatsAvailable.find(SlotOrReMat)->second & 1;
198 }
199
200 /// canClobberPhysReg - Return true if the spiller is allowed to clobber the
201 /// physical register where values for some stack slot(s) might be
202 /// available.
203 bool canClobberPhysReg(unsigned PhysReg) const {
204 std::multimap<unsigned, int>::const_iterator I =
205 PhysRegsAvailable.lower_bound(PhysReg);
206 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
207 int SlotOrReMat = I->second;
208 I++;
209 if (!canClobberPhysRegForSS(SlotOrReMat))
210 return false;
211 }
212 return true;
213 }
214
215 /// disallowClobberPhysReg - Unset the CanClobber bit of the specified
216 /// stackslot register. The register is still available but is no longer
217 /// allowed to be modifed.
218 void disallowClobberPhysReg(unsigned PhysReg);
219
220 /// ClobberPhysReg - This is called when the specified physreg changes
221 /// value. We use this to invalidate any info about stuff that lives in
222 /// it and any of its aliases.
223 void ClobberPhysReg(unsigned PhysReg);
224
225 /// ModifyStackSlotOrReMat - This method is called when the value in a stack
226 /// slot changes. This removes information about which register the
227 /// previous value for this slot lives in (as the previous value is dead
228 /// now).
229 void ModifyStackSlotOrReMat(int SlotOrReMat);
230
231 /// AddAvailableRegsToLiveIn - Availability information is being kept coming
232 /// into the specified MBB. Add available physical registers as potential
233 /// live-in's. If they are reused in the MBB, they will be added to the
234 /// live-in set to make register scavenger and post-allocation scheduler.
235 void AddAvailableRegsToLiveIn(MachineBasicBlock &MBB, BitVector &RegKills,
236 std::vector<MachineOperand*> &KillOps);
237};
238
Dan Gohman7db949d2009-08-07 01:32:21 +0000239}
240
Lang Hames87e3bca2009-05-06 02:36:21 +0000241// ************************************************************************ //
242
David Greene2d4e6d32009-07-28 16:49:24 +0000243// Given a location where a reload of a spilled register or a remat of
244// a constant is to be inserted, attempt to find a safe location to
245// insert the load at an earlier point in the basic-block, to hide
246// latency of the load and to avoid address-generation interlock
247// issues.
248static MachineBasicBlock::iterator
249ComputeReloadLoc(MachineBasicBlock::iterator const InsertLoc,
250 MachineBasicBlock::iterator const Begin,
251 unsigned PhysReg,
252 const TargetRegisterInfo *TRI,
253 bool DoReMat,
254 int SSorRMId,
255 const TargetInstrInfo *TII,
256 const MachineFunction &MF)
257{
258 if (!ScheduleSpills)
259 return InsertLoc;
260
261 // Spill backscheduling is of primary interest to addresses, so
262 // don't do anything if the register isn't in the register class
263 // used for pointers.
264
265 const TargetLowering *TL = MF.getTarget().getTargetLowering();
266
267 if (!TL->isTypeLegal(TL->getPointerTy()))
268 // Believe it or not, this is true on PIC16.
269 return InsertLoc;
270
271 const TargetRegisterClass *ptrRegClass =
272 TL->getRegClassFor(TL->getPointerTy());
273 if (!ptrRegClass->contains(PhysReg))
274 return InsertLoc;
275
276 // Scan upwards through the preceding instructions. If an instruction doesn't
277 // reference the stack slot or the register we're loading, we can
278 // backschedule the reload up past it.
279 MachineBasicBlock::iterator NewInsertLoc = InsertLoc;
280 while (NewInsertLoc != Begin) {
281 MachineBasicBlock::iterator Prev = prior(NewInsertLoc);
282 for (unsigned i = 0; i < Prev->getNumOperands(); ++i) {
283 MachineOperand &Op = Prev->getOperand(i);
284 if (!DoReMat && Op.isFI() && Op.getIndex() == SSorRMId)
285 goto stop;
286 }
287 if (Prev->findRegisterUseOperandIdx(PhysReg) != -1 ||
288 Prev->findRegisterDefOperand(PhysReg))
289 goto stop;
290 for (const unsigned *Alias = TRI->getAliasSet(PhysReg); *Alias; ++Alias)
291 if (Prev->findRegisterUseOperandIdx(*Alias) != -1 ||
292 Prev->findRegisterDefOperand(*Alias))
293 goto stop;
294 NewInsertLoc = Prev;
295 }
296stop:;
297
298 // If we made it to the beginning of the block, turn around and move back
299 // down just past any existing reloads. They're likely to be reloads/remats
300 // for instructions earlier than what our current reload/remat is for, so
301 // they should be scheduled earlier.
302 if (NewInsertLoc == Begin) {
303 int FrameIdx;
304 while (InsertLoc != NewInsertLoc &&
305 (TII->isLoadFromStackSlot(NewInsertLoc, FrameIdx) ||
306 TII->isTriviallyReMaterializable(NewInsertLoc)))
307 ++NewInsertLoc;
308 }
309
310 return NewInsertLoc;
311}
Dan Gohman7db949d2009-08-07 01:32:21 +0000312
313namespace {
314
Lang Hames87e3bca2009-05-06 02:36:21 +0000315// ReusedOp - For each reused operand, we keep track of a bit of information,
316// in case we need to rollback upon processing a new operand. See comments
317// below.
318struct ReusedOp {
319 // The MachineInstr operand that reused an available value.
320 unsigned Operand;
321
322 // StackSlotOrReMat - The spill slot or remat id of the value being reused.
323 unsigned StackSlotOrReMat;
324
325 // PhysRegReused - The physical register the value was available in.
326 unsigned PhysRegReused;
327
328 // AssignedPhysReg - The physreg that was assigned for use by the reload.
329 unsigned AssignedPhysReg;
330
331 // VirtReg - The virtual register itself.
332 unsigned VirtReg;
333
334 ReusedOp(unsigned o, unsigned ss, unsigned prr, unsigned apr,
335 unsigned vreg)
336 : Operand(o), StackSlotOrReMat(ss), PhysRegReused(prr),
337 AssignedPhysReg(apr), VirtReg(vreg) {}
338};
339
340/// ReuseInfo - This maintains a collection of ReuseOp's for each operand that
341/// is reused instead of reloaded.
Nick Lewycky6726b6d2009-10-25 06:33:48 +0000342class ReuseInfo {
Lang Hames87e3bca2009-05-06 02:36:21 +0000343 MachineInstr &MI;
344 std::vector<ReusedOp> Reuses;
345 BitVector PhysRegsClobbered;
346public:
347 ReuseInfo(MachineInstr &mi, const TargetRegisterInfo *tri) : MI(mi) {
348 PhysRegsClobbered.resize(tri->getNumRegs());
349 }
350
351 bool hasReuses() const {
352 return !Reuses.empty();
353 }
354
355 /// addReuse - If we choose to reuse a virtual register that is already
356 /// available instead of reloading it, remember that we did so.
357 void addReuse(unsigned OpNo, unsigned StackSlotOrReMat,
358 unsigned PhysRegReused, unsigned AssignedPhysReg,
359 unsigned VirtReg) {
360 // If the reload is to the assigned register anyway, no undo will be
361 // required.
362 if (PhysRegReused == AssignedPhysReg) return;
363
364 // Otherwise, remember this.
365 Reuses.push_back(ReusedOp(OpNo, StackSlotOrReMat, PhysRegReused,
366 AssignedPhysReg, VirtReg));
367 }
368
369 void markClobbered(unsigned PhysReg) {
370 PhysRegsClobbered.set(PhysReg);
371 }
372
373 bool isClobbered(unsigned PhysReg) const {
374 return PhysRegsClobbered.test(PhysReg);
375 }
376
377 /// GetRegForReload - We are about to emit a reload into PhysReg. If there
378 /// is some other operand that is using the specified register, either pick
379 /// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000380 unsigned GetRegForReload(const TargetRegisterClass *RC, unsigned PhysReg,
381 MachineFunction &MF, MachineInstr *MI,
Lang Hames87e3bca2009-05-06 02:36:21 +0000382 AvailableSpills &Spills,
383 std::vector<MachineInstr*> &MaybeDeadStores,
384 SmallSet<unsigned, 8> &Rejected,
385 BitVector &RegKills,
386 std::vector<MachineOperand*> &KillOps,
387 VirtRegMap &VRM);
388
389 /// GetRegForReload - Helper for the above GetRegForReload(). Add a
390 /// 'Rejected' set to remember which registers have been considered and
391 /// rejected for the reload. This avoids infinite looping in case like
392 /// this:
393 /// t1 := op t2, t3
394 /// t2 <- assigned r0 for use by the reload but ended up reuse r1
395 /// t3 <- assigned r1 for use by the reload but ended up reuse r0
396 /// t1 <- desires r1
397 /// sees r1 is taken by t2, tries t2's reload register r0
398 /// sees r0 is taken by t3, tries t3's reload register r1
399 /// sees r1 is taken by t2, tries t2's reload register r0 ...
Evan Cheng5d885022009-07-21 09:15:00 +0000400 unsigned GetRegForReload(unsigned VirtReg, unsigned PhysReg, MachineInstr *MI,
Lang Hames87e3bca2009-05-06 02:36:21 +0000401 AvailableSpills &Spills,
402 std::vector<MachineInstr*> &MaybeDeadStores,
403 BitVector &RegKills,
404 std::vector<MachineOperand*> &KillOps,
405 VirtRegMap &VRM) {
406 SmallSet<unsigned, 8> Rejected;
Evan Cheng5d885022009-07-21 09:15:00 +0000407 MachineFunction &MF = *MI->getParent()->getParent();
408 const TargetRegisterClass* RC = MF.getRegInfo().getRegClass(VirtReg);
409 return GetRegForReload(RC, PhysReg, MF, MI, Spills, MaybeDeadStores,
410 Rejected, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +0000411 }
412};
413
Dan Gohman7db949d2009-08-07 01:32:21 +0000414}
Lang Hames87e3bca2009-05-06 02:36:21 +0000415
416// ****************** //
417// Utility Functions //
418// ****************** //
419
Lang Hames87e3bca2009-05-06 02:36:21 +0000420/// findSinglePredSuccessor - Return via reference a vector of machine basic
421/// blocks each of which is a successor of the specified BB and has no other
422/// predecessor.
423static void findSinglePredSuccessor(MachineBasicBlock *MBB,
424 SmallVectorImpl<MachineBasicBlock *> &Succs) {
425 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
426 SE = MBB->succ_end(); SI != SE; ++SI) {
427 MachineBasicBlock *SuccMBB = *SI;
428 if (SuccMBB->pred_size() == 1)
429 Succs.push_back(SuccMBB);
430 }
431}
432
Evan Cheng427a6b62009-05-15 06:48:19 +0000433/// InvalidateKill - Invalidate register kill information for a specific
434/// register. This also unsets the kills marker on the last kill operand.
435static void InvalidateKill(unsigned Reg,
436 const TargetRegisterInfo* TRI,
437 BitVector &RegKills,
438 std::vector<MachineOperand*> &KillOps) {
439 if (RegKills[Reg]) {
440 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000441 // KillOps[Reg] might be a def of a super-register.
442 unsigned KReg = KillOps[Reg]->getReg();
443 KillOps[KReg] = NULL;
444 RegKills.reset(KReg);
445 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
Evan Cheng427a6b62009-05-15 06:48:19 +0000446 if (RegKills[*SR]) {
447 KillOps[*SR]->setIsKill(false);
448 KillOps[*SR] = NULL;
449 RegKills.reset(*SR);
450 }
451 }
452 }
453}
454
Lang Hames87e3bca2009-05-06 02:36:21 +0000455/// InvalidateKills - MI is going to be deleted. If any of its operands are
456/// marked kill, then invalidate the information.
Evan Cheng427a6b62009-05-15 06:48:19 +0000457static void InvalidateKills(MachineInstr &MI,
458 const TargetRegisterInfo* TRI,
459 BitVector &RegKills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000460 std::vector<MachineOperand*> &KillOps,
461 SmallVector<unsigned, 2> *KillRegs = NULL) {
462 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
463 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000464 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000465 continue;
466 unsigned Reg = MO.getReg();
467 if (TargetRegisterInfo::isVirtualRegister(Reg))
468 continue;
469 if (KillRegs)
470 KillRegs->push_back(Reg);
471 assert(Reg < KillOps.size());
472 if (KillOps[Reg] == &MO) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000473 KillOps[Reg] = NULL;
Evan Cheng427a6b62009-05-15 06:48:19 +0000474 RegKills.reset(Reg);
475 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
476 if (RegKills[*SR]) {
477 KillOps[*SR] = NULL;
478 RegKills.reset(*SR);
479 }
480 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000481 }
482 }
483}
484
485/// InvalidateRegDef - If the def operand of the specified def MI is now dead
486/// (since it's spill instruction is removed), mark it isDead. Also checks if
487/// the def MI has other definition operands that are not dead. Returns it by
488/// reference.
489static bool InvalidateRegDef(MachineBasicBlock::iterator I,
490 MachineInstr &NewDef, unsigned Reg,
491 bool &HasLiveDef) {
492 // Due to remat, it's possible this reg isn't being reused. That is,
493 // the def of this reg (by prev MI) is now dead.
494 MachineInstr *DefMI = I;
495 MachineOperand *DefOp = NULL;
496 for (unsigned i = 0, e = DefMI->getNumOperands(); i != e; ++i) {
497 MachineOperand &MO = DefMI->getOperand(i);
Evan Chenga5dc45e2009-10-26 04:56:07 +0000498 if (!MO.isReg() || !MO.isUse() || !MO.isKill() || MO.isUndef())
Evan Cheng4784f1f2009-06-30 08:49:04 +0000499 continue;
500 if (MO.getReg() == Reg)
501 DefOp = &MO;
502 else if (!MO.isDead())
503 HasLiveDef = true;
Lang Hames87e3bca2009-05-06 02:36:21 +0000504 }
505 if (!DefOp)
506 return false;
507
508 bool FoundUse = false, Done = false;
509 MachineBasicBlock::iterator E = &NewDef;
510 ++I; ++E;
511 for (; !Done && I != E; ++I) {
512 MachineInstr *NMI = I;
513 for (unsigned j = 0, ee = NMI->getNumOperands(); j != ee; ++j) {
514 MachineOperand &MO = NMI->getOperand(j);
515 if (!MO.isReg() || MO.getReg() != Reg)
516 continue;
517 if (MO.isUse())
518 FoundUse = true;
519 Done = true; // Stop after scanning all the operands of this MI.
520 }
521 }
522 if (!FoundUse) {
523 // Def is dead!
524 DefOp->setIsDead();
525 return true;
526 }
527 return false;
528}
529
530/// UpdateKills - Track and update kill info. If a MI reads a register that is
531/// marked kill, then it must be due to register reuse. Transfer the kill info
532/// over.
Evan Cheng427a6b62009-05-15 06:48:19 +0000533static void UpdateKills(MachineInstr &MI, const TargetRegisterInfo* TRI,
534 BitVector &RegKills,
535 std::vector<MachineOperand*> &KillOps) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000536 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
537 MachineOperand &MO = MI.getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +0000538 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
Lang Hames87e3bca2009-05-06 02:36:21 +0000539 continue;
540 unsigned Reg = MO.getReg();
541 if (Reg == 0)
542 continue;
543
544 if (RegKills[Reg] && KillOps[Reg]->getParent() != &MI) {
545 // That can't be right. Register is killed but not re-defined and it's
546 // being reused. Let's fix that.
547 KillOps[Reg]->setIsKill(false);
Evan Cheng2c48fe62009-06-03 09:00:27 +0000548 // KillOps[Reg] might be a def of a super-register.
549 unsigned KReg = KillOps[Reg]->getReg();
550 KillOps[KReg] = NULL;
551 RegKills.reset(KReg);
552
553 // Must be a def of a super-register. Its other sub-regsters are no
554 // longer killed as well.
555 for (const unsigned *SR = TRI->getSubRegisters(KReg); *SR; ++SR) {
556 KillOps[*SR] = NULL;
557 RegKills.reset(*SR);
558 }
559
Lang Hames87e3bca2009-05-06 02:36:21 +0000560 if (!MI.isRegTiedToDefOperand(i))
561 // Unless it's a two-address operand, this is the new kill.
562 MO.setIsKill();
563 }
564 if (MO.isKill()) {
565 RegKills.set(Reg);
566 KillOps[Reg] = &MO;
Evan Cheng427a6b62009-05-15 06:48:19 +0000567 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
568 RegKills.set(*SR);
569 KillOps[*SR] = &MO;
570 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000571 }
572 }
573
574 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
575 const MachineOperand &MO = MI.getOperand(i);
576 if (!MO.isReg() || !MO.isDef())
577 continue;
578 unsigned Reg = MO.getReg();
579 RegKills.reset(Reg);
580 KillOps[Reg] = NULL;
581 // It also defines (or partially define) aliases.
Evan Cheng427a6b62009-05-15 06:48:19 +0000582 for (const unsigned *SR = TRI->getSubRegisters(Reg); *SR; ++SR) {
583 RegKills.reset(*SR);
584 KillOps[*SR] = NULL;
Lang Hames87e3bca2009-05-06 02:36:21 +0000585 }
Evan Cheng1f6a3c82009-11-13 23:16:41 +0000586 for (const unsigned *SR = TRI->getSuperRegisters(Reg); *SR; ++SR) {
587 RegKills.reset(*SR);
588 KillOps[*SR] = NULL;
589 }
Lang Hames87e3bca2009-05-06 02:36:21 +0000590 }
591}
592
593/// ReMaterialize - Re-materialize definition for Reg targetting DestReg.
594///
595static void ReMaterialize(MachineBasicBlock &MBB,
596 MachineBasicBlock::iterator &MII,
597 unsigned DestReg, unsigned Reg,
598 const TargetInstrInfo *TII,
599 const TargetRegisterInfo *TRI,
600 VirtRegMap &VRM) {
Evan Cheng5f159922009-07-16 20:15:00 +0000601 MachineInstr *ReMatDefMI = VRM.getReMaterializedMI(Reg);
Daniel Dunbar24cd3c42009-07-16 22:08:25 +0000602#ifndef NDEBUG
Evan Cheng5f159922009-07-16 20:15:00 +0000603 const TargetInstrDesc &TID = ReMatDefMI->getDesc();
Evan Chengc1b46f92009-07-17 00:32:06 +0000604 assert(TID.getNumDefs() == 1 &&
Evan Cheng5f159922009-07-16 20:15:00 +0000605 "Don't know how to remat instructions that define > 1 values!");
606#endif
607 TII->reMaterialize(MBB, MII, DestReg,
608 ReMatDefMI->getOperand(0).getSubReg(), ReMatDefMI);
Lang Hames87e3bca2009-05-06 02:36:21 +0000609 MachineInstr *NewMI = prior(MII);
610 for (unsigned i = 0, e = NewMI->getNumOperands(); i != e; ++i) {
611 MachineOperand &MO = NewMI->getOperand(i);
612 if (!MO.isReg() || MO.getReg() == 0)
613 continue;
614 unsigned VirtReg = MO.getReg();
615 if (TargetRegisterInfo::isPhysicalRegister(VirtReg))
616 continue;
617 assert(MO.isUse());
618 unsigned SubIdx = MO.getSubReg();
619 unsigned Phys = VRM.getPhys(VirtReg);
Evan Cheng427c3ba2009-10-25 07:51:47 +0000620 assert(Phys && "Virtual register is not assigned a register?");
Lang Hames87e3bca2009-05-06 02:36:21 +0000621 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
622 MO.setReg(RReg);
623 MO.setSubReg(0);
624 }
625 ++NumReMats;
626}
627
628/// findSuperReg - Find the SubReg's super-register of given register class
629/// where its SubIdx sub-register is SubReg.
630static unsigned findSuperReg(const TargetRegisterClass *RC, unsigned SubReg,
631 unsigned SubIdx, const TargetRegisterInfo *TRI) {
632 for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
633 I != E; ++I) {
634 unsigned Reg = *I;
635 if (TRI->getSubReg(Reg, SubIdx) == SubReg)
636 return Reg;
637 }
638 return 0;
639}
640
641// ******************************** //
642// Available Spills Implementation //
643// ******************************** //
644
645/// disallowClobberPhysRegOnly - Unset the CanClobber bit of the specified
646/// stackslot register. The register is still available but is no longer
647/// allowed to be modifed.
648void AvailableSpills::disallowClobberPhysRegOnly(unsigned PhysReg) {
649 std::multimap<unsigned, int>::iterator I =
650 PhysRegsAvailable.lower_bound(PhysReg);
651 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
652 int SlotOrReMat = I->second;
653 I++;
654 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
655 "Bidirectional map mismatch!");
656 SpillSlotsOrReMatsAvailable[SlotOrReMat] &= ~1;
Chris Lattner6456d382009-08-23 03:20:44 +0000657 DEBUG(errs() << "PhysReg " << TRI->getName(PhysReg)
658 << " copied, it is available for use but can no longer be modified\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000659 }
660}
661
662/// disallowClobberPhysReg - Unset the CanClobber bit of the specified
663/// stackslot register and its aliases. The register and its aliases may
664/// still available but is no longer allowed to be modifed.
665void AvailableSpills::disallowClobberPhysReg(unsigned PhysReg) {
666 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
667 disallowClobberPhysRegOnly(*AS);
668 disallowClobberPhysRegOnly(PhysReg);
669}
670
671/// ClobberPhysRegOnly - This is called when the specified physreg changes
672/// value. We use this to invalidate any info about stuff we thing lives in it.
673void AvailableSpills::ClobberPhysRegOnly(unsigned PhysReg) {
674 std::multimap<unsigned, int>::iterator I =
675 PhysRegsAvailable.lower_bound(PhysReg);
676 while (I != PhysRegsAvailable.end() && I->first == PhysReg) {
677 int SlotOrReMat = I->second;
678 PhysRegsAvailable.erase(I++);
679 assert((SpillSlotsOrReMatsAvailable[SlotOrReMat] >> 1) == PhysReg &&
680 "Bidirectional map mismatch!");
681 SpillSlotsOrReMatsAvailable.erase(SlotOrReMat);
Chris Lattner6456d382009-08-23 03:20:44 +0000682 DEBUG(errs() << "PhysReg " << TRI->getName(PhysReg)
683 << " clobbered, invalidating ");
Lang Hames87e3bca2009-05-06 02:36:21 +0000684 if (SlotOrReMat > VirtRegMap::MAX_STACK_SLOT)
Chris Lattner6456d382009-08-23 03:20:44 +0000685 DEBUG(errs() << "RM#" << SlotOrReMat-VirtRegMap::MAX_STACK_SLOT-1 <<"\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000686 else
Chris Lattner6456d382009-08-23 03:20:44 +0000687 DEBUG(errs() << "SS#" << SlotOrReMat << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000688 }
689}
690
691/// ClobberPhysReg - This is called when the specified physreg changes
692/// value. We use this to invalidate any info about stuff we thing lives in
693/// it and any of its aliases.
694void AvailableSpills::ClobberPhysReg(unsigned PhysReg) {
695 for (const unsigned *AS = TRI->getAliasSet(PhysReg); *AS; ++AS)
696 ClobberPhysRegOnly(*AS);
697 ClobberPhysRegOnly(PhysReg);
698}
699
700/// AddAvailableRegsToLiveIn - Availability information is being kept coming
701/// into the specified MBB. Add available physical registers as potential
702/// live-in's. If they are reused in the MBB, they will be added to the
703/// live-in set to make register scavenger and post-allocation scheduler.
704void AvailableSpills::AddAvailableRegsToLiveIn(MachineBasicBlock &MBB,
705 BitVector &RegKills,
706 std::vector<MachineOperand*> &KillOps) {
707 std::set<unsigned> NotAvailable;
708 for (std::multimap<unsigned, int>::iterator
709 I = PhysRegsAvailable.begin(), E = PhysRegsAvailable.end();
710 I != E; ++I) {
711 unsigned Reg = I->first;
712 const TargetRegisterClass* RC = TRI->getPhysicalRegisterRegClass(Reg);
713 // FIXME: A temporary workaround. We can't reuse available value if it's
714 // not safe to move the def of the virtual register's class. e.g.
715 // X86::RFP* register classes. Do not add it as a live-in.
716 if (!TII->isSafeToMoveRegClassDefs(RC))
717 // This is no longer available.
718 NotAvailable.insert(Reg);
719 else {
720 MBB.addLiveIn(Reg);
Evan Cheng427a6b62009-05-15 06:48:19 +0000721 InvalidateKill(Reg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +0000722 }
723
724 // Skip over the same register.
725 std::multimap<unsigned, int>::iterator NI = next(I);
726 while (NI != E && NI->first == Reg) {
727 ++I;
728 ++NI;
729 }
730 }
731
732 for (std::set<unsigned>::iterator I = NotAvailable.begin(),
733 E = NotAvailable.end(); I != E; ++I) {
734 ClobberPhysReg(*I);
735 for (const unsigned *SubRegs = TRI->getSubRegisters(*I);
736 *SubRegs; ++SubRegs)
737 ClobberPhysReg(*SubRegs);
738 }
739}
740
741/// ModifyStackSlotOrReMat - This method is called when the value in a stack
742/// slot changes. This removes information about which register the previous
743/// value for this slot lives in (as the previous value is dead now).
744void AvailableSpills::ModifyStackSlotOrReMat(int SlotOrReMat) {
745 std::map<int, unsigned>::iterator It =
746 SpillSlotsOrReMatsAvailable.find(SlotOrReMat);
747 if (It == SpillSlotsOrReMatsAvailable.end()) return;
748 unsigned Reg = It->second >> 1;
749 SpillSlotsOrReMatsAvailable.erase(It);
750
751 // This register may hold the value of multiple stack slots, only remove this
752 // stack slot from the set of values the register contains.
753 std::multimap<unsigned, int>::iterator I = PhysRegsAvailable.lower_bound(Reg);
754 for (; ; ++I) {
755 assert(I != PhysRegsAvailable.end() && I->first == Reg &&
756 "Map inverse broken!");
757 if (I->second == SlotOrReMat) break;
758 }
759 PhysRegsAvailable.erase(I);
760}
761
762// ************************** //
763// Reuse Info Implementation //
764// ************************** //
765
766/// GetRegForReload - We are about to emit a reload into PhysReg. If there
767/// is some other operand that is using the specified register, either pick
768/// a new register to use, or evict the previous reload and use this reg.
Evan Cheng5d885022009-07-21 09:15:00 +0000769unsigned ReuseInfo::GetRegForReload(const TargetRegisterClass *RC,
770 unsigned PhysReg,
771 MachineFunction &MF,
772 MachineInstr *MI, AvailableSpills &Spills,
Lang Hames87e3bca2009-05-06 02:36:21 +0000773 std::vector<MachineInstr*> &MaybeDeadStores,
774 SmallSet<unsigned, 8> &Rejected,
775 BitVector &RegKills,
776 std::vector<MachineOperand*> &KillOps,
777 VirtRegMap &VRM) {
Evan Cheng5d885022009-07-21 09:15:00 +0000778 const TargetInstrInfo* TII = MF.getTarget().getInstrInfo();
779 const TargetRegisterInfo *TRI = Spills.getRegInfo();
Lang Hames87e3bca2009-05-06 02:36:21 +0000780
781 if (Reuses.empty()) return PhysReg; // This is most often empty.
782
783 for (unsigned ro = 0, e = Reuses.size(); ro != e; ++ro) {
784 ReusedOp &Op = Reuses[ro];
785 // If we find some other reuse that was supposed to use this register
786 // exactly for its reload, we can change this reload to use ITS reload
787 // register. That is, unless its reload register has already been
788 // considered and subsequently rejected because it has also been reused
789 // by another operand.
790 if (Op.PhysRegReused == PhysReg &&
Evan Cheng5d885022009-07-21 09:15:00 +0000791 Rejected.count(Op.AssignedPhysReg) == 0 &&
792 RC->contains(Op.AssignedPhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000793 // Yup, use the reload register that we didn't use before.
794 unsigned NewReg = Op.AssignedPhysReg;
795 Rejected.insert(PhysReg);
Evan Cheng5d885022009-07-21 09:15:00 +0000796 return GetRegForReload(RC, NewReg, MF, MI, Spills, MaybeDeadStores, Rejected,
Lang Hames87e3bca2009-05-06 02:36:21 +0000797 RegKills, KillOps, VRM);
798 } else {
799 // Otherwise, we might also have a problem if a previously reused
Evan Cheng5d885022009-07-21 09:15:00 +0000800 // value aliases the new register. If so, codegen the previous reload
Lang Hames87e3bca2009-05-06 02:36:21 +0000801 // and use this one.
802 unsigned PRRU = Op.PhysRegReused;
Lang Hames3f2f3f52009-09-03 02:52:02 +0000803 if (TRI->regsOverlap(PRRU, PhysReg)) {
Lang Hames87e3bca2009-05-06 02:36:21 +0000804 // Okay, we found out that an alias of a reused register
805 // was used. This isn't good because it means we have
806 // to undo a previous reuse.
807 MachineBasicBlock *MBB = MI->getParent();
808 const TargetRegisterClass *AliasRC =
809 MBB->getParent()->getRegInfo().getRegClass(Op.VirtReg);
810
811 // Copy Op out of the vector and remove it, we're going to insert an
812 // explicit load for it.
813 ReusedOp NewOp = Op;
814 Reuses.erase(Reuses.begin()+ro);
815
Jakob Stoklund Olesen46ff9692009-08-23 13:01:45 +0000816 // MI may be using only a sub-register of PhysRegUsed.
817 unsigned RealPhysRegUsed = MI->getOperand(NewOp.Operand).getReg();
818 unsigned SubIdx = 0;
819 assert(TargetRegisterInfo::isPhysicalRegister(RealPhysRegUsed) &&
820 "A reuse cannot be a virtual register");
821 if (PRRU != RealPhysRegUsed) {
822 // What was the sub-register index?
823 unsigned SubReg;
824 for (SubIdx = 1; (SubReg = TRI->getSubReg(PRRU, SubIdx)); SubIdx++)
825 if (SubReg == RealPhysRegUsed)
826 break;
827 assert(SubReg == RealPhysRegUsed &&
828 "Operand physreg is not a sub-register of PhysRegUsed");
829 }
830
Lang Hames87e3bca2009-05-06 02:36:21 +0000831 // Ok, we're going to try to reload the assigned physreg into the
832 // slot that we were supposed to in the first place. However, that
833 // register could hold a reuse. Check to see if it conflicts or
834 // would prefer us to use a different register.
Evan Cheng5d885022009-07-21 09:15:00 +0000835 unsigned NewPhysReg = GetRegForReload(RC, NewOp.AssignedPhysReg,
836 MF, MI, Spills, MaybeDeadStores,
837 Rejected, RegKills, KillOps, VRM);
David Greene2d4e6d32009-07-28 16:49:24 +0000838
839 bool DoReMat = NewOp.StackSlotOrReMat > VirtRegMap::MAX_STACK_SLOT;
840 int SSorRMId = DoReMat
841 ? VRM.getReMatId(NewOp.VirtReg) : NewOp.StackSlotOrReMat;
842
843 // Back-schedule reloads and remats.
844 MachineBasicBlock::iterator InsertLoc =
845 ComputeReloadLoc(MI, MBB->begin(), PhysReg, TRI,
846 DoReMat, SSorRMId, TII, MF);
847
848 if (DoReMat) {
849 ReMaterialize(*MBB, InsertLoc, NewPhysReg, NewOp.VirtReg, TII,
850 TRI, VRM);
851 } else {
852 TII->loadRegFromStackSlot(*MBB, InsertLoc, NewPhysReg,
Lang Hames87e3bca2009-05-06 02:36:21 +0000853 NewOp.StackSlotOrReMat, AliasRC);
David Greene2d4e6d32009-07-28 16:49:24 +0000854 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +0000855 VRM.addSpillSlotUse(NewOp.StackSlotOrReMat, LoadMI);
856 // Any stores to this stack slot are not dead anymore.
857 MaybeDeadStores[NewOp.StackSlotOrReMat] = NULL;
858 ++NumLoads;
859 }
860 Spills.ClobberPhysReg(NewPhysReg);
861 Spills.ClobberPhysReg(NewOp.PhysRegReused);
862
Evan Cheng427c3ba2009-10-25 07:51:47 +0000863 unsigned RReg = SubIdx ? TRI->getSubReg(NewPhysReg, SubIdx) :NewPhysReg;
Lang Hames87e3bca2009-05-06 02:36:21 +0000864 MI->getOperand(NewOp.Operand).setReg(RReg);
865 MI->getOperand(NewOp.Operand).setSubReg(0);
866
867 Spills.addAvailable(NewOp.StackSlotOrReMat, NewPhysReg);
David Greene2d4e6d32009-07-28 16:49:24 +0000868 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
Chris Lattner6456d382009-08-23 03:20:44 +0000869 DEBUG(errs() << '\t' << *prior(InsertLoc));
Lang Hames87e3bca2009-05-06 02:36:21 +0000870
Chris Lattner6456d382009-08-23 03:20:44 +0000871 DEBUG(errs() << "Reuse undone!\n");
Lang Hames87e3bca2009-05-06 02:36:21 +0000872 --NumReused;
873
874 // Finally, PhysReg is now available, go ahead and use it.
875 return PhysReg;
876 }
877 }
878 }
879 return PhysReg;
880}
881
882// ************************************************************************ //
883
884/// FoldsStackSlotModRef - Return true if the specified MI folds the specified
885/// stack slot mod/ref. It also checks if it's possible to unfold the
886/// instruction by having it define a specified physical register instead.
887static bool FoldsStackSlotModRef(MachineInstr &MI, int SS, unsigned PhysReg,
888 const TargetInstrInfo *TII,
889 const TargetRegisterInfo *TRI,
890 VirtRegMap &VRM) {
891 if (VRM.hasEmergencySpills(&MI) || VRM.isSpillPt(&MI))
892 return false;
893
894 bool Found = false;
895 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
896 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ++I) {
897 unsigned VirtReg = I->second.first;
898 VirtRegMap::ModRef MR = I->second.second;
899 if (MR & VirtRegMap::isModRef)
900 if (VRM.getStackSlot(VirtReg) == SS) {
901 Found= TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(), true, true) != 0;
902 break;
903 }
904 }
905 if (!Found)
906 return false;
907
908 // Does the instruction uses a register that overlaps the scratch register?
909 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
910 MachineOperand &MO = MI.getOperand(i);
911 if (!MO.isReg() || MO.getReg() == 0)
912 continue;
913 unsigned Reg = MO.getReg();
914 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
915 if (!VRM.hasPhys(Reg))
916 continue;
917 Reg = VRM.getPhys(Reg);
918 }
919 if (TRI->regsOverlap(PhysReg, Reg))
920 return false;
921 }
922 return true;
923}
924
925/// FindFreeRegister - Find a free register of a given register class by looking
926/// at (at most) the last two machine instructions.
927static unsigned FindFreeRegister(MachineBasicBlock::iterator MII,
928 MachineBasicBlock &MBB,
929 const TargetRegisterClass *RC,
930 const TargetRegisterInfo *TRI,
931 BitVector &AllocatableRegs) {
932 BitVector Defs(TRI->getNumRegs());
933 BitVector Uses(TRI->getNumRegs());
934 SmallVector<unsigned, 4> LocalUses;
935 SmallVector<unsigned, 4> Kills;
936
937 // Take a look at 2 instructions at most.
938 for (unsigned Count = 0; Count < 2; ++Count) {
939 if (MII == MBB.begin())
940 break;
941 MachineInstr *PrevMI = prior(MII);
942 for (unsigned i = 0, e = PrevMI->getNumOperands(); i != e; ++i) {
943 MachineOperand &MO = PrevMI->getOperand(i);
944 if (!MO.isReg() || MO.getReg() == 0)
945 continue;
946 unsigned Reg = MO.getReg();
947 if (MO.isDef()) {
948 Defs.set(Reg);
949 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
950 Defs.set(*AS);
951 } else {
952 LocalUses.push_back(Reg);
953 if (MO.isKill() && AllocatableRegs[Reg])
954 Kills.push_back(Reg);
955 }
956 }
957
958 for (unsigned i = 0, e = Kills.size(); i != e; ++i) {
959 unsigned Kill = Kills[i];
960 if (!Defs[Kill] && !Uses[Kill] &&
961 TRI->getPhysicalRegisterRegClass(Kill) == RC)
962 return Kill;
963 }
964 for (unsigned i = 0, e = LocalUses.size(); i != e; ++i) {
965 unsigned Reg = LocalUses[i];
966 Uses.set(Reg);
967 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
968 Uses.set(*AS);
969 }
970
971 MII = PrevMI;
972 }
973
974 return 0;
975}
976
977static
978void AssignPhysToVirtReg(MachineInstr *MI, unsigned VirtReg, unsigned PhysReg) {
979 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
980 MachineOperand &MO = MI->getOperand(i);
981 if (MO.isReg() && MO.getReg() == VirtReg)
982 MO.setReg(PhysReg);
983 }
984}
985
Evan Chengeca24fb2009-05-12 23:07:00 +0000986namespace {
987 struct RefSorter {
988 bool operator()(const std::pair<MachineInstr*, int> &A,
989 const std::pair<MachineInstr*, int> &B) {
990 return A.second < B.second;
991 }
992 };
993}
Lang Hames87e3bca2009-05-06 02:36:21 +0000994
995// ***************************** //
996// Local Spiller Implementation //
997// ***************************** //
998
Dan Gohman7db949d2009-08-07 01:32:21 +0000999namespace {
1000
Nick Lewycky6726b6d2009-10-25 06:33:48 +00001001class LocalRewriter : public VirtRegRewriter {
Lang Hames87e3bca2009-05-06 02:36:21 +00001002 MachineRegisterInfo *RegInfo;
1003 const TargetRegisterInfo *TRI;
1004 const TargetInstrInfo *TII;
1005 BitVector AllocatableRegs;
1006 DenseMap<MachineInstr*, unsigned> DistanceMap;
1007public:
1008
1009 bool runOnMachineFunction(MachineFunction &MF, VirtRegMap &VRM,
1010 LiveIntervals* LIs) {
1011 RegInfo = &MF.getRegInfo();
1012 TRI = MF.getTarget().getRegisterInfo();
1013 TII = MF.getTarget().getInstrInfo();
1014 AllocatableRegs = TRI->getAllocatableSet(MF);
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001015 DEBUG(errs() << "\n**** Local spiller rewriting function '"
1016 << MF.getFunction()->getName() << "':\n");
Chris Lattner6456d382009-08-23 03:20:44 +00001017 DEBUG(errs() << "**** Machine Instrs (NOTE! Does not include spills and"
1018 " reloads!) ****\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001019 DEBUG(MF.dump());
1020
1021 // Spills - Keep track of which spilled values are available in physregs
1022 // so that we can choose to reuse the physregs instead of emitting
1023 // reloads. This is usually refreshed per basic block.
1024 AvailableSpills Spills(TRI, TII);
1025
1026 // Keep track of kill information.
1027 BitVector RegKills(TRI->getNumRegs());
1028 std::vector<MachineOperand*> KillOps;
1029 KillOps.resize(TRI->getNumRegs(), NULL);
1030
1031 // SingleEntrySuccs - Successor blocks which have a single predecessor.
1032 SmallVector<MachineBasicBlock*, 4> SinglePredSuccs;
1033 SmallPtrSet<MachineBasicBlock*,16> EarlyVisited;
1034
1035 // Traverse the basic blocks depth first.
1036 MachineBasicBlock *Entry = MF.begin();
1037 SmallPtrSet<MachineBasicBlock*,16> Visited;
1038 for (df_ext_iterator<MachineBasicBlock*,
1039 SmallPtrSet<MachineBasicBlock*,16> >
1040 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1041 DFI != E; ++DFI) {
1042 MachineBasicBlock *MBB = *DFI;
1043 if (!EarlyVisited.count(MBB))
1044 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1045
1046 // If this MBB is the only predecessor of a successor. Keep the
1047 // availability information and visit it next.
1048 do {
1049 // Keep visiting single predecessor successor as long as possible.
1050 SinglePredSuccs.clear();
1051 findSinglePredSuccessor(MBB, SinglePredSuccs);
1052 if (SinglePredSuccs.empty())
1053 MBB = 0;
1054 else {
1055 // FIXME: More than one successors, each of which has MBB has
1056 // the only predecessor.
1057 MBB = SinglePredSuccs[0];
1058 if (!Visited.count(MBB) && EarlyVisited.insert(MBB)) {
1059 Spills.AddAvailableRegsToLiveIn(*MBB, RegKills, KillOps);
1060 RewriteMBB(*MBB, VRM, LIs, Spills, RegKills, KillOps);
1061 }
1062 }
1063 } while (MBB);
1064
1065 // Clear the availability info.
1066 Spills.clear();
1067 }
1068
Chris Lattner6456d382009-08-23 03:20:44 +00001069 DEBUG(errs() << "**** Post Machine Instrs ****\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001070 DEBUG(MF.dump());
1071
1072 // Mark unused spill slots.
1073 MachineFrameInfo *MFI = MF.getFrameInfo();
1074 int SS = VRM.getLowSpillSlot();
1075 if (SS != VirtRegMap::NO_STACK_SLOT)
1076 for (int e = VRM.getHighSpillSlot(); SS <= e; ++SS)
1077 if (!VRM.isSpillSlotUsed(SS)) {
1078 MFI->RemoveStackObject(SS);
1079 ++NumDSS;
1080 }
1081
1082 return true;
1083 }
1084
1085private:
1086
1087 /// OptimizeByUnfold2 - Unfold a series of load / store folding instructions if
1088 /// a scratch register is available.
1089 /// xorq %r12<kill>, %r13
1090 /// addq %rax, -184(%rbp)
1091 /// addq %r13, -184(%rbp)
1092 /// ==>
1093 /// xorq %r12<kill>, %r13
1094 /// movq -184(%rbp), %r12
1095 /// addq %rax, %r12
1096 /// addq %r13, %r12
1097 /// movq %r12, -184(%rbp)
1098 bool OptimizeByUnfold2(unsigned VirtReg, int SS,
1099 MachineBasicBlock &MBB,
1100 MachineBasicBlock::iterator &MII,
1101 std::vector<MachineInstr*> &MaybeDeadStores,
1102 AvailableSpills &Spills,
1103 BitVector &RegKills,
1104 std::vector<MachineOperand*> &KillOps,
1105 VirtRegMap &VRM) {
1106
1107 MachineBasicBlock::iterator NextMII = next(MII);
1108 if (NextMII == MBB.end())
1109 return false;
1110
1111 if (TII->getOpcodeAfterMemoryUnfold(MII->getOpcode(), true, true) == 0)
1112 return false;
1113
1114 // Now let's see if the last couple of instructions happens to have freed up
1115 // a register.
1116 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1117 unsigned PhysReg = FindFreeRegister(MII, MBB, RC, TRI, AllocatableRegs);
1118 if (!PhysReg)
1119 return false;
1120
1121 MachineFunction &MF = *MBB.getParent();
1122 TRI = MF.getTarget().getRegisterInfo();
1123 MachineInstr &MI = *MII;
1124 if (!FoldsStackSlotModRef(MI, SS, PhysReg, TII, TRI, VRM))
1125 return false;
1126
1127 // If the next instruction also folds the same SS modref and can be unfoled,
1128 // then it's worthwhile to issue a load from SS into the free register and
1129 // then unfold these instructions.
1130 if (!FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM))
1131 return false;
1132
David Greene2d4e6d32009-07-28 16:49:24 +00001133 // Back-schedule reloads and remats.
Duncan Sandsb7c5bdf2009-09-06 08:33:48 +00001134 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, false, SS, TII, MF);
David Greene2d4e6d32009-07-28 16:49:24 +00001135
Lang Hames87e3bca2009-05-06 02:36:21 +00001136 // Load from SS to the spare physical register.
1137 TII->loadRegFromStackSlot(MBB, MII, PhysReg, SS, RC);
1138 // This invalidates Phys.
1139 Spills.ClobberPhysReg(PhysReg);
1140 // Remember it's available.
1141 Spills.addAvailable(SS, PhysReg);
1142 MaybeDeadStores[SS] = NULL;
1143
1144 // Unfold current MI.
1145 SmallVector<MachineInstr*, 4> NewMIs;
1146 if (!TII->unfoldMemoryOperand(MF, &MI, VirtReg, false, false, NewMIs))
Torok Edwinc23197a2009-07-14 16:55:14 +00001147 llvm_unreachable("Unable unfold the load / store folding instruction!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001148 assert(NewMIs.size() == 1);
1149 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1150 VRM.transferRestorePts(&MI, NewMIs[0]);
1151 MII = MBB.insert(MII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00001152 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001153 VRM.RemoveMachineInstrFromMaps(&MI);
1154 MBB.erase(&MI);
1155 ++NumModRefUnfold;
1156
1157 // Unfold next instructions that fold the same SS.
1158 do {
1159 MachineInstr &NextMI = *NextMII;
1160 NextMII = next(NextMII);
1161 NewMIs.clear();
1162 if (!TII->unfoldMemoryOperand(MF, &NextMI, VirtReg, false, false, NewMIs))
Torok Edwinc23197a2009-07-14 16:55:14 +00001163 llvm_unreachable("Unable unfold the load / store folding instruction!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001164 assert(NewMIs.size() == 1);
1165 AssignPhysToVirtReg(NewMIs[0], VirtReg, PhysReg);
1166 VRM.transferRestorePts(&NextMI, NewMIs[0]);
1167 MBB.insert(NextMII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00001168 InvalidateKills(NextMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001169 VRM.RemoveMachineInstrFromMaps(&NextMI);
1170 MBB.erase(&NextMI);
1171 ++NumModRefUnfold;
Evan Cheng2c48fe62009-06-03 09:00:27 +00001172 if (NextMII == MBB.end())
1173 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001174 } while (FoldsStackSlotModRef(*NextMII, SS, PhysReg, TII, TRI, VRM));
1175
1176 // Store the value back into SS.
1177 TII->storeRegToStackSlot(MBB, NextMII, PhysReg, true, SS, RC);
1178 MachineInstr *StoreMI = prior(NextMII);
1179 VRM.addSpillSlotUse(SS, StoreMI);
1180 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1181
1182 return true;
1183 }
1184
1185 /// OptimizeByUnfold - Turn a store folding instruction into a load folding
1186 /// instruction. e.g.
1187 /// xorl %edi, %eax
1188 /// movl %eax, -32(%ebp)
1189 /// movl -36(%ebp), %eax
1190 /// orl %eax, -32(%ebp)
1191 /// ==>
1192 /// xorl %edi, %eax
1193 /// orl -36(%ebp), %eax
1194 /// mov %eax, -32(%ebp)
1195 /// This enables unfolding optimization for a subsequent instruction which will
1196 /// also eliminate the newly introduced store instruction.
1197 bool OptimizeByUnfold(MachineBasicBlock &MBB,
1198 MachineBasicBlock::iterator &MII,
1199 std::vector<MachineInstr*> &MaybeDeadStores,
1200 AvailableSpills &Spills,
1201 BitVector &RegKills,
1202 std::vector<MachineOperand*> &KillOps,
1203 VirtRegMap &VRM) {
1204 MachineFunction &MF = *MBB.getParent();
1205 MachineInstr &MI = *MII;
1206 unsigned UnfoldedOpc = 0;
1207 unsigned UnfoldPR = 0;
1208 unsigned UnfoldVR = 0;
1209 int FoldedSS = VirtRegMap::NO_STACK_SLOT;
1210 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1211 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
1212 // Only transform a MI that folds a single register.
1213 if (UnfoldedOpc)
1214 return false;
1215 UnfoldVR = I->second.first;
1216 VirtRegMap::ModRef MR = I->second.second;
1217 // MI2VirtMap be can updated which invalidate the iterator.
1218 // Increment the iterator first.
1219 ++I;
1220 if (VRM.isAssignedReg(UnfoldVR))
1221 continue;
1222 // If this reference is not a use, any previous store is now dead.
1223 // Otherwise, the store to this stack slot is not dead anymore.
1224 FoldedSS = VRM.getStackSlot(UnfoldVR);
1225 MachineInstr* DeadStore = MaybeDeadStores[FoldedSS];
1226 if (DeadStore && (MR & VirtRegMap::isModRef)) {
1227 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(FoldedSS);
1228 if (!PhysReg || !DeadStore->readsRegister(PhysReg))
1229 continue;
1230 UnfoldPR = PhysReg;
1231 UnfoldedOpc = TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1232 false, true);
1233 }
1234 }
1235
1236 if (!UnfoldedOpc) {
1237 if (!UnfoldVR)
1238 return false;
1239
1240 // Look for other unfolding opportunities.
1241 return OptimizeByUnfold2(UnfoldVR, FoldedSS, MBB, MII,
1242 MaybeDeadStores, Spills, RegKills, KillOps, VRM);
1243 }
1244
1245 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1246 MachineOperand &MO = MI.getOperand(i);
1247 if (!MO.isReg() || MO.getReg() == 0 || !MO.isUse())
1248 continue;
1249 unsigned VirtReg = MO.getReg();
1250 if (TargetRegisterInfo::isPhysicalRegister(VirtReg) || MO.getSubReg())
1251 continue;
1252 if (VRM.isAssignedReg(VirtReg)) {
1253 unsigned PhysReg = VRM.getPhys(VirtReg);
1254 if (PhysReg && TRI->regsOverlap(PhysReg, UnfoldPR))
1255 return false;
1256 } else if (VRM.isReMaterialized(VirtReg))
1257 continue;
1258 int SS = VRM.getStackSlot(VirtReg);
1259 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
1260 if (PhysReg) {
1261 if (TRI->regsOverlap(PhysReg, UnfoldPR))
1262 return false;
1263 continue;
1264 }
1265 if (VRM.hasPhys(VirtReg)) {
1266 PhysReg = VRM.getPhys(VirtReg);
1267 if (!TRI->regsOverlap(PhysReg, UnfoldPR))
1268 continue;
1269 }
1270
1271 // Ok, we'll need to reload the value into a register which makes
1272 // it impossible to perform the store unfolding optimization later.
1273 // Let's see if it is possible to fold the load if the store is
1274 // unfolded. This allows us to perform the store unfolding
1275 // optimization.
1276 SmallVector<MachineInstr*, 4> NewMIs;
1277 if (TII->unfoldMemoryOperand(MF, &MI, UnfoldVR, false, false, NewMIs)) {
1278 assert(NewMIs.size() == 1);
1279 MachineInstr *NewMI = NewMIs.back();
1280 NewMIs.clear();
1281 int Idx = NewMI->findRegisterUseOperandIdx(VirtReg, false);
1282 assert(Idx != -1);
1283 SmallVector<unsigned, 1> Ops;
1284 Ops.push_back(Idx);
1285 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, NewMI, Ops, SS);
1286 if (FoldedMI) {
1287 VRM.addSpillSlotUse(SS, FoldedMI);
1288 if (!VRM.hasPhys(UnfoldVR))
1289 VRM.assignVirt2Phys(UnfoldVR, UnfoldPR);
1290 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1291 MII = MBB.insert(MII, FoldedMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001292 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001293 VRM.RemoveMachineInstrFromMaps(&MI);
1294 MBB.erase(&MI);
1295 MF.DeleteMachineInstr(NewMI);
1296 return true;
1297 }
1298 MF.DeleteMachineInstr(NewMI);
1299 }
1300 }
1301
1302 return false;
1303 }
1304
Evan Cheng261ce1d2009-07-10 19:15:51 +00001305 /// CommuteChangesDestination - We are looking for r0 = op r1, r2 and
1306 /// where SrcReg is r1 and it is tied to r0. Return true if after
1307 /// commuting this instruction it will be r0 = op r2, r1.
1308 static bool CommuteChangesDestination(MachineInstr *DefMI,
1309 const TargetInstrDesc &TID,
1310 unsigned SrcReg,
1311 const TargetInstrInfo *TII,
1312 unsigned &DstIdx) {
1313 if (TID.getNumDefs() != 1 && TID.getNumOperands() != 3)
1314 return false;
1315 if (!DefMI->getOperand(1).isReg() ||
1316 DefMI->getOperand(1).getReg() != SrcReg)
1317 return false;
1318 unsigned DefIdx;
1319 if (!DefMI->isRegTiedToDefOperand(1, &DefIdx) || DefIdx != 0)
1320 return false;
1321 unsigned SrcIdx1, SrcIdx2;
1322 if (!TII->findCommutedOpIndices(DefMI, SrcIdx1, SrcIdx2))
1323 return false;
1324 if (SrcIdx1 == 1 && SrcIdx2 == 2) {
1325 DstIdx = 2;
1326 return true;
1327 }
1328 return false;
1329 }
1330
Lang Hames87e3bca2009-05-06 02:36:21 +00001331 /// CommuteToFoldReload -
1332 /// Look for
1333 /// r1 = load fi#1
1334 /// r1 = op r1, r2<kill>
1335 /// store r1, fi#1
1336 ///
1337 /// If op is commutable and r2 is killed, then we can xform these to
1338 /// r2 = op r2, fi#1
1339 /// store r2, fi#1
1340 bool CommuteToFoldReload(MachineBasicBlock &MBB,
1341 MachineBasicBlock::iterator &MII,
1342 unsigned VirtReg, unsigned SrcReg, int SS,
1343 AvailableSpills &Spills,
1344 BitVector &RegKills,
1345 std::vector<MachineOperand*> &KillOps,
1346 const TargetRegisterInfo *TRI,
1347 VirtRegMap &VRM) {
1348 if (MII == MBB.begin() || !MII->killsRegister(SrcReg))
1349 return false;
1350
1351 MachineFunction &MF = *MBB.getParent();
1352 MachineInstr &MI = *MII;
1353 MachineBasicBlock::iterator DefMII = prior(MII);
1354 MachineInstr *DefMI = DefMII;
1355 const TargetInstrDesc &TID = DefMI->getDesc();
1356 unsigned NewDstIdx;
1357 if (DefMII != MBB.begin() &&
1358 TID.isCommutable() &&
Evan Cheng261ce1d2009-07-10 19:15:51 +00001359 CommuteChangesDestination(DefMI, TID, SrcReg, TII, NewDstIdx)) {
Lang Hames87e3bca2009-05-06 02:36:21 +00001360 MachineOperand &NewDstMO = DefMI->getOperand(NewDstIdx);
1361 unsigned NewReg = NewDstMO.getReg();
1362 if (!NewDstMO.isKill() || TRI->regsOverlap(NewReg, SrcReg))
1363 return false;
1364 MachineInstr *ReloadMI = prior(DefMII);
1365 int FrameIdx;
1366 unsigned DestReg = TII->isLoadFromStackSlot(ReloadMI, FrameIdx);
1367 if (DestReg != SrcReg || FrameIdx != SS)
1368 return false;
1369 int UseIdx = DefMI->findRegisterUseOperandIdx(DestReg, false);
1370 if (UseIdx == -1)
1371 return false;
1372 unsigned DefIdx;
1373 if (!MI.isRegTiedToDefOperand(UseIdx, &DefIdx))
1374 return false;
1375 assert(DefMI->getOperand(DefIdx).isReg() &&
1376 DefMI->getOperand(DefIdx).getReg() == SrcReg);
1377
1378 // Now commute def instruction.
1379 MachineInstr *CommutedMI = TII->commuteInstruction(DefMI, true);
1380 if (!CommutedMI)
1381 return false;
1382 SmallVector<unsigned, 1> Ops;
1383 Ops.push_back(NewDstIdx);
1384 MachineInstr *FoldedMI = TII->foldMemoryOperand(MF, CommutedMI, Ops, SS);
1385 // Not needed since foldMemoryOperand returns new MI.
1386 MF.DeleteMachineInstr(CommutedMI);
1387 if (!FoldedMI)
1388 return false;
1389
1390 VRM.addSpillSlotUse(SS, FoldedMI);
1391 VRM.virtFolded(VirtReg, FoldedMI, VirtRegMap::isRef);
1392 // Insert new def MI and spill MI.
1393 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1394 TII->storeRegToStackSlot(MBB, &MI, NewReg, true, SS, RC);
1395 MII = prior(MII);
1396 MachineInstr *StoreMI = MII;
1397 VRM.addSpillSlotUse(SS, StoreMI);
1398 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1399 MII = MBB.insert(MII, FoldedMI); // Update MII to backtrack.
1400
1401 // Delete all 3 old instructions.
Evan Cheng427a6b62009-05-15 06:48:19 +00001402 InvalidateKills(*ReloadMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001403 VRM.RemoveMachineInstrFromMaps(ReloadMI);
1404 MBB.erase(ReloadMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001405 InvalidateKills(*DefMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001406 VRM.RemoveMachineInstrFromMaps(DefMI);
1407 MBB.erase(DefMI);
Evan Cheng427a6b62009-05-15 06:48:19 +00001408 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001409 VRM.RemoveMachineInstrFromMaps(&MI);
1410 MBB.erase(&MI);
1411
1412 // If NewReg was previously holding value of some SS, it's now clobbered.
1413 // This has to be done now because it's a physical register. When this
1414 // instruction is re-visited, it's ignored.
1415 Spills.ClobberPhysReg(NewReg);
1416
1417 ++NumCommutes;
1418 return true;
1419 }
1420
1421 return false;
1422 }
1423
1424 /// SpillRegToStackSlot - Spill a register to a specified stack slot. Check if
1425 /// the last store to the same slot is now dead. If so, remove the last store.
1426 void SpillRegToStackSlot(MachineBasicBlock &MBB,
1427 MachineBasicBlock::iterator &MII,
1428 int Idx, unsigned PhysReg, int StackSlot,
1429 const TargetRegisterClass *RC,
1430 bool isAvailable, MachineInstr *&LastStore,
1431 AvailableSpills &Spills,
1432 SmallSet<MachineInstr*, 4> &ReMatDefs,
1433 BitVector &RegKills,
1434 std::vector<MachineOperand*> &KillOps,
1435 VirtRegMap &VRM) {
1436
Dale Johannesene841d2f2009-10-28 21:56:18 +00001437 MachineBasicBlock::iterator oldNextMII = next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001438 TII->storeRegToStackSlot(MBB, next(MII), PhysReg, true, StackSlot, RC);
Dale Johannesen78c5cda2009-10-29 01:15:40 +00001439 MachineInstr *StoreMI = prior(oldNextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001440 VRM.addSpillSlotUse(StackSlot, StoreMI);
Chris Lattner6456d382009-08-23 03:20:44 +00001441 DEBUG(errs() << "Store:\t" << *StoreMI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001442
1443 // If there is a dead store to this stack slot, nuke it now.
1444 if (LastStore) {
Chris Lattner6456d382009-08-23 03:20:44 +00001445 DEBUG(errs() << "Removed dead store:\t" << *LastStore);
Lang Hames87e3bca2009-05-06 02:36:21 +00001446 ++NumDSE;
1447 SmallVector<unsigned, 2> KillRegs;
Evan Cheng427a6b62009-05-15 06:48:19 +00001448 InvalidateKills(*LastStore, TRI, RegKills, KillOps, &KillRegs);
Lang Hames87e3bca2009-05-06 02:36:21 +00001449 MachineBasicBlock::iterator PrevMII = LastStore;
1450 bool CheckDef = PrevMII != MBB.begin();
1451 if (CheckDef)
1452 --PrevMII;
1453 VRM.RemoveMachineInstrFromMaps(LastStore);
1454 MBB.erase(LastStore);
1455 if (CheckDef) {
1456 // Look at defs of killed registers on the store. Mark the defs
1457 // as dead since the store has been deleted and they aren't
1458 // being reused.
1459 for (unsigned j = 0, ee = KillRegs.size(); j != ee; ++j) {
1460 bool HasOtherDef = false;
1461 if (InvalidateRegDef(PrevMII, *MII, KillRegs[j], HasOtherDef)) {
1462 MachineInstr *DeadDef = PrevMII;
1463 if (ReMatDefs.count(DeadDef) && !HasOtherDef) {
Evan Cheng4784f1f2009-06-30 08:49:04 +00001464 // FIXME: This assumes a remat def does not have side effects.
Lang Hames87e3bca2009-05-06 02:36:21 +00001465 VRM.RemoveMachineInstrFromMaps(DeadDef);
1466 MBB.erase(DeadDef);
1467 ++NumDRM;
1468 }
1469 }
1470 }
1471 }
1472 }
1473
Dale Johannesene841d2f2009-10-28 21:56:18 +00001474 // Allow for multi-instruction spill sequences, as on PPC Altivec. Presume
1475 // the last of multiple instructions is the actual store.
1476 LastStore = prior(oldNextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001477
1478 // If the stack slot value was previously available in some other
1479 // register, change it now. Otherwise, make the register available,
1480 // in PhysReg.
1481 Spills.ModifyStackSlotOrReMat(StackSlot);
1482 Spills.ClobberPhysReg(PhysReg);
1483 Spills.addAvailable(StackSlot, PhysReg, isAvailable);
1484 ++NumStores;
1485 }
1486
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001487 /// isSafeToDelete - Return true if this instruction doesn't produce any side
1488 /// effect and all of its defs are dead.
1489 static bool isSafeToDelete(MachineInstr &MI) {
1490 const TargetInstrDesc &TID = MI.getDesc();
1491 if (TID.mayLoad() || TID.mayStore() || TID.isCall() || TID.isTerminator() ||
1492 TID.isCall() || TID.isBarrier() || TID.isReturn() ||
1493 TID.hasUnmodeledSideEffects())
1494 return false;
1495 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1496 MachineOperand &MO = MI.getOperand(i);
1497 if (!MO.isReg() || !MO.getReg())
1498 continue;
1499 if (MO.isDef() && !MO.isDead())
1500 return false;
1501 if (MO.isUse() && MO.isKill())
1502 // FIXME: We can't remove kill markers or else the scavenger will assert.
1503 // An alternative is to add a ADD pseudo instruction to replace kill
1504 // markers.
1505 return false;
1506 }
1507 return true;
1508 }
1509
Lang Hames87e3bca2009-05-06 02:36:21 +00001510 /// TransferDeadness - A identity copy definition is dead and it's being
1511 /// removed. Find the last def or use and mark it as dead / kill.
1512 void TransferDeadness(MachineBasicBlock *MBB, unsigned CurDist,
1513 unsigned Reg, BitVector &RegKills,
Evan Chengeca24fb2009-05-12 23:07:00 +00001514 std::vector<MachineOperand*> &KillOps,
1515 VirtRegMap &VRM) {
1516 SmallPtrSet<MachineInstr*, 4> Seens;
1517 SmallVector<std::pair<MachineInstr*, int>,8> Refs;
Lang Hames87e3bca2009-05-06 02:36:21 +00001518 for (MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(Reg),
1519 RE = RegInfo->reg_end(); RI != RE; ++RI) {
1520 MachineInstr *UDMI = &*RI;
1521 if (UDMI->getParent() != MBB)
1522 continue;
1523 DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UDMI);
1524 if (DI == DistanceMap.end() || DI->second > CurDist)
1525 continue;
Evan Chengeca24fb2009-05-12 23:07:00 +00001526 if (Seens.insert(UDMI))
1527 Refs.push_back(std::make_pair(UDMI, DI->second));
Lang Hames87e3bca2009-05-06 02:36:21 +00001528 }
1529
Evan Chengeca24fb2009-05-12 23:07:00 +00001530 if (Refs.empty())
1531 return;
1532 std::sort(Refs.begin(), Refs.end(), RefSorter());
1533
1534 while (!Refs.empty()) {
1535 MachineInstr *LastUDMI = Refs.back().first;
1536 Refs.pop_back();
1537
Lang Hames87e3bca2009-05-06 02:36:21 +00001538 MachineOperand *LastUD = NULL;
1539 for (unsigned i = 0, e = LastUDMI->getNumOperands(); i != e; ++i) {
1540 MachineOperand &MO = LastUDMI->getOperand(i);
1541 if (!MO.isReg() || MO.getReg() != Reg)
1542 continue;
1543 if (!LastUD || (LastUD->isUse() && MO.isDef()))
1544 LastUD = &MO;
1545 if (LastUDMI->isRegTiedToDefOperand(i))
Evan Chengeca24fb2009-05-12 23:07:00 +00001546 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001547 }
Evan Chengeca24fb2009-05-12 23:07:00 +00001548 if (LastUD->isDef()) {
1549 // If the instruction has no side effect, delete it and propagate
1550 // backward further. Otherwise, mark is dead and we are done.
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00001551 if (!isSafeToDelete(*LastUDMI)) {
Evan Chengeca24fb2009-05-12 23:07:00 +00001552 LastUD->setIsDead();
1553 break;
1554 }
1555 VRM.RemoveMachineInstrFromMaps(LastUDMI);
1556 MBB->erase(LastUDMI);
1557 } else {
Lang Hames87e3bca2009-05-06 02:36:21 +00001558 LastUD->setIsKill();
1559 RegKills.set(Reg);
1560 KillOps[Reg] = LastUD;
Evan Chengeca24fb2009-05-12 23:07:00 +00001561 break;
Lang Hames87e3bca2009-05-06 02:36:21 +00001562 }
1563 }
1564 }
1565
1566 /// rewriteMBB - Keep track of which spills are available even after the
1567 /// register allocator is done with them. If possible, avid reloading vregs.
1568 void RewriteMBB(MachineBasicBlock &MBB, VirtRegMap &VRM,
1569 LiveIntervals *LIs,
1570 AvailableSpills &Spills, BitVector &RegKills,
1571 std::vector<MachineOperand*> &KillOps) {
1572
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001573 DEBUG(errs() << "\n**** Local spiller rewriting MBB '"
1574 << MBB.getBasicBlock()->getName() << "':\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001575
1576 MachineFunction &MF = *MBB.getParent();
1577
1578 // MaybeDeadStores - When we need to write a value back into a stack slot,
1579 // keep track of the inserted store. If the stack slot value is never read
1580 // (because the value was used from some available register, for example), and
1581 // subsequently stored to, the original store is dead. This map keeps track
1582 // of inserted stores that are not used. If we see a subsequent store to the
1583 // same stack slot, the original store is deleted.
1584 std::vector<MachineInstr*> MaybeDeadStores;
1585 MaybeDeadStores.resize(MF.getFrameInfo()->getObjectIndexEnd(), NULL);
1586
1587 // ReMatDefs - These are rematerializable def MIs which are not deleted.
1588 SmallSet<MachineInstr*, 4> ReMatDefs;
1589
1590 // Clear kill info.
1591 SmallSet<unsigned, 2> KilledMIRegs;
1592 RegKills.reset();
1593 KillOps.clear();
1594 KillOps.resize(TRI->getNumRegs(), NULL);
1595
1596 unsigned Dist = 0;
1597 DistanceMap.clear();
1598 for (MachineBasicBlock::iterator MII = MBB.begin(), E = MBB.end();
1599 MII != E; ) {
1600 MachineBasicBlock::iterator NextMII = next(MII);
1601
1602 VirtRegMap::MI2VirtMapTy::const_iterator I, End;
1603 bool Erased = false;
1604 bool BackTracked = false;
1605 if (OptimizeByUnfold(MBB, MII,
1606 MaybeDeadStores, Spills, RegKills, KillOps, VRM))
1607 NextMII = next(MII);
1608
1609 MachineInstr &MI = *MII;
1610
1611 if (VRM.hasEmergencySpills(&MI)) {
1612 // Spill physical register(s) in the rare case the allocator has run out
1613 // of registers to allocate.
1614 SmallSet<int, 4> UsedSS;
1615 std::vector<unsigned> &EmSpills = VRM.getEmergencySpills(&MI);
1616 for (unsigned i = 0, e = EmSpills.size(); i != e; ++i) {
1617 unsigned PhysReg = EmSpills[i];
1618 const TargetRegisterClass *RC =
1619 TRI->getPhysicalRegisterRegClass(PhysReg);
1620 assert(RC && "Unable to determine register class!");
1621 int SS = VRM.getEmergencySpillSlot(RC);
1622 if (UsedSS.count(SS))
Torok Edwinc23197a2009-07-14 16:55:14 +00001623 llvm_unreachable("Need to spill more than one physical registers!");
Lang Hames87e3bca2009-05-06 02:36:21 +00001624 UsedSS.insert(SS);
1625 TII->storeRegToStackSlot(MBB, MII, PhysReg, true, SS, RC);
1626 MachineInstr *StoreMI = prior(MII);
1627 VRM.addSpillSlotUse(SS, StoreMI);
David Greene2d4e6d32009-07-28 16:49:24 +00001628
1629 // Back-schedule reloads and remats.
1630 MachineBasicBlock::iterator InsertLoc =
1631 ComputeReloadLoc(next(MII), MBB.begin(), PhysReg, TRI, false,
1632 SS, TII, MF);
1633
1634 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SS, RC);
1635
1636 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00001637 VRM.addSpillSlotUse(SS, LoadMI);
1638 ++NumPSpills;
Jakob Stoklund Olesen7a1e8722009-08-15 11:03:03 +00001639 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00001640 }
1641 NextMII = next(MII);
1642 }
1643
1644 // Insert restores here if asked to.
1645 if (VRM.isRestorePt(&MI)) {
1646 std::vector<unsigned> &RestoreRegs = VRM.getRestorePtRestores(&MI);
1647 for (unsigned i = 0, e = RestoreRegs.size(); i != e; ++i) {
1648 unsigned VirtReg = RestoreRegs[e-i-1]; // Reverse order.
1649 if (!VRM.getPreSplitReg(VirtReg))
1650 continue; // Split interval spilled again.
1651 unsigned Phys = VRM.getPhys(VirtReg);
1652 RegInfo->setPhysRegUsed(Phys);
1653
1654 // Check if the value being restored if available. If so, it must be
1655 // from a predecessor BB that fallthrough into this BB. We do not
1656 // expect:
1657 // BB1:
1658 // r1 = load fi#1
1659 // ...
1660 // = r1<kill>
1661 // ... # r1 not clobbered
1662 // ...
1663 // = load fi#1
1664 bool DoReMat = VRM.isReMaterialized(VirtReg);
1665 int SSorRMId = DoReMat
1666 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1667 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1668 unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1669 if (InReg == Phys) {
1670 // If the value is already available in the expected register, save
1671 // a reload / remat.
1672 if (SSorRMId)
Chris Lattner6456d382009-08-23 03:20:44 +00001673 DEBUG(errs() << "Reusing RM#"
1674 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001675 else
Chris Lattner6456d382009-08-23 03:20:44 +00001676 DEBUG(errs() << "Reusing SS#" << SSorRMId);
1677 DEBUG(errs() << " from physreg "
1678 << TRI->getName(InReg) << " for vreg"
1679 << VirtReg <<" instead of reloading into physreg "
1680 << TRI->getName(Phys) << '\n');
Lang Hames87e3bca2009-05-06 02:36:21 +00001681 ++NumOmitted;
1682 continue;
1683 } else if (InReg && InReg != Phys) {
1684 if (SSorRMId)
Chris Lattner6456d382009-08-23 03:20:44 +00001685 DEBUG(errs() << "Reusing RM#"
1686 << SSorRMId-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001687 else
Chris Lattner6456d382009-08-23 03:20:44 +00001688 DEBUG(errs() << "Reusing SS#" << SSorRMId);
1689 DEBUG(errs() << " from physreg "
1690 << TRI->getName(InReg) << " for vreg"
1691 << VirtReg <<" by copying it into physreg "
1692 << TRI->getName(Phys) << '\n');
Lang Hames87e3bca2009-05-06 02:36:21 +00001693
1694 // If the reloaded / remat value is available in another register,
1695 // copy it to the desired register.
David Greene2d4e6d32009-07-28 16:49:24 +00001696
1697 // Back-schedule reloads and remats.
1698 MachineBasicBlock::iterator InsertLoc =
1699 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1700 SSorRMId, TII, MF);
1701
1702 TII->copyRegToReg(MBB, InsertLoc, Phys, InReg, RC, RC);
Lang Hames87e3bca2009-05-06 02:36:21 +00001703
1704 // This invalidates Phys.
1705 Spills.ClobberPhysReg(Phys);
1706 // Remember it's available.
1707 Spills.addAvailable(SSorRMId, Phys);
1708
1709 // Mark is killed.
David Greene2d4e6d32009-07-28 16:49:24 +00001710 MachineInstr *CopyMI = prior(InsertLoc);
David Greene6bedb302009-11-12 21:07:54 +00001711 CopyMI->setAsmPrinterFlag(AsmPrinter::ReloadReuse);
Lang Hames87e3bca2009-05-06 02:36:21 +00001712 MachineOperand *KillOpnd = CopyMI->findRegisterUseOperand(InReg);
1713 KillOpnd->setIsKill();
Evan Cheng427a6b62009-05-15 06:48:19 +00001714 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001715
Chris Lattner6456d382009-08-23 03:20:44 +00001716 DEBUG(errs() << '\t' << *CopyMI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001717 ++NumCopified;
1718 continue;
1719 }
1720
David Greene2d4e6d32009-07-28 16:49:24 +00001721 // Back-schedule reloads and remats.
1722 MachineBasicBlock::iterator InsertLoc =
1723 ComputeReloadLoc(MII, MBB.begin(), Phys, TRI, DoReMat,
1724 SSorRMId, TII, MF);
1725
Lang Hames87e3bca2009-05-06 02:36:21 +00001726 if (VRM.isReMaterialized(VirtReg)) {
David Greene2d4e6d32009-07-28 16:49:24 +00001727 ReMaterialize(MBB, InsertLoc, Phys, VirtReg, TII, TRI, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00001728 } else {
1729 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
David Greene2d4e6d32009-07-28 16:49:24 +00001730 TII->loadRegFromStackSlot(MBB, InsertLoc, Phys, SSorRMId, RC);
1731 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00001732 VRM.addSpillSlotUse(SSorRMId, LoadMI);
1733 ++NumLoads;
Jakob Stoklund Olesen7a1e8722009-08-15 11:03:03 +00001734 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00001735 }
1736
1737 // This invalidates Phys.
1738 Spills.ClobberPhysReg(Phys);
1739 // Remember it's available.
1740 Spills.addAvailable(SSorRMId, Phys);
1741
David Greene2d4e6d32009-07-28 16:49:24 +00001742 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
Chris Lattner6456d382009-08-23 03:20:44 +00001743 DEBUG(errs() << '\t' << *prior(MII));
Lang Hames87e3bca2009-05-06 02:36:21 +00001744 }
1745 }
1746
1747 // Insert spills here if asked to.
1748 if (VRM.isSpillPt(&MI)) {
1749 std::vector<std::pair<unsigned,bool> > &SpillRegs =
1750 VRM.getSpillPtSpills(&MI);
1751 for (unsigned i = 0, e = SpillRegs.size(); i != e; ++i) {
1752 unsigned VirtReg = SpillRegs[i].first;
1753 bool isKill = SpillRegs[i].second;
1754 if (!VRM.getPreSplitReg(VirtReg))
1755 continue; // Split interval spilled again.
1756 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
1757 unsigned Phys = VRM.getPhys(VirtReg);
1758 int StackSlot = VRM.getStackSlot(VirtReg);
Dale Johannesen78c5cda2009-10-29 01:15:40 +00001759 MachineBasicBlock::iterator oldNextMII = next(MII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001760 TII->storeRegToStackSlot(MBB, next(MII), Phys, isKill, StackSlot, RC);
Dale Johannesen78c5cda2009-10-29 01:15:40 +00001761 MachineInstr *StoreMI = prior(oldNextMII);
Lang Hames87e3bca2009-05-06 02:36:21 +00001762 VRM.addSpillSlotUse(StackSlot, StoreMI);
Chris Lattner6456d382009-08-23 03:20:44 +00001763 DEBUG(errs() << "Store:\t" << *StoreMI);
Lang Hames87e3bca2009-05-06 02:36:21 +00001764 VRM.virtFolded(VirtReg, StoreMI, VirtRegMap::isMod);
1765 }
1766 NextMII = next(MII);
1767 }
1768
1769 /// ReusedOperands - Keep track of operand reuse in case we need to undo
1770 /// reuse.
1771 ReuseInfo ReusedOperands(MI, TRI);
1772 SmallVector<unsigned, 4> VirtUseOps;
1773 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1774 MachineOperand &MO = MI.getOperand(i);
1775 if (!MO.isReg() || MO.getReg() == 0)
1776 continue; // Ignore non-register operands.
1777
1778 unsigned VirtReg = MO.getReg();
1779 if (TargetRegisterInfo::isPhysicalRegister(VirtReg)) {
1780 // Ignore physregs for spilling, but remember that it is used by this
1781 // function.
1782 RegInfo->setPhysRegUsed(VirtReg);
1783 continue;
1784 }
1785
1786 // We want to process implicit virtual register uses first.
1787 if (MO.isImplicit())
1788 // If the virtual register is implicitly defined, emit a implicit_def
1789 // before so scavenger knows it's "defined".
Evan Cheng4784f1f2009-06-30 08:49:04 +00001790 // FIXME: This is a horrible hack done the by register allocator to
1791 // remat a definition with virtual register operand.
Lang Hames87e3bca2009-05-06 02:36:21 +00001792 VirtUseOps.insert(VirtUseOps.begin(), i);
1793 else
1794 VirtUseOps.push_back(i);
1795 }
1796
1797 // Process all of the spilled uses and all non spilled reg references.
1798 SmallVector<int, 2> PotentialDeadStoreSlots;
1799 KilledMIRegs.clear();
1800 for (unsigned j = 0, e = VirtUseOps.size(); j != e; ++j) {
1801 unsigned i = VirtUseOps[j];
1802 MachineOperand &MO = MI.getOperand(i);
1803 unsigned VirtReg = MO.getReg();
1804 assert(TargetRegisterInfo::isVirtualRegister(VirtReg) &&
1805 "Not a virtual register?");
1806
1807 unsigned SubIdx = MO.getSubReg();
1808 if (VRM.isAssignedReg(VirtReg)) {
1809 // This virtual register was assigned a physreg!
1810 unsigned Phys = VRM.getPhys(VirtReg);
1811 RegInfo->setPhysRegUsed(Phys);
1812 if (MO.isDef())
1813 ReusedOperands.markClobbered(Phys);
1814 unsigned RReg = SubIdx ? TRI->getSubReg(Phys, SubIdx) : Phys;
1815 MI.getOperand(i).setReg(RReg);
1816 MI.getOperand(i).setSubReg(0);
1817 if (VRM.isImplicitlyDefined(VirtReg))
Evan Cheng4784f1f2009-06-30 08:49:04 +00001818 // FIXME: Is this needed?
Lang Hames87e3bca2009-05-06 02:36:21 +00001819 BuildMI(MBB, &MI, MI.getDebugLoc(),
1820 TII->get(TargetInstrInfo::IMPLICIT_DEF), RReg);
1821 continue;
1822 }
1823
1824 // This virtual register is now known to be a spilled value.
1825 if (!MO.isUse())
1826 continue; // Handle defs in the loop below (handle use&def here though)
1827
Evan Cheng4784f1f2009-06-30 08:49:04 +00001828 bool AvoidReload = MO.isUndef();
1829 // Check if it is defined by an implicit def. It should not be spilled.
1830 // Note, this is for correctness reason. e.g.
1831 // 8 %reg1024<def> = IMPLICIT_DEF
1832 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1833 // The live range [12, 14) are not part of the r1024 live interval since
1834 // it's defined by an implicit def. It will not conflicts with live
1835 // interval of r1025. Now suppose both registers are spilled, you can
1836 // easily see a situation where both registers are reloaded before
1837 // the INSERT_SUBREG and both target registers that would overlap.
Lang Hames87e3bca2009-05-06 02:36:21 +00001838 bool DoReMat = VRM.isReMaterialized(VirtReg);
1839 int SSorRMId = DoReMat
1840 ? VRM.getReMatId(VirtReg) : VRM.getStackSlot(VirtReg);
1841 int ReuseSlot = SSorRMId;
1842
1843 // Check to see if this stack slot is available.
1844 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SSorRMId);
1845
1846 // If this is a sub-register use, make sure the reuse register is in the
1847 // right register class. For example, for x86 not all of the 32-bit
1848 // registers have accessible sub-registers.
1849 // Similarly so for EXTRACT_SUBREG. Consider this:
1850 // EDI = op
1851 // MOV32_mr fi#1, EDI
1852 // ...
1853 // = EXTRACT_SUBREG fi#1
1854 // fi#1 is available in EDI, but it cannot be reused because it's not in
1855 // the right register file.
1856 if (PhysReg && !AvoidReload &&
1857 (SubIdx || MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)) {
1858 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1859 if (!RC->contains(PhysReg))
1860 PhysReg = 0;
1861 }
1862
1863 if (PhysReg && !AvoidReload) {
1864 // This spilled operand might be part of a two-address operand. If this
1865 // is the case, then changing it will necessarily require changing the
1866 // def part of the instruction as well. However, in some cases, we
1867 // aren't allowed to modify the reused register. If none of these cases
1868 // apply, reuse it.
1869 bool CanReuse = true;
1870 bool isTied = MI.isRegTiedToDefOperand(i);
1871 if (isTied) {
1872 // Okay, we have a two address operand. We can reuse this physreg as
1873 // long as we are allowed to clobber the value and there isn't an
1874 // earlier def that has already clobbered the physreg.
1875 CanReuse = !ReusedOperands.isClobbered(PhysReg) &&
1876 Spills.canClobberPhysReg(PhysReg);
1877 }
1878
1879 if (CanReuse) {
1880 // If this stack slot value is already available, reuse it!
1881 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
Chris Lattner6456d382009-08-23 03:20:44 +00001882 DEBUG(errs() << "Reusing RM#"
1883 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001884 else
Chris Lattner6456d382009-08-23 03:20:44 +00001885 DEBUG(errs() << "Reusing SS#" << ReuseSlot);
1886 DEBUG(errs() << " from physreg "
1887 << TRI->getName(PhysReg) << " for vreg"
1888 << VirtReg <<" instead of reloading into physreg "
1889 << TRI->getName(VRM.getPhys(VirtReg)) << '\n');
Lang Hames87e3bca2009-05-06 02:36:21 +00001890 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1891 MI.getOperand(i).setReg(RReg);
1892 MI.getOperand(i).setSubReg(0);
1893
1894 // The only technical detail we have is that we don't know that
1895 // PhysReg won't be clobbered by a reloaded stack slot that occurs
1896 // later in the instruction. In particular, consider 'op V1, V2'.
1897 // If V1 is available in physreg R0, we would choose to reuse it
1898 // here, instead of reloading it into the register the allocator
1899 // indicated (say R1). However, V2 might have to be reloaded
1900 // later, and it might indicate that it needs to live in R0. When
1901 // this occurs, we need to have information available that
1902 // indicates it is safe to use R1 for the reload instead of R0.
1903 //
1904 // To further complicate matters, we might conflict with an alias,
1905 // or R0 and R1 might not be compatible with each other. In this
1906 // case, we actually insert a reload for V1 in R1, ensuring that
1907 // we can get at R0 or its alias.
1908 ReusedOperands.addReuse(i, ReuseSlot, PhysReg,
1909 VRM.getPhys(VirtReg), VirtReg);
1910 if (isTied)
1911 // Only mark it clobbered if this is a use&def operand.
1912 ReusedOperands.markClobbered(PhysReg);
1913 ++NumReused;
1914
1915 if (MI.getOperand(i).isKill() &&
1916 ReuseSlot <= VirtRegMap::MAX_STACK_SLOT) {
1917
1918 // The store of this spilled value is potentially dead, but we
1919 // won't know for certain until we've confirmed that the re-use
1920 // above is valid, which means waiting until the other operands
1921 // are processed. For now we just track the spill slot, we'll
1922 // remove it after the other operands are processed if valid.
1923
1924 PotentialDeadStoreSlots.push_back(ReuseSlot);
1925 }
1926
1927 // Mark is isKill if it's there no other uses of the same virtual
1928 // register and it's not a two-address operand. IsKill will be
1929 // unset if reg is reused.
1930 if (!isTied && KilledMIRegs.count(VirtReg) == 0) {
1931 MI.getOperand(i).setIsKill();
1932 KilledMIRegs.insert(VirtReg);
1933 }
1934
1935 continue;
1936 } // CanReuse
1937
1938 // Otherwise we have a situation where we have a two-address instruction
1939 // whose mod/ref operand needs to be reloaded. This reload is already
1940 // available in some register "PhysReg", but if we used PhysReg as the
1941 // operand to our 2-addr instruction, the instruction would modify
1942 // PhysReg. This isn't cool if something later uses PhysReg and expects
1943 // to get its initial value.
1944 //
1945 // To avoid this problem, and to avoid doing a load right after a store,
1946 // we emit a copy from PhysReg into the designated register for this
1947 // operand.
1948 unsigned DesignatedReg = VRM.getPhys(VirtReg);
1949 assert(DesignatedReg && "Must map virtreg to physreg!");
1950
1951 // Note that, if we reused a register for a previous operand, the
1952 // register we want to reload into might not actually be
1953 // available. If this occurs, use the register indicated by the
1954 // reuser.
1955 if (ReusedOperands.hasReuses())
Evan Cheng5d885022009-07-21 09:15:00 +00001956 DesignatedReg = ReusedOperands.GetRegForReload(VirtReg,
1957 DesignatedReg, &MI,
1958 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00001959
1960 // If the mapped designated register is actually the physreg we have
1961 // incoming, we don't need to inserted a dead copy.
1962 if (DesignatedReg == PhysReg) {
1963 // If this stack slot value is already available, reuse it!
1964 if (ReuseSlot > VirtRegMap::MAX_STACK_SLOT)
Chris Lattner6456d382009-08-23 03:20:44 +00001965 DEBUG(errs() << "Reusing RM#"
1966 << ReuseSlot-VirtRegMap::MAX_STACK_SLOT-1);
Lang Hames87e3bca2009-05-06 02:36:21 +00001967 else
Chris Lattner6456d382009-08-23 03:20:44 +00001968 DEBUG(errs() << "Reusing SS#" << ReuseSlot);
1969 DEBUG(errs() << " from physreg " << TRI->getName(PhysReg)
1970 << " for vreg" << VirtReg
1971 << " instead of reloading into same physreg.\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00001972 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
1973 MI.getOperand(i).setReg(RReg);
1974 MI.getOperand(i).setSubReg(0);
1975 ReusedOperands.markClobbered(RReg);
1976 ++NumReused;
1977 continue;
1978 }
1979
1980 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
1981 RegInfo->setPhysRegUsed(DesignatedReg);
1982 ReusedOperands.markClobbered(DesignatedReg);
Lang Hames87e3bca2009-05-06 02:36:21 +00001983
David Greene2d4e6d32009-07-28 16:49:24 +00001984 // Back-schedule reloads and remats.
1985 MachineBasicBlock::iterator InsertLoc =
1986 ComputeReloadLoc(&MI, MBB.begin(), PhysReg, TRI, DoReMat,
1987 SSorRMId, TII, MF);
1988
1989 TII->copyRegToReg(MBB, InsertLoc, DesignatedReg, PhysReg, RC, RC);
1990
1991 MachineInstr *CopyMI = prior(InsertLoc);
David Greene6bedb302009-11-12 21:07:54 +00001992 CopyMI->setAsmPrinterFlag(AsmPrinter::ReloadReuse);
Evan Cheng427a6b62009-05-15 06:48:19 +00001993 UpdateKills(*CopyMI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00001994
1995 // This invalidates DesignatedReg.
1996 Spills.ClobberPhysReg(DesignatedReg);
1997
1998 Spills.addAvailable(ReuseSlot, DesignatedReg);
1999 unsigned RReg =
2000 SubIdx ? TRI->getSubReg(DesignatedReg, SubIdx) : DesignatedReg;
2001 MI.getOperand(i).setReg(RReg);
2002 MI.getOperand(i).setSubReg(0);
Chris Lattner6456d382009-08-23 03:20:44 +00002003 DEBUG(errs() << '\t' << *prior(MII));
Lang Hames87e3bca2009-05-06 02:36:21 +00002004 ++NumReused;
2005 continue;
2006 } // if (PhysReg)
2007
2008 // Otherwise, reload it and remember that we have it.
2009 PhysReg = VRM.getPhys(VirtReg);
2010 assert(PhysReg && "Must map virtreg to physreg!");
2011
2012 // Note that, if we reused a register for a previous operand, the
2013 // register we want to reload into might not actually be
2014 // available. If this occurs, use the register indicated by the
2015 // reuser.
2016 if (ReusedOperands.hasReuses())
Evan Cheng5d885022009-07-21 09:15:00 +00002017 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2018 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002019
2020 RegInfo->setPhysRegUsed(PhysReg);
2021 ReusedOperands.markClobbered(PhysReg);
2022 if (AvoidReload)
2023 ++NumAvoided;
2024 else {
David Greene2d4e6d32009-07-28 16:49:24 +00002025 // Back-schedule reloads and remats.
2026 MachineBasicBlock::iterator InsertLoc =
2027 ComputeReloadLoc(MII, MBB.begin(), PhysReg, TRI, DoReMat,
2028 SSorRMId, TII, MF);
2029
Lang Hames87e3bca2009-05-06 02:36:21 +00002030 if (DoReMat) {
David Greene2d4e6d32009-07-28 16:49:24 +00002031 ReMaterialize(MBB, InsertLoc, PhysReg, VirtReg, TII, TRI, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002032 } else {
2033 const TargetRegisterClass* RC = RegInfo->getRegClass(VirtReg);
David Greene2d4e6d32009-07-28 16:49:24 +00002034 TII->loadRegFromStackSlot(MBB, InsertLoc, PhysReg, SSorRMId, RC);
2035 MachineInstr *LoadMI = prior(InsertLoc);
Lang Hames87e3bca2009-05-06 02:36:21 +00002036 VRM.addSpillSlotUse(SSorRMId, LoadMI);
2037 ++NumLoads;
Jakob Stoklund Olesen7a1e8722009-08-15 11:03:03 +00002038 DistanceMap.insert(std::make_pair(LoadMI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00002039 }
2040 // This invalidates PhysReg.
2041 Spills.ClobberPhysReg(PhysReg);
2042
2043 // Any stores to this stack slot are not dead anymore.
2044 if (!DoReMat)
2045 MaybeDeadStores[SSorRMId] = NULL;
2046 Spills.addAvailable(SSorRMId, PhysReg);
2047 // Assumes this is the last use. IsKill will be unset if reg is reused
2048 // unless it's a two-address operand.
2049 if (!MI.isRegTiedToDefOperand(i) &&
2050 KilledMIRegs.count(VirtReg) == 0) {
2051 MI.getOperand(i).setIsKill();
2052 KilledMIRegs.insert(VirtReg);
2053 }
2054
David Greene2d4e6d32009-07-28 16:49:24 +00002055 UpdateKills(*prior(InsertLoc), TRI, RegKills, KillOps);
Chris Lattner6456d382009-08-23 03:20:44 +00002056 DEBUG(errs() << '\t' << *prior(InsertLoc));
Lang Hames87e3bca2009-05-06 02:36:21 +00002057 }
2058 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2059 MI.getOperand(i).setReg(RReg);
2060 MI.getOperand(i).setSubReg(0);
2061 }
2062
2063 // Ok - now we can remove stores that have been confirmed dead.
2064 for (unsigned j = 0, e = PotentialDeadStoreSlots.size(); j != e; ++j) {
2065 // This was the last use and the spilled value is still available
2066 // for reuse. That means the spill was unnecessary!
2067 int PDSSlot = PotentialDeadStoreSlots[j];
2068 MachineInstr* DeadStore = MaybeDeadStores[PDSSlot];
2069 if (DeadStore) {
Chris Lattner6456d382009-08-23 03:20:44 +00002070 DEBUG(errs() << "Removed dead store:\t" << *DeadStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002071 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002072 VRM.RemoveMachineInstrFromMaps(DeadStore);
2073 MBB.erase(DeadStore);
2074 MaybeDeadStores[PDSSlot] = NULL;
2075 ++NumDSE;
2076 }
2077 }
2078
2079
Chris Lattner6456d382009-08-23 03:20:44 +00002080 DEBUG(errs() << '\t' << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002081
2082
2083 // If we have folded references to memory operands, make sure we clear all
2084 // physical registers that may contain the value of the spilled virtual
2085 // register
2086 SmallSet<int, 2> FoldedSS;
2087 for (tie(I, End) = VRM.getFoldedVirts(&MI); I != End; ) {
2088 unsigned VirtReg = I->second.first;
2089 VirtRegMap::ModRef MR = I->second.second;
Chris Lattner6456d382009-08-23 03:20:44 +00002090 DEBUG(errs() << "Folded vreg: " << VirtReg << " MR: " << MR);
Lang Hames87e3bca2009-05-06 02:36:21 +00002091
2092 // MI2VirtMap be can updated which invalidate the iterator.
2093 // Increment the iterator first.
2094 ++I;
2095 int SS = VRM.getStackSlot(VirtReg);
2096 if (SS == VirtRegMap::NO_STACK_SLOT)
2097 continue;
2098 FoldedSS.insert(SS);
Chris Lattner6456d382009-08-23 03:20:44 +00002099 DEBUG(errs() << " - StackSlot: " << SS << "\n");
Lang Hames87e3bca2009-05-06 02:36:21 +00002100
2101 // If this folded instruction is just a use, check to see if it's a
2102 // straight load from the virt reg slot.
2103 if ((MR & VirtRegMap::isRef) && !(MR & VirtRegMap::isMod)) {
2104 int FrameIdx;
2105 unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx);
2106 if (DestReg && FrameIdx == SS) {
2107 // If this spill slot is available, turn it into a copy (or nothing)
2108 // instead of leaving it as a load!
2109 if (unsigned InReg = Spills.getSpillSlotOrReMatPhysReg(SS)) {
Chris Lattner6456d382009-08-23 03:20:44 +00002110 DEBUG(errs() << "Promoted Load To Copy: " << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002111 if (DestReg != InReg) {
2112 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2113 TII->copyRegToReg(MBB, &MI, DestReg, InReg, RC, RC);
2114 MachineOperand *DefMO = MI.findRegisterDefOperand(DestReg);
2115 unsigned SubIdx = DefMO->getSubReg();
2116 // Revisit the copy so we make sure to notice the effects of the
2117 // operation on the destreg (either needing to RA it if it's
2118 // virtual or needing to clobber any values if it's physical).
2119 NextMII = &MI;
2120 --NextMII; // backtrack to the copy.
David Greene6bedb302009-11-12 21:07:54 +00002121 NextMII->setAsmPrinterFlag(AsmPrinter::ReloadReuse);
Lang Hames87e3bca2009-05-06 02:36:21 +00002122 // Propagate the sub-register index over.
2123 if (SubIdx) {
2124 DefMO = NextMII->findRegisterDefOperand(DestReg);
2125 DefMO->setSubReg(SubIdx);
2126 }
2127
2128 // Mark is killed.
2129 MachineOperand *KillOpnd = NextMII->findRegisterUseOperand(InReg);
2130 KillOpnd->setIsKill();
2131
2132 BackTracked = true;
2133 } else {
Chris Lattner6456d382009-08-23 03:20:44 +00002134 DEBUG(errs() << "Removing now-noop copy: " << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002135 // Unset last kill since it's being reused.
Evan Cheng427a6b62009-05-15 06:48:19 +00002136 InvalidateKill(InReg, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002137 Spills.disallowClobberPhysReg(InReg);
2138 }
2139
Evan Cheng427a6b62009-05-15 06:48:19 +00002140 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002141 VRM.RemoveMachineInstrFromMaps(&MI);
2142 MBB.erase(&MI);
2143 Erased = true;
2144 goto ProcessNextInst;
2145 }
2146 } else {
2147 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2148 SmallVector<MachineInstr*, 4> NewMIs;
2149 if (PhysReg &&
2150 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, false, NewMIs)) {
2151 MBB.insert(MII, NewMIs[0]);
Evan Cheng427a6b62009-05-15 06:48:19 +00002152 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002153 VRM.RemoveMachineInstrFromMaps(&MI);
2154 MBB.erase(&MI);
2155 Erased = true;
2156 --NextMII; // backtrack to the unfolded instruction.
2157 BackTracked = true;
2158 goto ProcessNextInst;
2159 }
2160 }
2161 }
2162
2163 // If this reference is not a use, any previous store is now dead.
2164 // Otherwise, the store to this stack slot is not dead anymore.
2165 MachineInstr* DeadStore = MaybeDeadStores[SS];
2166 if (DeadStore) {
2167 bool isDead = !(MR & VirtRegMap::isRef);
2168 MachineInstr *NewStore = NULL;
2169 if (MR & VirtRegMap::isModRef) {
2170 unsigned PhysReg = Spills.getSpillSlotOrReMatPhysReg(SS);
2171 SmallVector<MachineInstr*, 4> NewMIs;
2172 // We can reuse this physreg as long as we are allowed to clobber
2173 // the value and there isn't an earlier def that has already clobbered
2174 // the physreg.
2175 if (PhysReg &&
2176 !ReusedOperands.isClobbered(PhysReg) &&
2177 Spills.canClobberPhysReg(PhysReg) &&
2178 !TII->isStoreToStackSlot(&MI, SS)) { // Not profitable!
2179 MachineOperand *KillOpnd =
2180 DeadStore->findRegisterUseOperand(PhysReg, true);
2181 // Note, if the store is storing a sub-register, it's possible the
2182 // super-register is needed below.
2183 if (KillOpnd && !KillOpnd->getSubReg() &&
2184 TII->unfoldMemoryOperand(MF, &MI, PhysReg, false, true,NewMIs)){
2185 MBB.insert(MII, NewMIs[0]);
2186 NewStore = NewMIs[1];
2187 MBB.insert(MII, NewStore);
2188 VRM.addSpillSlotUse(SS, NewStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002189 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002190 VRM.RemoveMachineInstrFromMaps(&MI);
2191 MBB.erase(&MI);
2192 Erased = true;
2193 --NextMII;
2194 --NextMII; // backtrack to the unfolded instruction.
2195 BackTracked = true;
2196 isDead = true;
2197 ++NumSUnfold;
2198 }
2199 }
2200 }
2201
2202 if (isDead) { // Previous store is dead.
2203 // If we get here, the store is dead, nuke it now.
Chris Lattner6456d382009-08-23 03:20:44 +00002204 DEBUG(errs() << "Removed dead store:\t" << *DeadStore);
Evan Cheng427a6b62009-05-15 06:48:19 +00002205 InvalidateKills(*DeadStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002206 VRM.RemoveMachineInstrFromMaps(DeadStore);
2207 MBB.erase(DeadStore);
2208 if (!NewStore)
2209 ++NumDSE;
2210 }
2211
2212 MaybeDeadStores[SS] = NULL;
2213 if (NewStore) {
2214 // Treat this store as a spill merged into a copy. That makes the
2215 // stack slot value available.
2216 VRM.virtFolded(VirtReg, NewStore, VirtRegMap::isMod);
2217 goto ProcessNextInst;
2218 }
2219 }
2220
2221 // If the spill slot value is available, and this is a new definition of
2222 // the value, the value is not available anymore.
2223 if (MR & VirtRegMap::isMod) {
2224 // Notice that the value in this stack slot has been modified.
2225 Spills.ModifyStackSlotOrReMat(SS);
2226
2227 // If this is *just* a mod of the value, check to see if this is just a
2228 // store to the spill slot (i.e. the spill got merged into the copy). If
2229 // so, realize that the vreg is available now, and add the store to the
2230 // MaybeDeadStore info.
2231 int StackSlot;
2232 if (!(MR & VirtRegMap::isRef)) {
2233 if (unsigned SrcReg = TII->isStoreToStackSlot(&MI, StackSlot)) {
2234 assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) &&
2235 "Src hasn't been allocated yet?");
2236
2237 if (CommuteToFoldReload(MBB, MII, VirtReg, SrcReg, StackSlot,
2238 Spills, RegKills, KillOps, TRI, VRM)) {
2239 NextMII = next(MII);
2240 BackTracked = true;
2241 goto ProcessNextInst;
2242 }
2243
2244 // Okay, this is certainly a store of SrcReg to [StackSlot]. Mark
2245 // this as a potentially dead store in case there is a subsequent
2246 // store into the stack slot without a read from it.
2247 MaybeDeadStores[StackSlot] = &MI;
2248
2249 // If the stack slot value was previously available in some other
2250 // register, change it now. Otherwise, make the register
2251 // available in PhysReg.
2252 Spills.addAvailable(StackSlot, SrcReg, MI.killsRegister(SrcReg));
2253 }
2254 }
2255 }
2256 }
2257
2258 // Process all of the spilled defs.
2259 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
2260 MachineOperand &MO = MI.getOperand(i);
2261 if (!(MO.isReg() && MO.getReg() && MO.isDef()))
2262 continue;
2263
2264 unsigned VirtReg = MO.getReg();
2265 if (!TargetRegisterInfo::isVirtualRegister(VirtReg)) {
2266 // Check to see if this is a noop copy. If so, eliminate the
2267 // instruction before considering the dest reg to be changed.
Evan Cheng2578ba22009-07-01 01:59:31 +00002268 // Also check if it's copying from an "undef", if so, we can't
2269 // eliminate this or else the undef marker is lost and it will
2270 // confuses the scavenger. This is extremely rare.
Lang Hames87e3bca2009-05-06 02:36:21 +00002271 unsigned Src, Dst, SrcSR, DstSR;
Evan Chenga5dc45e2009-10-26 04:56:07 +00002272 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst &&
Evan Cheng2578ba22009-07-01 01:59:31 +00002273 !MI.findRegisterUseOperand(Src)->isUndef()) {
Lang Hames87e3bca2009-05-06 02:36:21 +00002274 ++NumDCE;
Chris Lattner6456d382009-08-23 03:20:44 +00002275 DEBUG(errs() << "Removing now-noop copy: " << MI);
Lang Hames87e3bca2009-05-06 02:36:21 +00002276 SmallVector<unsigned, 2> KillRegs;
Evan Cheng427a6b62009-05-15 06:48:19 +00002277 InvalidateKills(MI, TRI, RegKills, KillOps, &KillRegs);
Lang Hames87e3bca2009-05-06 02:36:21 +00002278 if (MO.isDead() && !KillRegs.empty()) {
2279 // Source register or an implicit super/sub-register use is killed.
2280 assert(KillRegs[0] == Dst ||
2281 TRI->isSubRegister(KillRegs[0], Dst) ||
2282 TRI->isSuperRegister(KillRegs[0], Dst));
2283 // Last def is now dead.
Evan Chengeca24fb2009-05-12 23:07:00 +00002284 TransferDeadness(&MBB, Dist, Src, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002285 }
2286 VRM.RemoveMachineInstrFromMaps(&MI);
2287 MBB.erase(&MI);
2288 Erased = true;
2289 Spills.disallowClobberPhysReg(VirtReg);
2290 goto ProcessNextInst;
2291 }
Evan Cheng2578ba22009-07-01 01:59:31 +00002292
Lang Hames87e3bca2009-05-06 02:36:21 +00002293 // If it's not a no-op copy, it clobbers the value in the destreg.
2294 Spills.ClobberPhysReg(VirtReg);
2295 ReusedOperands.markClobbered(VirtReg);
2296
2297 // Check to see if this instruction is a load from a stack slot into
2298 // a register. If so, this provides the stack slot value in the reg.
2299 int FrameIdx;
2300 if (unsigned DestReg = TII->isLoadFromStackSlot(&MI, FrameIdx)) {
2301 assert(DestReg == VirtReg && "Unknown load situation!");
2302
2303 // If it is a folded reference, then it's not safe to clobber.
2304 bool Folded = FoldedSS.count(FrameIdx);
2305 // Otherwise, if it wasn't available, remember that it is now!
2306 Spills.addAvailable(FrameIdx, DestReg, !Folded);
2307 goto ProcessNextInst;
2308 }
2309
2310 continue;
2311 }
2312
2313 unsigned SubIdx = MO.getSubReg();
2314 bool DoReMat = VRM.isReMaterialized(VirtReg);
2315 if (DoReMat)
2316 ReMatDefs.insert(&MI);
2317
2318 // The only vregs left are stack slot definitions.
2319 int StackSlot = VRM.getStackSlot(VirtReg);
2320 const TargetRegisterClass *RC = RegInfo->getRegClass(VirtReg);
2321
2322 // If this def is part of a two-address operand, make sure to execute
2323 // the store from the correct physical register.
2324 unsigned PhysReg;
2325 unsigned TiedOp;
2326 if (MI.isRegTiedToUseOperand(i, &TiedOp)) {
2327 PhysReg = MI.getOperand(TiedOp).getReg();
2328 if (SubIdx) {
2329 unsigned SuperReg = findSuperReg(RC, PhysReg, SubIdx, TRI);
2330 assert(SuperReg && TRI->getSubReg(SuperReg, SubIdx) == PhysReg &&
2331 "Can't find corresponding super-register!");
2332 PhysReg = SuperReg;
2333 }
2334 } else {
2335 PhysReg = VRM.getPhys(VirtReg);
2336 if (ReusedOperands.isClobbered(PhysReg)) {
2337 // Another def has taken the assigned physreg. It must have been a
2338 // use&def which got it due to reuse. Undo the reuse!
Evan Cheng5d885022009-07-21 09:15:00 +00002339 PhysReg = ReusedOperands.GetRegForReload(VirtReg, PhysReg, &MI,
2340 Spills, MaybeDeadStores, RegKills, KillOps, VRM);
Lang Hames87e3bca2009-05-06 02:36:21 +00002341 }
2342 }
2343
2344 assert(PhysReg && "VR not assigned a physical register?");
2345 RegInfo->setPhysRegUsed(PhysReg);
2346 unsigned RReg = SubIdx ? TRI->getSubReg(PhysReg, SubIdx) : PhysReg;
2347 ReusedOperands.markClobbered(RReg);
2348 MI.getOperand(i).setReg(RReg);
2349 MI.getOperand(i).setSubReg(0);
2350
2351 if (!MO.isDead()) {
2352 MachineInstr *&LastStore = MaybeDeadStores[StackSlot];
2353 SpillRegToStackSlot(MBB, MII, -1, PhysReg, StackSlot, RC, true,
2354 LastStore, Spills, ReMatDefs, RegKills, KillOps, VRM);
2355 NextMII = next(MII);
2356
2357 // Check to see if this is a noop copy. If so, eliminate the
2358 // instruction before considering the dest reg to be changed.
2359 {
2360 unsigned Src, Dst, SrcSR, DstSR;
Evan Chenga5dc45e2009-10-26 04:56:07 +00002361 if (TII->isMoveInstr(MI, Src, Dst, SrcSR, DstSR) && Src == Dst) {
Lang Hames87e3bca2009-05-06 02:36:21 +00002362 ++NumDCE;
Chris Lattner6456d382009-08-23 03:20:44 +00002363 DEBUG(errs() << "Removing now-noop copy: " << MI);
Evan Cheng427a6b62009-05-15 06:48:19 +00002364 InvalidateKills(MI, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002365 VRM.RemoveMachineInstrFromMaps(&MI);
2366 MBB.erase(&MI);
2367 Erased = true;
Evan Cheng427a6b62009-05-15 06:48:19 +00002368 UpdateKills(*LastStore, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002369 goto ProcessNextInst;
2370 }
2371 }
2372 }
2373 }
2374 ProcessNextInst:
Evan Cheng52484682009-07-18 02:10:10 +00002375 // Delete dead instructions without side effects.
Dale Johannesen3a6b9eb2009-10-12 18:49:00 +00002376 if (!Erased && !BackTracked && isSafeToDelete(MI)) {
Evan Cheng52484682009-07-18 02:10:10 +00002377 InvalidateKills(MI, TRI, RegKills, KillOps);
2378 VRM.RemoveMachineInstrFromMaps(&MI);
2379 MBB.erase(&MI);
2380 Erased = true;
2381 }
2382 if (!Erased)
2383 DistanceMap.insert(std::make_pair(&MI, Dist++));
Lang Hames87e3bca2009-05-06 02:36:21 +00002384 if (!Erased && !BackTracked) {
2385 for (MachineBasicBlock::iterator II = &MI; II != NextMII; ++II)
Evan Cheng427a6b62009-05-15 06:48:19 +00002386 UpdateKills(*II, TRI, RegKills, KillOps);
Lang Hames87e3bca2009-05-06 02:36:21 +00002387 }
2388 MII = NextMII;
2389 }
2390
2391 }
2392
2393};
2394
Dan Gohman7db949d2009-08-07 01:32:21 +00002395}
2396
Lang Hames87e3bca2009-05-06 02:36:21 +00002397llvm::VirtRegRewriter* llvm::createVirtRegRewriter() {
2398 switch (RewriterOpt) {
Torok Edwinc23197a2009-07-14 16:55:14 +00002399 default: llvm_unreachable("Unreachable!");
Lang Hames87e3bca2009-05-06 02:36:21 +00002400 case local:
2401 return new LocalRewriter();
Lang Hamesf41538d2009-06-02 16:53:25 +00002402 case trivial:
2403 return new TrivialRewriter();
Lang Hames87e3bca2009-05-06 02:36:21 +00002404 }
2405}