1 //===----------- PPCVSXSwapRemoval.cpp - Remove VSX LE Swaps -------------===//
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 pass analyzes vector computations and removes unnecessary
11 // doubleword swaps (xxswapd instructions). This pass is performed
12 // only for little-endian VSX code generation.
14 // For this specific case, loads and stores of v4i32, v4f32, v2i64,
15 // and v2f64 vectors are inefficient. These are implemented using
16 // the lxvd2x and stxvd2x instructions, which invert the order of
17 // doublewords in a vector register. Thus code generation inserts
18 // an xxswapd after each such load, and prior to each such store.
20 // The extra xxswapd instructions reduce performance. The purpose
21 // of this pass is to reduce the number of xxswapd instructions
22 // required for correctness.
24 // The primary insight is that much code that operates on vectors
25 // does not care about the relative order of elements in a register,
26 // so long as the correct memory order is preserved. If we have a
27 // computation where all input values are provided by lxvd2x/xxswapd,
28 // all outputs are stored using xxswapd/lxvd2x, and all intermediate
29 // computations are lane-insensitive (independent of element order),
30 // then all the xxswapd instructions associated with the loads and
31 // stores may be removed without changing observable semantics.
33 // This pass uses standard equivalence class infrastructure to create
34 // maximal webs of computations fitting the above description. Each
35 // such web is then optimized by removing its unnecessary xxswapd
38 // There are some lane-sensitive operations for which we can still
39 // permit the optimization, provided we modify those operations
40 // accordingly. Such operations are identified as using "special
41 // handling" within this module.
43 //===---------------------------------------------------------------------===//
46 #include "PPCInstrBuilder.h"
47 #include "PPCInstrInfo.h"
48 #include "PPCTargetMachine.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/EquivalenceClasses.h"
51 #include "llvm/CodeGen/MachineFunctionPass.h"
52 #include "llvm/CodeGen/MachineInstrBuilder.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/Config/llvm-config.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/Format.h"
57 #include "llvm/Support/raw_ostream.h"
61 #define DEBUG_TYPE "ppc-vsx-swaps"
64 void initializePPCVSXSwapRemovalPass(PassRegistry
&);
69 // A PPCVSXSwapEntry is created for each machine instruction that
70 // is relevant to a vector computation.
71 struct PPCVSXSwapEntry
{
72 // Pointer to the instruction.
75 // Unique ID (position in the swap vector).
78 // Attributes of this node.
79 unsigned int IsLoad
: 1;
80 unsigned int IsStore
: 1;
81 unsigned int IsSwap
: 1;
82 unsigned int MentionsPhysVR
: 1;
83 unsigned int IsSwappable
: 1;
84 unsigned int MentionsPartialVR
: 1;
85 unsigned int SpecialHandling
: 3;
86 unsigned int WebRejected
: 1;
87 unsigned int WillRemove
: 1;
101 struct PPCVSXSwapRemoval
: public MachineFunctionPass
{
104 const PPCInstrInfo
*TII
;
106 MachineRegisterInfo
*MRI
;
108 // Swap entries are allocated in a vector for better performance.
109 std::vector
<PPCVSXSwapEntry
> SwapVector
;
111 // A mapping is maintained between machine instructions and
112 // their swap entries. The key is the address of the MI.
113 DenseMap
<MachineInstr
*, int> SwapMap
;
115 // Equivalence classes are used to gather webs of related computation.
116 // Swap entries are represented by their VSEId fields.
117 EquivalenceClasses
<int> *EC
;
119 PPCVSXSwapRemoval() : MachineFunctionPass(ID
) {
120 initializePPCVSXSwapRemovalPass(*PassRegistry::getPassRegistry());
124 // Initialize data structures.
125 void initialize(MachineFunction
&MFParm
);
127 // Walk the machine instructions to gather vector usage information.
128 // Return true iff vector mentions are present.
129 bool gatherVectorInstructions();
131 // Add an entry to the swap vector and swap map.
132 int addSwapEntry(MachineInstr
*MI
, PPCVSXSwapEntry
&SwapEntry
);
134 // Hunt backwards through COPY and SUBREG_TO_REG chains for a
135 // source register. VecIdx indicates the swap vector entry to
136 // mark as mentioning a physical register if the search leads
138 unsigned lookThruCopyLike(unsigned SrcReg
, unsigned VecIdx
);
140 // Generate equivalence classes for related computations (webs).
143 // Analyze webs and determine those that cannot be optimized.
144 void recordUnoptimizableWebs();
146 // Record which swap instructions can be safely removed.
147 void markSwapsForRemoval();
149 // Remove swaps and update other instructions requiring special
150 // handling. Return true iff any changes are made.
153 // Insert a swap instruction from SrcReg to DstReg at the given
155 void insertSwap(MachineInstr
*MI
, MachineBasicBlock::iterator InsertPoint
,
156 unsigned DstReg
, unsigned SrcReg
);
158 // Update instructions requiring special handling.
159 void handleSpecialSwappables(int EntryIdx
);
161 // Dump a description of the entries in the swap vector.
162 void dumpSwapVector();
164 // Return true iff the given register is in the given class.
165 bool isRegInClass(unsigned Reg
, const TargetRegisterClass
*RC
) {
166 if (TargetRegisterInfo::isVirtualRegister(Reg
))
167 return RC
->hasSubClassEq(MRI
->getRegClass(Reg
));
168 return RC
->contains(Reg
);
171 // Return true iff the given register is a full vector register.
172 bool isVecReg(unsigned Reg
) {
173 return (isRegInClass(Reg
, &PPC::VSRCRegClass
) ||
174 isRegInClass(Reg
, &PPC::VRRCRegClass
));
177 // Return true iff the given register is a partial vector register.
178 bool isScalarVecReg(unsigned Reg
) {
179 return (isRegInClass(Reg
, &PPC::VSFRCRegClass
) ||
180 isRegInClass(Reg
, &PPC::VSSRCRegClass
));
183 // Return true iff the given register mentions all or part of a
184 // vector register. Also sets Partial to true if the mention
185 // is for just the floating-point register overlap of the register.
186 bool isAnyVecReg(unsigned Reg
, bool &Partial
) {
187 if (isScalarVecReg(Reg
))
189 return isScalarVecReg(Reg
) || isVecReg(Reg
);
193 // Main entry point for this pass.
194 bool runOnMachineFunction(MachineFunction
&MF
) override
{
195 if (skipFunction(MF
.getFunction()))
198 // If we don't have VSX on the subtarget, don't do anything.
199 // Also, on Power 9 the load and store ops preserve element order and so
200 // the swaps are not required.
201 const PPCSubtarget
&STI
= MF
.getSubtarget
<PPCSubtarget
>();
202 if (!STI
.hasVSX() || !STI
.needsSwapsForVSXMemOps())
205 bool Changed
= false;
208 if (gatherVectorInstructions()) {
210 recordUnoptimizableWebs();
211 markSwapsForRemoval();
212 Changed
= removeSwaps();
215 // FIXME: See the allocation of EC in initialize().
221 // Initialize data structures for this pass. In particular, clear the
222 // swap vector and allocate the equivalence class mapping before
223 // processing each function.
224 void PPCVSXSwapRemoval::initialize(MachineFunction
&MFParm
) {
226 MRI
= &MF
->getRegInfo();
227 TII
= MF
->getSubtarget
<PPCSubtarget
>().getInstrInfo();
229 // An initial vector size of 256 appears to work well in practice.
230 // Small/medium functions with vector content tend not to incur a
231 // reallocation at this size. Three of the vector tests in
232 // projects/test-suite reallocate, which seems like a reasonable rate.
233 const int InitialVectorSize(256);
235 SwapVector
.reserve(InitialVectorSize
);
237 // FIXME: Currently we allocate EC each time because we don't have
238 // access to the set representation on which to call clear(). Should
239 // consider adding a clear() method to the EquivalenceClasses class.
240 EC
= new EquivalenceClasses
<int>;
243 // Create an entry in the swap vector for each instruction that mentions
244 // a full vector register, recording various characteristics of the
245 // instructions there.
246 bool PPCVSXSwapRemoval::gatherVectorInstructions() {
247 bool RelevantFunction
= false;
249 for (MachineBasicBlock
&MBB
: *MF
) {
250 for (MachineInstr
&MI
: MBB
) {
252 if (MI
.isDebugInstr())
255 bool RelevantInstr
= false;
256 bool Partial
= false;
258 for (const MachineOperand
&MO
: MI
.operands()) {
261 unsigned Reg
= MO
.getReg();
262 if (isAnyVecReg(Reg
, Partial
)) {
263 RelevantInstr
= true;
271 RelevantFunction
= true;
273 // Create a SwapEntry initialized to zeros, then fill in the
274 // instruction and ID fields before pushing it to the back
275 // of the swap vector.
276 PPCVSXSwapEntry SwapEntry
{};
277 int VecIdx
= addSwapEntry(&MI
, SwapEntry
);
279 switch(MI
.getOpcode()) {
281 // Unless noted otherwise, an instruction is considered
282 // safe for the optimization. There are a large number of
283 // such true-SIMD instructions (all vector math, logical,
284 // select, compare, etc.). However, if the instruction
285 // mentions a partial vector register and does not have
286 // special handling defined, it is not swappable.
288 SwapVector
[VecIdx
].MentionsPartialVR
= 1;
290 SwapVector
[VecIdx
].IsSwappable
= 1;
292 case PPC::XXPERMDI
: {
293 // This is a swap if it is of the form XXPERMDI t, s, s, 2.
294 // Unfortunately, MachineCSE ignores COPY and SUBREG_TO_REG, so we
295 // can also see XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), 2,
296 // for example. We have to look through chains of COPY and
297 // SUBREG_TO_REG to find the real source value for comparison.
298 // If the real source value is a physical register, then mark the
299 // XXPERMDI as mentioning a physical register.
300 int immed
= MI
.getOperand(3).getImm();
302 unsigned trueReg1
= lookThruCopyLike(MI
.getOperand(1).getReg(),
304 unsigned trueReg2
= lookThruCopyLike(MI
.getOperand(2).getReg(),
306 if (trueReg1
== trueReg2
)
307 SwapVector
[VecIdx
].IsSwap
= 1;
309 // We can still handle these if the two registers are not
310 // identical, by adjusting the form of the XXPERMDI.
311 SwapVector
[VecIdx
].IsSwappable
= 1;
312 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_XXPERMDI
;
314 // This is a doubleword splat if it is of the form
315 // XXPERMDI t, s, s, 0 or XXPERMDI t, s, s, 3. As above we
316 // must look through chains of copy-likes to find the source
317 // register. We turn off the marking for mention of a physical
318 // register, because splatting it is safe; the optimization
319 // will not swap the value in the physical register. Whether
320 // or not the two input registers are identical, we can handle
321 // these by adjusting the form of the XXPERMDI.
322 } else if (immed
== 0 || immed
== 3) {
324 SwapVector
[VecIdx
].IsSwappable
= 1;
325 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_XXPERMDI
;
327 unsigned trueReg1
= lookThruCopyLike(MI
.getOperand(1).getReg(),
329 unsigned trueReg2
= lookThruCopyLike(MI
.getOperand(2).getReg(),
331 if (trueReg1
== trueReg2
)
332 SwapVector
[VecIdx
].MentionsPhysVR
= 0;
335 // We can still handle these by adjusting the form of the XXPERMDI.
336 SwapVector
[VecIdx
].IsSwappable
= 1;
337 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_XXPERMDI
;
342 // Non-permuting loads are currently unsafe. We can use special
343 // handling for this in the future. By not marking these as
344 // IsSwap, we ensure computations containing them will be rejected
346 SwapVector
[VecIdx
].IsLoad
= 1;
350 // Permuting loads are marked as both load and swap, and are
351 // safe for optimization.
352 SwapVector
[VecIdx
].IsLoad
= 1;
353 SwapVector
[VecIdx
].IsSwap
= 1;
359 // A load of a floating-point value into the high-order half of
360 // a vector register is safe, provided that we introduce a swap
361 // following the load, which will be done by the SUBREG_TO_REG
362 // support. So just mark these as safe.
363 SwapVector
[VecIdx
].IsLoad
= 1;
364 SwapVector
[VecIdx
].IsSwappable
= 1;
367 // Non-permuting stores are currently unsafe. We can use special
368 // handling for this in the future. By not marking these as
369 // IsSwap, we ensure computations containing them will be rejected
371 SwapVector
[VecIdx
].IsStore
= 1;
375 // Permuting stores are marked as both store and swap, and are
376 // safe for optimization.
377 SwapVector
[VecIdx
].IsStore
= 1;
378 SwapVector
[VecIdx
].IsSwap
= 1;
381 // These are fine provided they are moving between full vector
383 if (isVecReg(MI
.getOperand(0).getReg()) &&
384 isVecReg(MI
.getOperand(1).getReg()))
385 SwapVector
[VecIdx
].IsSwappable
= 1;
386 // If we have a copy from one scalar floating-point register
387 // to another, we can accept this even if it is a physical
388 // register. The only way this gets involved is if it feeds
389 // a SUBREG_TO_REG, which is handled by introducing a swap.
390 else if (isScalarVecReg(MI
.getOperand(0).getReg()) &&
391 isScalarVecReg(MI
.getOperand(1).getReg()))
392 SwapVector
[VecIdx
].IsSwappable
= 1;
394 case PPC::SUBREG_TO_REG
: {
395 // These are fine provided they are moving between full vector
396 // register classes. If they are moving from a scalar
397 // floating-point class to a vector class, we can handle those
398 // as well, provided we introduce a swap. It is generally the
399 // case that we will introduce fewer swaps than we remove, but
400 // (FIXME) a cost model could be used. However, introduced
401 // swaps could potentially be CSEd, so this is not trivial.
402 if (isVecReg(MI
.getOperand(0).getReg()) &&
403 isVecReg(MI
.getOperand(2).getReg()))
404 SwapVector
[VecIdx
].IsSwappable
= 1;
405 else if (isVecReg(MI
.getOperand(0).getReg()) &&
406 isScalarVecReg(MI
.getOperand(2).getReg())) {
407 SwapVector
[VecIdx
].IsSwappable
= 1;
408 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_COPYWIDEN
;
416 // Splats are lane-sensitive, but we can use special handling
417 // to adjust the source lane for the splat.
418 SwapVector
[VecIdx
].IsSwappable
= 1;
419 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_SPLAT
;
421 // The presence of the following lane-sensitive operations in a
422 // web will kill the optimization, at least for now. For these
423 // we do nothing, causing the optimization to fail.
424 // FIXME: Some of these could be permitted with special handling,
425 // and will be phased in as time permits.
426 // FIXME: There is no simple and maintainable way to express a set
427 // of opcodes having a common attribute in TableGen. Should this
428 // change, this is a prime candidate to use such a mechanism.
430 case PPC::EXTRACT_SUBREG
:
431 case PPC::INSERT_SUBREG
:
432 case PPC::COPY_TO_REGCLASS
:
443 // We can handle STXSDX and STXSSPX similarly to LXSDX and LXSSPX,
444 // by adding special handling for narrowing copies as well as
445 // widening ones. However, I've experimented with this, and in
446 // practice we currently do not appear to use STXSDX fed by
447 // a narrowing copy from a full vector register. Since I can't
448 // generate any useful test cases, I've left this alone for now.
452 case PPC::VCIPHERLAST
:
472 case PPC::VNCIPHERLAST
:
497 case PPC::VSHASIGMAD
:
498 case PPC::VSHASIGMAW
:
519 // XXSLDWI could be replaced by a general permute with one of three
520 // permute control vectors (for shift values 1, 2, 3). However,
521 // VPERM has a more restrictive register class.
530 if (RelevantFunction
) {
531 LLVM_DEBUG(dbgs() << "Swap vector when first built\n\n");
532 LLVM_DEBUG(dumpSwapVector());
535 return RelevantFunction
;
538 // Add an entry to the swap vector and swap map, and make a
539 // singleton equivalence class for the entry.
540 int PPCVSXSwapRemoval::addSwapEntry(MachineInstr
*MI
,
541 PPCVSXSwapEntry
& SwapEntry
) {
542 SwapEntry
.VSEMI
= MI
;
543 SwapEntry
.VSEId
= SwapVector
.size();
544 SwapVector
.push_back(SwapEntry
);
545 EC
->insert(SwapEntry
.VSEId
);
546 SwapMap
[MI
] = SwapEntry
.VSEId
;
547 return SwapEntry
.VSEId
;
550 // This is used to find the "true" source register for an
551 // XXPERMDI instruction, since MachineCSE does not handle the
552 // "copy-like" operations (Copy and SubregToReg). Returns
553 // the original SrcReg unless it is the target of a copy-like
554 // operation, in which case we chain backwards through all
555 // such operations to the ultimate source register. If a
556 // physical register is encountered, we stop the search and
557 // flag the swap entry indicated by VecIdx (the original
558 // XXPERMDI) as mentioning a physical register.
559 unsigned PPCVSXSwapRemoval::lookThruCopyLike(unsigned SrcReg
,
561 MachineInstr
*MI
= MRI
->getVRegDef(SrcReg
);
562 if (!MI
->isCopyLike())
567 CopySrcReg
= MI
->getOperand(1).getReg();
569 assert(MI
->isSubregToReg() && "bad opcode for lookThruCopyLike");
570 CopySrcReg
= MI
->getOperand(2).getReg();
573 if (!TargetRegisterInfo::isVirtualRegister(CopySrcReg
)) {
574 if (!isScalarVecReg(CopySrcReg
))
575 SwapVector
[VecIdx
].MentionsPhysVR
= 1;
579 return lookThruCopyLike(CopySrcReg
, VecIdx
);
582 // Generate equivalence classes for related computations (webs) by
583 // def-use relationships of virtual registers. Mention of a physical
584 // register terminates the generation of equivalence classes as this
585 // indicates a use of a parameter, definition of a return value, use
586 // of a value returned from a call, or definition of a parameter to a
587 // call. Computations with physical register mentions are flagged
588 // as such so their containing webs will not be optimized.
589 void PPCVSXSwapRemoval::formWebs() {
591 LLVM_DEBUG(dbgs() << "\n*** Forming webs for swap removal ***\n\n");
593 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
595 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
597 LLVM_DEBUG(dbgs() << "\n" << SwapVector
[EntryIdx
].VSEId
<< " ");
598 LLVM_DEBUG(MI
->dump());
600 // It's sufficient to walk vector uses and join them to their unique
601 // definitions. In addition, check full vector register operands
602 // for physical regs. We exclude partial-vector register operands
603 // because we can handle them if copied to a full vector.
604 for (const MachineOperand
&MO
: MI
->operands()) {
608 unsigned Reg
= MO
.getReg();
609 if (!isVecReg(Reg
) && !isScalarVecReg(Reg
))
612 if (!TargetRegisterInfo::isVirtualRegister(Reg
)) {
613 if (!(MI
->isCopy() && isScalarVecReg(Reg
)))
614 SwapVector
[EntryIdx
].MentionsPhysVR
= 1;
621 MachineInstr
* DefMI
= MRI
->getVRegDef(Reg
);
622 assert(SwapMap
.find(DefMI
) != SwapMap
.end() &&
623 "Inconsistency: def of vector reg not found in swap map!");
624 int DefIdx
= SwapMap
[DefMI
];
625 (void)EC
->unionSets(SwapVector
[DefIdx
].VSEId
,
626 SwapVector
[EntryIdx
].VSEId
);
628 LLVM_DEBUG(dbgs() << format("Unioning %d with %d\n",
629 SwapVector
[DefIdx
].VSEId
,
630 SwapVector
[EntryIdx
].VSEId
));
631 LLVM_DEBUG(dbgs() << " Def: ");
632 LLVM_DEBUG(DefMI
->dump());
637 // Walk the swap vector entries looking for conditions that prevent their
638 // containing computations from being optimized. When such conditions are
639 // found, mark the representative of the computation's equivalence class
641 void PPCVSXSwapRemoval::recordUnoptimizableWebs() {
643 LLVM_DEBUG(dbgs() << "\n*** Rejecting webs for swap removal ***\n\n");
645 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
646 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
648 // If representative is already rejected, don't waste further time.
649 if (SwapVector
[Repr
].WebRejected
)
652 // Reject webs containing mentions of physical or partial registers, or
653 // containing operations that we don't know how to handle in a lane-
655 if (SwapVector
[EntryIdx
].MentionsPhysVR
||
656 SwapVector
[EntryIdx
].MentionsPartialVR
||
657 !(SwapVector
[EntryIdx
].IsSwappable
|| SwapVector
[EntryIdx
].IsSwap
)) {
659 SwapVector
[Repr
].WebRejected
= 1;
662 dbgs() << format("Web %d rejected for physreg, partial reg, or not "
665 LLVM_DEBUG(dbgs() << " in " << EntryIdx
<< ": ");
666 LLVM_DEBUG(SwapVector
[EntryIdx
].VSEMI
->dump());
667 LLVM_DEBUG(dbgs() << "\n");
670 // Reject webs than contain swapping loads that feed something other
671 // than a swap instruction.
672 else if (SwapVector
[EntryIdx
].IsLoad
&& SwapVector
[EntryIdx
].IsSwap
) {
673 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
674 unsigned DefReg
= MI
->getOperand(0).getReg();
676 // We skip debug instructions in the analysis. (Note that debug
677 // location information is still maintained by this optimization
678 // because it remains on the LXVD2X and STXVD2X instructions after
679 // the XXPERMDIs are removed.)
680 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(DefReg
)) {
681 int UseIdx
= SwapMap
[&UseMI
];
683 if (!SwapVector
[UseIdx
].IsSwap
|| SwapVector
[UseIdx
].IsLoad
||
684 SwapVector
[UseIdx
].IsStore
) {
686 SwapVector
[Repr
].WebRejected
= 1;
688 LLVM_DEBUG(dbgs() << format(
689 "Web %d rejected for load not feeding swap\n", Repr
));
690 LLVM_DEBUG(dbgs() << " def " << EntryIdx
<< ": ");
691 LLVM_DEBUG(MI
->dump());
692 LLVM_DEBUG(dbgs() << " use " << UseIdx
<< ": ");
693 LLVM_DEBUG(UseMI
.dump());
694 LLVM_DEBUG(dbgs() << "\n");
698 // Reject webs that contain swapping stores that are fed by something
699 // other than a swap instruction.
700 } else if (SwapVector
[EntryIdx
].IsStore
&& SwapVector
[EntryIdx
].IsSwap
) {
701 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
702 unsigned UseReg
= MI
->getOperand(0).getReg();
703 MachineInstr
*DefMI
= MRI
->getVRegDef(UseReg
);
704 unsigned DefReg
= DefMI
->getOperand(0).getReg();
705 int DefIdx
= SwapMap
[DefMI
];
707 if (!SwapVector
[DefIdx
].IsSwap
|| SwapVector
[DefIdx
].IsLoad
||
708 SwapVector
[DefIdx
].IsStore
) {
710 SwapVector
[Repr
].WebRejected
= 1;
712 LLVM_DEBUG(dbgs() << format(
713 "Web %d rejected for store not fed by swap\n", Repr
));
714 LLVM_DEBUG(dbgs() << " def " << DefIdx
<< ": ");
715 LLVM_DEBUG(DefMI
->dump());
716 LLVM_DEBUG(dbgs() << " use " << EntryIdx
<< ": ");
717 LLVM_DEBUG(MI
->dump());
718 LLVM_DEBUG(dbgs() << "\n");
721 // Ensure all uses of the register defined by DefMI feed store
723 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(DefReg
)) {
724 int UseIdx
= SwapMap
[&UseMI
];
726 if (SwapVector
[UseIdx
].VSEMI
->getOpcode() != MI
->getOpcode()) {
727 SwapVector
[Repr
].WebRejected
= 1;
731 "Web %d rejected for swap not feeding only stores\n", Repr
));
732 LLVM_DEBUG(dbgs() << " def "
734 LLVM_DEBUG(DefMI
->dump());
735 LLVM_DEBUG(dbgs() << " use " << UseIdx
<< ": ");
736 LLVM_DEBUG(SwapVector
[UseIdx
].VSEMI
->dump());
737 LLVM_DEBUG(dbgs() << "\n");
743 LLVM_DEBUG(dbgs() << "Swap vector after web analysis:\n\n");
744 LLVM_DEBUG(dumpSwapVector());
747 // Walk the swap vector entries looking for swaps fed by permuting loads
748 // and swaps that feed permuting stores. If the containing computation
749 // has not been marked rejected, mark each such swap for removal.
750 // (Removal is delayed in case optimization has disturbed the pattern,
751 // such that multiple loads feed the same swap, etc.)
752 void PPCVSXSwapRemoval::markSwapsForRemoval() {
754 LLVM_DEBUG(dbgs() << "\n*** Marking swaps for removal ***\n\n");
756 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
758 if (SwapVector
[EntryIdx
].IsLoad
&& SwapVector
[EntryIdx
].IsSwap
) {
759 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
761 if (!SwapVector
[Repr
].WebRejected
) {
762 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
763 unsigned DefReg
= MI
->getOperand(0).getReg();
765 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(DefReg
)) {
766 int UseIdx
= SwapMap
[&UseMI
];
767 SwapVector
[UseIdx
].WillRemove
= 1;
769 LLVM_DEBUG(dbgs() << "Marking swap fed by load for removal: ");
770 LLVM_DEBUG(UseMI
.dump());
774 } else if (SwapVector
[EntryIdx
].IsStore
&& SwapVector
[EntryIdx
].IsSwap
) {
775 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
777 if (!SwapVector
[Repr
].WebRejected
) {
778 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
779 unsigned UseReg
= MI
->getOperand(0).getReg();
780 MachineInstr
*DefMI
= MRI
->getVRegDef(UseReg
);
781 int DefIdx
= SwapMap
[DefMI
];
782 SwapVector
[DefIdx
].WillRemove
= 1;
784 LLVM_DEBUG(dbgs() << "Marking swap feeding store for removal: ");
785 LLVM_DEBUG(DefMI
->dump());
788 } else if (SwapVector
[EntryIdx
].IsSwappable
&&
789 SwapVector
[EntryIdx
].SpecialHandling
!= 0) {
790 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
792 if (!SwapVector
[Repr
].WebRejected
)
793 handleSpecialSwappables(EntryIdx
);
798 // Create an xxswapd instruction and insert it prior to the given point.
799 // MI is used to determine basic block and debug loc information.
800 // FIXME: When inserting a swap, we should check whether SrcReg is
801 // defined by another swap: SrcReg = XXPERMDI Reg, Reg, 2; If so,
802 // then instead we should generate a copy from Reg to DstReg.
803 void PPCVSXSwapRemoval::insertSwap(MachineInstr
*MI
,
804 MachineBasicBlock::iterator InsertPoint
,
805 unsigned DstReg
, unsigned SrcReg
) {
806 BuildMI(*MI
->getParent(), InsertPoint
, MI
->getDebugLoc(),
807 TII
->get(PPC::XXPERMDI
), DstReg
)
813 // The identified swap entry requires special handling to allow its
814 // containing computation to be optimized. Perform that handling
816 // FIXME: Additional opportunities will be phased in with subsequent
818 void PPCVSXSwapRemoval::handleSpecialSwappables(int EntryIdx
) {
819 switch (SwapVector
[EntryIdx
].SpecialHandling
) {
822 llvm_unreachable("Unexpected special handling type");
824 // For splats based on an index into a vector, add N/2 modulo N
825 // to the index, where N is the number of vector elements.
826 case SHValues::SH_SPLAT
: {
827 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
830 LLVM_DEBUG(dbgs() << "Changing splat: ");
831 LLVM_DEBUG(MI
->dump());
833 switch (MI
->getOpcode()) {
835 llvm_unreachable("Unexpected splat opcode");
836 case PPC::VSPLTB
: NElts
= 16; break;
837 case PPC::VSPLTH
: NElts
= 8; break;
839 case PPC::XXSPLTW
: NElts
= 4; break;
843 if (MI
->getOpcode() == PPC::XXSPLTW
)
844 EltNo
= MI
->getOperand(2).getImm();
846 EltNo
= MI
->getOperand(1).getImm();
848 EltNo
= (EltNo
+ NElts
/ 2) % NElts
;
849 if (MI
->getOpcode() == PPC::XXSPLTW
)
850 MI
->getOperand(2).setImm(EltNo
);
852 MI
->getOperand(1).setImm(EltNo
);
854 LLVM_DEBUG(dbgs() << " Into: ");
855 LLVM_DEBUG(MI
->dump());
859 // For an XXPERMDI that isn't handled otherwise, we need to
860 // reverse the order of the operands. If the selector operand
861 // has a value of 0 or 3, we need to change it to 3 or 0,
862 // respectively. Otherwise we should leave it alone. (This
863 // is equivalent to reversing the two bits of the selector
864 // operand and complementing the result.)
865 case SHValues::SH_XXPERMDI
: {
866 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
868 LLVM_DEBUG(dbgs() << "Changing XXPERMDI: ");
869 LLVM_DEBUG(MI
->dump());
871 unsigned Selector
= MI
->getOperand(3).getImm();
872 if (Selector
== 0 || Selector
== 3)
873 Selector
= 3 - Selector
;
874 MI
->getOperand(3).setImm(Selector
);
876 unsigned Reg1
= MI
->getOperand(1).getReg();
877 unsigned Reg2
= MI
->getOperand(2).getReg();
878 MI
->getOperand(1).setReg(Reg2
);
879 MI
->getOperand(2).setReg(Reg1
);
881 // We also need to swap kill flag associated with the register.
882 bool IsKill1
= MI
->getOperand(1).isKill();
883 bool IsKill2
= MI
->getOperand(2).isKill();
884 MI
->getOperand(1).setIsKill(IsKill2
);
885 MI
->getOperand(2).setIsKill(IsKill1
);
887 LLVM_DEBUG(dbgs() << " Into: ");
888 LLVM_DEBUG(MI
->dump());
892 // For a copy from a scalar floating-point register to a vector
893 // register, removing swaps will leave the copied value in the
894 // wrong lane. Insert a swap following the copy to fix this.
895 case SHValues::SH_COPYWIDEN
: {
896 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
898 LLVM_DEBUG(dbgs() << "Changing SUBREG_TO_REG: ");
899 LLVM_DEBUG(MI
->dump());
901 unsigned DstReg
= MI
->getOperand(0).getReg();
902 const TargetRegisterClass
*DstRC
= MRI
->getRegClass(DstReg
);
903 unsigned NewVReg
= MRI
->createVirtualRegister(DstRC
);
905 MI
->getOperand(0).setReg(NewVReg
);
906 LLVM_DEBUG(dbgs() << " Into: ");
907 LLVM_DEBUG(MI
->dump());
909 auto InsertPoint
= ++MachineBasicBlock::iterator(MI
);
911 // Note that an XXPERMDI requires a VSRC, so if the SUBREG_TO_REG
912 // is copying to a VRRC, we need to be careful to avoid a register
913 // assignment problem. In this case we must copy from VRRC to VSRC
914 // prior to the swap, and from VSRC to VRRC following the swap.
915 // Coalescing will usually remove all this mess.
916 if (DstRC
== &PPC::VRRCRegClass
) {
917 unsigned VSRCTmp1
= MRI
->createVirtualRegister(&PPC::VSRCRegClass
);
918 unsigned VSRCTmp2
= MRI
->createVirtualRegister(&PPC::VSRCRegClass
);
920 BuildMI(*MI
->getParent(), InsertPoint
, MI
->getDebugLoc(),
921 TII
->get(PPC::COPY
), VSRCTmp1
)
923 LLVM_DEBUG(std::prev(InsertPoint
)->dump());
925 insertSwap(MI
, InsertPoint
, VSRCTmp2
, VSRCTmp1
);
926 LLVM_DEBUG(std::prev(InsertPoint
)->dump());
928 BuildMI(*MI
->getParent(), InsertPoint
, MI
->getDebugLoc(),
929 TII
->get(PPC::COPY
), DstReg
)
931 LLVM_DEBUG(std::prev(InsertPoint
)->dump());
934 insertSwap(MI
, InsertPoint
, DstReg
, NewVReg
);
935 LLVM_DEBUG(std::prev(InsertPoint
)->dump());
942 // Walk the swap vector and replace each entry marked for removal with
944 bool PPCVSXSwapRemoval::removeSwaps() {
946 LLVM_DEBUG(dbgs() << "\n*** Removing swaps ***\n\n");
948 bool Changed
= false;
950 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
951 if (SwapVector
[EntryIdx
].WillRemove
) {
953 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
954 MachineBasicBlock
*MBB
= MI
->getParent();
955 BuildMI(*MBB
, MI
, MI
->getDebugLoc(), TII
->get(TargetOpcode::COPY
),
956 MI
->getOperand(0).getReg())
957 .add(MI
->getOperand(1));
959 LLVM_DEBUG(dbgs() << format("Replaced %d with copy: ",
960 SwapVector
[EntryIdx
].VSEId
));
961 LLVM_DEBUG(MI
->dump());
963 MI
->eraseFromParent();
970 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
971 // For debug purposes, dump the contents of the swap vector.
972 LLVM_DUMP_METHOD
void PPCVSXSwapRemoval::dumpSwapVector() {
974 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
976 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
977 int ID
= SwapVector
[EntryIdx
].VSEId
;
979 dbgs() << format("%6d", ID
);
980 dbgs() << format("%6d", EC
->getLeaderValue(ID
));
981 dbgs() << format(" %bb.%3d", MI
->getParent()->getNumber());
982 dbgs() << format(" %14s ", TII
->getName(MI
->getOpcode()).str().c_str());
984 if (SwapVector
[EntryIdx
].IsLoad
)
986 if (SwapVector
[EntryIdx
].IsStore
)
988 if (SwapVector
[EntryIdx
].IsSwap
)
990 if (SwapVector
[EntryIdx
].MentionsPhysVR
)
991 dbgs() << "physreg ";
992 if (SwapVector
[EntryIdx
].MentionsPartialVR
)
993 dbgs() << "partialreg ";
995 if (SwapVector
[EntryIdx
].IsSwappable
) {
996 dbgs() << "swappable ";
997 switch(SwapVector
[EntryIdx
].SpecialHandling
) {
999 dbgs() << "special:**unknown**";
1004 dbgs() << "special:extract ";
1007 dbgs() << "special:insert ";
1010 dbgs() << "special:load ";
1013 dbgs() << "special:store ";
1016 dbgs() << "special:splat ";
1019 dbgs() << "special:xxpermdi ";
1022 dbgs() << "special:copywiden ";
1027 if (SwapVector
[EntryIdx
].WebRejected
)
1028 dbgs() << "rejected ";
1029 if (SwapVector
[EntryIdx
].WillRemove
)
1030 dbgs() << "remove ";
1034 // For no-asserts builds.
1043 } // end default namespace
1045 INITIALIZE_PASS_BEGIN(PPCVSXSwapRemoval
, DEBUG_TYPE
,
1046 "PowerPC VSX Swap Removal", false, false)
1047 INITIALIZE_PASS_END(PPCVSXSwapRemoval
, DEBUG_TYPE
,
1048 "PowerPC VSX Swap Removal", false, false)
1050 char PPCVSXSwapRemoval::ID
= 0;
1052 llvm::createPPCVSXSwapRemovalPass() { return new PPCVSXSwapRemoval(); }