1 //===- SSEDomainFix.cpp - Use proper int/float domain for SSE ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the SSEDomainFix pass.
12 // Some SSE instructions like mov, and, or, xor are available in different
13 // variants for different operand types. These variant instructions are
14 // equivalent, but on Nehalem and newer cpus there is extra latency
15 // transferring data between integer and floating point domains.
17 // This pass changes the variant instructions to minimize domain crossings.
19 //===----------------------------------------------------------------------===//
21 #define DEBUG_TYPE "sse-domain-fix"
22 #include "X86InstrInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/ADT/DepthFirstIterator.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
31 /// A DomainValue is a bit like LiveIntervals' ValNo, but it also keeps track
32 /// of execution domains.
34 /// An open DomainValue represents a set of instructions that can still switch
35 /// execution domain. Multiple registers may refer to the same open
36 /// DomainValue - they will eventually be collapsed to the same execution
39 /// A collapsed DomainValue represents a single register that has been forced
40 /// into one of more execution domains. There is a separate collapsed
41 /// DomainValue for each register, but it may contain multiple execution
42 /// domains. A register value is initially created in a single execution
43 /// domain, but if we were forced to pay the penalty of a domain crossing, we
44 /// keep track of the fact the the register is now available in multiple
48 // Basic reference counting.
51 // Bitmask of available domains. For an open DomainValue, it is the still
52 // possible domains for collapsing. For a collapsed DomainValue it is the
53 // domains where the register is available for free.
54 unsigned AvailableDomains;
56 // Position of the last defining instruction.
59 // Twiddleable instructions using or defining these registers.
60 SmallVector<MachineInstr*, 8> Instrs;
62 // A collapsed DomainValue has no instructions to twiddle - it simply keeps
63 // track of the domains where the registers are already available.
64 bool isCollapsed() const { return Instrs.empty(); }
66 // Is domain available?
67 bool hasDomain(unsigned domain) const {
68 return AvailableDomains & (1u << domain);
71 // Mark domain as available.
72 void addDomain(unsigned domain) {
73 AvailableDomains |= 1u << domain;
76 // Restrict to a single domain available.
77 void setSingleDomain(unsigned domain) {
78 AvailableDomains = 1u << domain;
81 // Return bitmask of domains that are available and in mask.
82 unsigned getCommonDomains(unsigned mask) const {
83 return AvailableDomains & mask;
86 // First domain available.
87 unsigned getFirstDomain() const {
88 return CountTrailingZeros_32(AvailableDomains);
91 DomainValue() { clear(); }
94 Refs = AvailableDomains = Dist = 0;
100 static const unsigned NumRegs = 16;
103 class SSEDomainFixPass : public MachineFunctionPass {
105 SpecificBumpPtrAllocator<DomainValue> Allocator;
106 SmallVector<DomainValue*,16> Avail;
109 const X86InstrInfo *TII;
110 const TargetRegisterInfo *TRI;
111 MachineBasicBlock *MBB;
112 DomainValue **LiveRegs;
113 typedef DenseMap<MachineBasicBlock*,DomainValue**> LiveOutMap;
118 SSEDomainFixPass() : MachineFunctionPass(&ID) {}
120 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
121 AU.setPreservesAll();
122 MachineFunctionPass::getAnalysisUsage(AU);
125 virtual bool runOnMachineFunction(MachineFunction &MF);
127 virtual const char *getPassName() const {
128 return "SSE execution domain fixup";
133 int RegIndex(unsigned Reg);
135 // DomainValue allocation.
136 DomainValue *Alloc(int domain = -1);
137 void Recycle(DomainValue*);
139 // LiveRegs manipulations.
140 void SetLiveReg(int rx, DomainValue *DV);
142 void Force(int rx, unsigned domain);
143 void Collapse(DomainValue *dv, unsigned domain);
144 bool Merge(DomainValue *A, DomainValue *B);
146 void enterBasicBlock();
147 void visitGenericInstr(MachineInstr*);
148 void visitSoftInstr(MachineInstr*, unsigned mask);
149 void visitHardInstr(MachineInstr*, unsigned domain);
153 char SSEDomainFixPass::ID = 0;
155 /// Translate TRI register number to an index into our smaller tables of
156 /// interesting registers. Return -1 for boring registers.
157 int SSEDomainFixPass::RegIndex(unsigned reg) {
158 // Registers are sorted lexicographically.
159 // We just need them to be consecutive, ordering doesn't matter.
160 assert(X86::XMM9 == X86::XMM0+NumRegs-1 && "Unexpected sort");
162 return reg < NumRegs ? reg : -1;
165 DomainValue *SSEDomainFixPass::Alloc(int domain) {
166 DomainValue *dv = Avail.empty() ?
167 new(Allocator.Allocate()) DomainValue :
168 Avail.pop_back_val();
171 dv->addDomain(domain);
175 void SSEDomainFixPass::Recycle(DomainValue *dv) {
176 assert(dv && "Cannot recycle NULL");
181 /// Set LiveRegs[rx] = dv, updating reference counts.
182 void SSEDomainFixPass::SetLiveReg(int rx, DomainValue *dv) {
183 assert(unsigned(rx) < NumRegs && "Invalid index");
185 LiveRegs = new DomainValue*[NumRegs];
186 std::fill(LiveRegs, LiveRegs+NumRegs, (DomainValue*)0);
189 if (LiveRegs[rx] == dv)
192 assert(LiveRegs[rx]->Refs && "Bad refcount");
193 if (--LiveRegs[rx]->Refs == 0) Recycle(LiveRegs[rx]);
199 // Kill register rx, recycle or collapse any DomainValue.
200 void SSEDomainFixPass::Kill(int rx) {
201 assert(unsigned(rx) < NumRegs && "Invalid index");
202 if (!LiveRegs || !LiveRegs[rx]) return;
204 // Before killing the last reference to an open DomainValue, collapse it to
205 // the first available domain.
206 if (LiveRegs[rx]->Refs == 1 && !LiveRegs[rx]->isCollapsed())
207 Collapse(LiveRegs[rx], LiveRegs[rx]->getFirstDomain());
212 /// Force register rx into domain.
213 void SSEDomainFixPass::Force(int rx, unsigned domain) {
214 assert(unsigned(rx) < NumRegs && "Invalid index");
216 if (LiveRegs && (dv = LiveRegs[rx])) {
217 if (dv->isCollapsed())
218 dv->addDomain(domain);
220 Collapse(dv, domain);
222 // Set up basic collapsed DomainValue.
223 SetLiveReg(rx, Alloc(domain));
227 /// Collapse open DomainValue into given domain. If there are multiple
228 /// registers using dv, they each get a unique collapsed DomainValue.
229 void SSEDomainFixPass::Collapse(DomainValue *dv, unsigned domain) {
230 assert(dv->hasDomain(domain) && "Cannot collapse");
232 // Collapse all the instructions.
233 while (!dv->Instrs.empty())
234 TII->SetSSEDomain(dv->Instrs.pop_back_val(), domain);
235 dv->setSingleDomain(domain);
237 // If there are multiple users, give them new, unique DomainValues.
238 if (LiveRegs && dv->Refs > 1)
239 for (unsigned rx = 0; rx != NumRegs; ++rx)
240 if (LiveRegs[rx] == dv)
241 SetLiveReg(rx, Alloc(domain));
244 /// Merge - All instructions and registers in B are moved to A, and B is
246 bool SSEDomainFixPass::Merge(DomainValue *A, DomainValue *B) {
247 assert(!A->isCollapsed() && "Cannot merge into collapsed");
248 assert(!B->isCollapsed() && "Cannot merge from collapsed");
251 // Restrict to the domains that A and B have in common.
252 unsigned common = A->getCommonDomains(B->AvailableDomains);
255 A->AvailableDomains = common;
256 A->Dist = std::max(A->Dist, B->Dist);
257 A->Instrs.append(B->Instrs.begin(), B->Instrs.end());
258 for (unsigned rx = 0; rx != NumRegs; ++rx)
259 if (LiveRegs[rx] == B)
264 void SSEDomainFixPass::enterBasicBlock() {
265 // Try to coalesce live-out registers from predecessors.
266 for (MachineBasicBlock::const_livein_iterator i = MBB->livein_begin(),
267 e = MBB->livein_end(); i != e; ++i) {
268 int rx = RegIndex(*i);
269 if (rx < 0) continue;
270 for (MachineBasicBlock::const_pred_iterator pi = MBB->pred_begin(),
271 pe = MBB->pred_end(); pi != pe; ++pi) {
272 LiveOutMap::const_iterator fi = LiveOuts.find(*pi);
273 if (fi == LiveOuts.end()) continue;
274 DomainValue *pdv = fi->second[rx];
276 if (!LiveRegs || !LiveRegs[rx]) {
281 // We have a live DomainValue from more than one predecessor.
282 if (LiveRegs[rx]->isCollapsed()) {
283 // We are already collapsed, but predecessor is not. Force him.
284 if (!pdv->isCollapsed())
285 Collapse(pdv, LiveRegs[rx]->getFirstDomain());
289 // Currently open, merge in predecessor.
290 if (!pdv->isCollapsed())
291 Merge(LiveRegs[rx], pdv);
293 Collapse(LiveRegs[rx], pdv->getFirstDomain());
298 // A hard instruction only works in one domain. All input registers will be
299 // forced into that domain.
300 void SSEDomainFixPass::visitHardInstr(MachineInstr *mi, unsigned domain) {
301 // Collapse all uses.
302 for (unsigned i = mi->getDesc().getNumDefs(),
303 e = mi->getDesc().getNumOperands(); i != e; ++i) {
304 MachineOperand &mo = mi->getOperand(i);
305 if (!mo.isReg()) continue;
306 int rx = RegIndex(mo.getReg());
307 if (rx < 0) continue;
311 // Kill all defs and force them.
312 for (unsigned i = 0, e = mi->getDesc().getNumDefs(); i != e; ++i) {
313 MachineOperand &mo = mi->getOperand(i);
314 if (!mo.isReg()) continue;
315 int rx = RegIndex(mo.getReg());
316 if (rx < 0) continue;
322 // A soft instruction can be changed to work in other domains given by mask.
323 void SSEDomainFixPass::visitSoftInstr(MachineInstr *mi, unsigned mask) {
324 // Bitmask of available domains for this instruction after taking collapsed
325 // operands into account.
326 unsigned available = mask;
328 // Scan the explicit use operands for incoming domains.
329 SmallVector<int, 4> used;
331 for (unsigned i = mi->getDesc().getNumDefs(),
332 e = mi->getDesc().getNumOperands(); i != e; ++i) {
333 MachineOperand &mo = mi->getOperand(i);
334 if (!mo.isReg()) continue;
335 int rx = RegIndex(mo.getReg());
336 if (rx < 0) continue;
337 if (DomainValue *dv = LiveRegs[rx]) {
338 // Bitmask of domains that dv and available have in common.
339 unsigned common = dv->getCommonDomains(available);
340 // Is it possible to use this collapsed register for free?
341 if (dv->isCollapsed()) {
342 // Restrict available domains to the ones in common with the operand.
343 // If there are no common domains, we must pay the cross-domain
344 // penalty for this operand.
345 if (common) available = common;
347 // Open DomainValue is compatible, save it for merging.
350 // Open DomainValue is not compatible with instruction. It is useless
356 // If the collapsed operands force a single domain, propagate the collapse.
357 if (isPowerOf2_32(available)) {
358 unsigned domain = CountTrailingZeros_32(available);
359 TII->SetSSEDomain(mi, domain);
360 visitHardInstr(mi, domain);
364 // Kill off any remaining uses that don't match available, and build a list of
365 // incoming DomainValues that we want to merge.
366 SmallVector<DomainValue*,4> doms;
367 for (SmallVector<int, 4>::iterator i=used.begin(), e=used.end(); i!=e; ++i) {
369 DomainValue *dv = LiveRegs[rx];
370 // This useless DomainValue could have been missed above.
371 if (!dv->getCommonDomains(available)) {
375 // sorted, uniqued insert.
376 bool inserted = false;
377 for (SmallVector<DomainValue*,4>::iterator i = doms.begin(), e = doms.end();
378 i != e && !inserted; ++i) {
381 else if (dv->Dist < (*i)->Dist) {
390 // doms are now sorted in order of appearance. Try to merge them all, giving
391 // priority to the latest ones.
393 while (!doms.empty()) {
395 dv = doms.pop_back_val();
399 DomainValue *latest = doms.pop_back_val();
400 if (Merge(dv, latest)) continue;
402 // If latest didn't merge, it is useless now. Kill all registers using it.
403 for (SmallVector<int,4>::iterator i=used.begin(), e=used.end(); i != e; ++i)
404 if (LiveRegs[*i] == latest)
408 // dv is the DomainValue we are going to use for this instruction.
412 dv->AvailableDomains = available;
413 dv->Instrs.push_back(mi);
415 // Finally set all defs and non-collapsed uses to dv.
416 for (unsigned i = 0, e = mi->getDesc().getNumOperands(); i != e; ++i) {
417 MachineOperand &mo = mi->getOperand(i);
418 if (!mo.isReg()) continue;
419 int rx = RegIndex(mo.getReg());
420 if (rx < 0) continue;
421 if (!LiveRegs || !LiveRegs[rx] || (mo.isDef() && LiveRegs[rx]!=dv)) {
428 void SSEDomainFixPass::visitGenericInstr(MachineInstr *mi) {
429 // Process explicit defs, kill any XMM registers redefined.
430 for (unsigned i = 0, e = mi->getDesc().getNumDefs(); i != e; ++i) {
431 MachineOperand &mo = mi->getOperand(i);
432 if (!mo.isReg()) continue;
433 int rx = RegIndex(mo.getReg());
434 if (rx < 0) continue;
439 bool SSEDomainFixPass::runOnMachineFunction(MachineFunction &mf) {
441 TII = static_cast<const X86InstrInfo*>(MF->getTarget().getInstrInfo());
442 TRI = MF->getTarget().getRegisterInfo();
446 assert(NumRegs == X86::VR128RegClass.getNumRegs() && "Bad regclass");
448 // If no XMM registers are used in the function, we can skip it completely.
449 bool anyregs = false;
450 for (TargetRegisterClass::const_iterator I = X86::VR128RegClass.begin(),
451 E = X86::VR128RegClass.end(); I != E; ++I)
452 if (MF->getRegInfo().isPhysRegUsed(*I)) {
456 if (!anyregs) return false;
458 MachineBasicBlock *Entry = MF->begin();
459 SmallPtrSet<MachineBasicBlock*, 16> Visited;
460 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 16> >
461 DFI = df_ext_begin(Entry, Visited), DFE = df_ext_end(Entry, Visited);
465 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end(); I != E;
467 MachineInstr *mi = I;
468 if (mi->isDebugValue()) continue;
470 std::pair<uint16_t, uint16_t> domp = TII->GetSSEDomain(mi);
473 visitSoftInstr(mi, domp.second);
475 visitHardInstr(mi, domp.first);
477 visitGenericInstr(mi);
480 // Save live registers at end of MBB - used by enterBasicBlock().
482 LiveOuts.insert(std::make_pair(MBB, LiveRegs));
486 // Clear the LiveOuts vectors. Should we also collapse any remaining
488 for (LiveOutMap::const_iterator i = LiveOuts.begin(), e = LiveOuts.end();
493 Allocator.DestroyAll();
498 FunctionPass *llvm::createSSEDomainFixPass() {
499 return new SSEDomainFixPass();