1 //===----------- PPCVSXSwapRemoval.cpp - Remove VSX LE Swaps -------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===---------------------------------------------------------------------===//
9 // This pass analyzes vector computations and removes unnecessary
10 // doubleword swaps (xxswapd instructions). This pass is performed
11 // only for little-endian VSX code generation.
13 // For this specific case, loads and stores of v4i32, v4f32, v2i64,
14 // and v2f64 vectors are inefficient. These are implemented using
15 // the lxvd2x and stxvd2x instructions, which invert the order of
16 // doublewords in a vector register. Thus code generation inserts
17 // an xxswapd after each such load, and prior to each such store.
19 // The extra xxswapd instructions reduce performance. The purpose
20 // of this pass is to reduce the number of xxswapd instructions
21 // required for correctness.
23 // The primary insight is that much code that operates on vectors
24 // does not care about the relative order of elements in a register,
25 // so long as the correct memory order is preserved. If we have a
26 // computation where all input values are provided by lxvd2x/xxswapd,
27 // all outputs are stored using xxswapd/lxvd2x, and all intermediate
28 // computations are lane-insensitive (independent of element order),
29 // then all the xxswapd instructions associated with the loads and
30 // stores may be removed without changing observable semantics.
32 // This pass uses standard equivalence class infrastructure to create
33 // maximal webs of computations fitting the above description. Each
34 // such web is then optimized by removing its unnecessary xxswapd
37 // There are some lane-sensitive operations for which we can still
38 // permit the optimization, provided we modify those operations
39 // accordingly. Such operations are identified as using "special
40 // handling" within this module.
42 //===---------------------------------------------------------------------===//
45 #include "PPCInstrInfo.h"
46 #include "PPCTargetMachine.h"
47 #include "llvm/ADT/DenseMap.h"
48 #include "llvm/ADT/EquivalenceClasses.h"
49 #include "llvm/CodeGen/MachineFunctionPass.h"
50 #include "llvm/CodeGen/MachineInstrBuilder.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/Config/llvm-config.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/Format.h"
55 #include "llvm/Support/raw_ostream.h"
59 #define DEBUG_TYPE "ppc-vsx-swaps"
63 // A PPCVSXSwapEntry is created for each machine instruction that
64 // is relevant to a vector computation.
65 struct PPCVSXSwapEntry
{
66 // Pointer to the instruction.
69 // Unique ID (position in the swap vector).
72 // Attributes of this node.
73 unsigned int IsLoad
: 1;
74 unsigned int IsStore
: 1;
75 unsigned int IsSwap
: 1;
76 unsigned int MentionsPhysVR
: 1;
77 unsigned int IsSwappable
: 1;
78 unsigned int MentionsPartialVR
: 1;
79 unsigned int SpecialHandling
: 3;
80 unsigned int WebRejected
: 1;
81 unsigned int WillRemove
: 1;
95 struct PPCVSXSwapRemoval
: public MachineFunctionPass
{
98 const PPCInstrInfo
*TII
;
100 MachineRegisterInfo
*MRI
;
102 // Swap entries are allocated in a vector for better performance.
103 std::vector
<PPCVSXSwapEntry
> SwapVector
;
105 // A mapping is maintained between machine instructions and
106 // their swap entries. The key is the address of the MI.
107 DenseMap
<MachineInstr
*, int> SwapMap
;
109 // Equivalence classes are used to gather webs of related computation.
110 // Swap entries are represented by their VSEId fields.
111 EquivalenceClasses
<int> *EC
;
113 PPCVSXSwapRemoval() : MachineFunctionPass(ID
) {
114 initializePPCVSXSwapRemovalPass(*PassRegistry::getPassRegistry());
118 // Initialize data structures.
119 void initialize(MachineFunction
&MFParm
);
121 // Walk the machine instructions to gather vector usage information.
122 // Return true iff vector mentions are present.
123 bool gatherVectorInstructions();
125 // Add an entry to the swap vector and swap map.
126 int addSwapEntry(MachineInstr
*MI
, PPCVSXSwapEntry
&SwapEntry
);
128 // Hunt backwards through COPY and SUBREG_TO_REG chains for a
129 // source register. VecIdx indicates the swap vector entry to
130 // mark as mentioning a physical register if the search leads
132 unsigned lookThruCopyLike(unsigned SrcReg
, unsigned VecIdx
);
134 // Generate equivalence classes for related computations (webs).
137 // Analyze webs and determine those that cannot be optimized.
138 void recordUnoptimizableWebs();
140 // Record which swap instructions can be safely removed.
141 void markSwapsForRemoval();
143 // Remove swaps and update other instructions requiring special
144 // handling. Return true iff any changes are made.
147 // Insert a swap instruction from SrcReg to DstReg at the given
149 void insertSwap(MachineInstr
*MI
, MachineBasicBlock::iterator InsertPoint
,
150 unsigned DstReg
, unsigned SrcReg
);
152 // Update instructions requiring special handling.
153 void handleSpecialSwappables(int EntryIdx
);
155 // Dump a description of the entries in the swap vector.
156 void dumpSwapVector();
158 // Return true iff the given register is in the given class.
159 bool isRegInClass(unsigned Reg
, const TargetRegisterClass
*RC
) {
160 if (Register::isVirtualRegister(Reg
))
161 return RC
->hasSubClassEq(MRI
->getRegClass(Reg
));
162 return RC
->contains(Reg
);
165 // Return true iff the given register is a full vector register.
166 bool isVecReg(unsigned Reg
) {
167 return (isRegInClass(Reg
, &PPC::VSRCRegClass
) ||
168 isRegInClass(Reg
, &PPC::VRRCRegClass
));
171 // Return true iff the given register is a partial vector register.
172 bool isScalarVecReg(unsigned Reg
) {
173 return (isRegInClass(Reg
, &PPC::VSFRCRegClass
) ||
174 isRegInClass(Reg
, &PPC::VSSRCRegClass
));
177 // Return true iff the given register mentions all or part of a
178 // vector register. Also sets Partial to true if the mention
179 // is for just the floating-point register overlap of the register.
180 bool isAnyVecReg(unsigned Reg
, bool &Partial
) {
181 if (isScalarVecReg(Reg
))
183 return isScalarVecReg(Reg
) || isVecReg(Reg
);
187 // Main entry point for this pass.
188 bool runOnMachineFunction(MachineFunction
&MF
) override
{
189 if (skipFunction(MF
.getFunction()))
192 // If we don't have VSX on the subtarget, don't do anything.
193 // Also, on Power 9 the load and store ops preserve element order and so
194 // the swaps are not required.
195 const PPCSubtarget
&STI
= MF
.getSubtarget
<PPCSubtarget
>();
196 if (!STI
.hasVSX() || !STI
.needsSwapsForVSXMemOps())
199 bool Changed
= false;
202 if (gatherVectorInstructions()) {
204 recordUnoptimizableWebs();
205 markSwapsForRemoval();
206 Changed
= removeSwaps();
209 // FIXME: See the allocation of EC in initialize().
215 // Initialize data structures for this pass. In particular, clear the
216 // swap vector and allocate the equivalence class mapping before
217 // processing each function.
218 void PPCVSXSwapRemoval::initialize(MachineFunction
&MFParm
) {
220 MRI
= &MF
->getRegInfo();
221 TII
= MF
->getSubtarget
<PPCSubtarget
>().getInstrInfo();
223 // An initial vector size of 256 appears to work well in practice.
224 // Small/medium functions with vector content tend not to incur a
225 // reallocation at this size. Three of the vector tests in
226 // projects/test-suite reallocate, which seems like a reasonable rate.
227 const int InitialVectorSize(256);
229 SwapVector
.reserve(InitialVectorSize
);
231 // FIXME: Currently we allocate EC each time because we don't have
232 // access to the set representation on which to call clear(). Should
233 // consider adding a clear() method to the EquivalenceClasses class.
234 EC
= new EquivalenceClasses
<int>;
237 // Create an entry in the swap vector for each instruction that mentions
238 // a full vector register, recording various characteristics of the
239 // instructions there.
240 bool PPCVSXSwapRemoval::gatherVectorInstructions() {
241 bool RelevantFunction
= false;
243 for (MachineBasicBlock
&MBB
: *MF
) {
244 for (MachineInstr
&MI
: MBB
) {
246 if (MI
.isDebugInstr())
249 bool RelevantInstr
= false;
250 bool Partial
= false;
252 for (const MachineOperand
&MO
: MI
.operands()) {
255 Register Reg
= MO
.getReg();
256 // All operands need to be checked because there are instructions that
257 // operate on a partial register and produce a full register (such as
259 if (isAnyVecReg(Reg
, Partial
))
260 RelevantInstr
= true;
266 RelevantFunction
= true;
268 // Create a SwapEntry initialized to zeros, then fill in the
269 // instruction and ID fields before pushing it to the back
270 // of the swap vector.
271 PPCVSXSwapEntry SwapEntry
{};
272 int VecIdx
= addSwapEntry(&MI
, SwapEntry
);
274 switch(MI
.getOpcode()) {
276 // Unless noted otherwise, an instruction is considered
277 // safe for the optimization. There are a large number of
278 // such true-SIMD instructions (all vector math, logical,
279 // select, compare, etc.). However, if the instruction
280 // mentions a partial vector register and does not have
281 // special handling defined, it is not swappable.
283 SwapVector
[VecIdx
].MentionsPartialVR
= 1;
285 SwapVector
[VecIdx
].IsSwappable
= 1;
287 case PPC::XXPERMDI
: {
288 // This is a swap if it is of the form XXPERMDI t, s, s, 2.
289 // Unfortunately, MachineCSE ignores COPY and SUBREG_TO_REG, so we
290 // can also see XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), 2,
291 // for example. We have to look through chains of COPY and
292 // SUBREG_TO_REG to find the real source value for comparison.
293 // If the real source value is a physical register, then mark the
294 // XXPERMDI as mentioning a physical register.
295 int immed
= MI
.getOperand(3).getImm();
297 unsigned trueReg1
= lookThruCopyLike(MI
.getOperand(1).getReg(),
299 unsigned trueReg2
= lookThruCopyLike(MI
.getOperand(2).getReg(),
301 if (trueReg1
== trueReg2
)
302 SwapVector
[VecIdx
].IsSwap
= 1;
304 // We can still handle these if the two registers are not
305 // identical, by adjusting the form of the XXPERMDI.
306 SwapVector
[VecIdx
].IsSwappable
= 1;
307 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_XXPERMDI
;
309 // This is a doubleword splat if it is of the form
310 // XXPERMDI t, s, s, 0 or XXPERMDI t, s, s, 3. As above we
311 // must look through chains of copy-likes to find the source
312 // register. We turn off the marking for mention of a physical
313 // register, because splatting it is safe; the optimization
314 // will not swap the value in the physical register. Whether
315 // or not the two input registers are identical, we can handle
316 // these by adjusting the form of the XXPERMDI.
317 } else if (immed
== 0 || immed
== 3) {
319 SwapVector
[VecIdx
].IsSwappable
= 1;
320 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_XXPERMDI
;
322 unsigned trueReg1
= lookThruCopyLike(MI
.getOperand(1).getReg(),
324 unsigned trueReg2
= lookThruCopyLike(MI
.getOperand(2).getReg(),
326 if (trueReg1
== trueReg2
)
327 SwapVector
[VecIdx
].MentionsPhysVR
= 0;
330 // We can still handle these by adjusting the form of the XXPERMDI.
331 SwapVector
[VecIdx
].IsSwappable
= 1;
332 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_XXPERMDI
;
337 // Non-permuting loads are currently unsafe. We can use special
338 // handling for this in the future. By not marking these as
339 // IsSwap, we ensure computations containing them will be rejected
341 SwapVector
[VecIdx
].IsLoad
= 1;
345 // Permuting loads are marked as both load and swap, and are
346 // safe for optimization.
347 SwapVector
[VecIdx
].IsLoad
= 1;
348 SwapVector
[VecIdx
].IsSwap
= 1;
354 // A load of a floating-point value into the high-order half of
355 // a vector register is safe, provided that we introduce a swap
356 // following the load, which will be done by the SUBREG_TO_REG
357 // support. So just mark these as safe.
358 SwapVector
[VecIdx
].IsLoad
= 1;
359 SwapVector
[VecIdx
].IsSwappable
= 1;
362 // Non-permuting stores are currently unsafe. We can use special
363 // handling for this in the future. By not marking these as
364 // IsSwap, we ensure computations containing them will be rejected
366 SwapVector
[VecIdx
].IsStore
= 1;
370 // Permuting stores are marked as both store and swap, and are
371 // safe for optimization.
372 SwapVector
[VecIdx
].IsStore
= 1;
373 SwapVector
[VecIdx
].IsSwap
= 1;
376 // These are fine provided they are moving between full vector
378 if (isVecReg(MI
.getOperand(0).getReg()) &&
379 isVecReg(MI
.getOperand(1).getReg()))
380 SwapVector
[VecIdx
].IsSwappable
= 1;
381 // If we have a copy from one scalar floating-point register
382 // to another, we can accept this even if it is a physical
383 // register. The only way this gets involved is if it feeds
384 // a SUBREG_TO_REG, which is handled by introducing a swap.
385 else if (isScalarVecReg(MI
.getOperand(0).getReg()) &&
386 isScalarVecReg(MI
.getOperand(1).getReg()))
387 SwapVector
[VecIdx
].IsSwappable
= 1;
389 case PPC::SUBREG_TO_REG
: {
390 // These are fine provided they are moving between full vector
391 // register classes. If they are moving from a scalar
392 // floating-point class to a vector class, we can handle those
393 // as well, provided we introduce a swap. It is generally the
394 // case that we will introduce fewer swaps than we remove, but
395 // (FIXME) a cost model could be used. However, introduced
396 // swaps could potentially be CSEd, so this is not trivial.
397 if (isVecReg(MI
.getOperand(0).getReg()) &&
398 isVecReg(MI
.getOperand(2).getReg()))
399 SwapVector
[VecIdx
].IsSwappable
= 1;
400 else if (isVecReg(MI
.getOperand(0).getReg()) &&
401 isScalarVecReg(MI
.getOperand(2).getReg())) {
402 SwapVector
[VecIdx
].IsSwappable
= 1;
403 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_COPYWIDEN
;
411 // Splats are lane-sensitive, but we can use special handling
412 // to adjust the source lane for the splat.
413 SwapVector
[VecIdx
].IsSwappable
= 1;
414 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_SPLAT
;
416 // The presence of the following lane-sensitive operations in a
417 // web will kill the optimization, at least for now. For these
418 // we do nothing, causing the optimization to fail.
419 // FIXME: Some of these could be permitted with special handling,
420 // and will be phased in as time permits.
421 // FIXME: There is no simple and maintainable way to express a set
422 // of opcodes having a common attribute in TableGen. Should this
423 // change, this is a prime candidate to use such a mechanism.
425 case PPC::INLINEASM_BR
:
426 case PPC::EXTRACT_SUBREG
:
427 case PPC::INSERT_SUBREG
:
428 case PPC::COPY_TO_REGCLASS
:
439 // We can handle STXSDX and STXSSPX similarly to LXSDX and LXSSPX,
440 // by adding special handling for narrowing copies as well as
441 // widening ones. However, I've experimented with this, and in
442 // practice we currently do not appear to use STXSDX fed by
443 // a narrowing copy from a full vector register. Since I can't
444 // generate any useful test cases, I've left this alone for now.
448 case PPC::VCIPHERLAST
:
468 case PPC::VNCIPHERLAST
:
493 case PPC::VSHASIGMAD
:
494 case PPC::VSHASIGMAW
:
515 // XXSLDWI could be replaced by a general permute with one of three
516 // permute control vectors (for shift values 1, 2, 3). However,
517 // VPERM has a more restrictive register class.
528 if (RelevantFunction
) {
529 LLVM_DEBUG(dbgs() << "Swap vector when first built\n\n");
530 LLVM_DEBUG(dumpSwapVector());
533 return RelevantFunction
;
536 // Add an entry to the swap vector and swap map, and make a
537 // singleton equivalence class for the entry.
538 int PPCVSXSwapRemoval::addSwapEntry(MachineInstr
*MI
,
539 PPCVSXSwapEntry
& SwapEntry
) {
540 SwapEntry
.VSEMI
= MI
;
541 SwapEntry
.VSEId
= SwapVector
.size();
542 SwapVector
.push_back(SwapEntry
);
543 EC
->insert(SwapEntry
.VSEId
);
544 SwapMap
[MI
] = SwapEntry
.VSEId
;
545 return SwapEntry
.VSEId
;
548 // This is used to find the "true" source register for an
549 // XXPERMDI instruction, since MachineCSE does not handle the
550 // "copy-like" operations (Copy and SubregToReg). Returns
551 // the original SrcReg unless it is the target of a copy-like
552 // operation, in which case we chain backwards through all
553 // such operations to the ultimate source register. If a
554 // physical register is encountered, we stop the search and
555 // flag the swap entry indicated by VecIdx (the original
556 // XXPERMDI) as mentioning a physical register.
557 unsigned PPCVSXSwapRemoval::lookThruCopyLike(unsigned SrcReg
,
559 MachineInstr
*MI
= MRI
->getVRegDef(SrcReg
);
560 if (!MI
->isCopyLike())
565 CopySrcReg
= MI
->getOperand(1).getReg();
567 assert(MI
->isSubregToReg() && "bad opcode for lookThruCopyLike");
568 CopySrcReg
= MI
->getOperand(2).getReg();
571 if (!Register::isVirtualRegister(CopySrcReg
)) {
572 if (!isScalarVecReg(CopySrcReg
))
573 SwapVector
[VecIdx
].MentionsPhysVR
= 1;
577 return lookThruCopyLike(CopySrcReg
, VecIdx
);
580 // Generate equivalence classes for related computations (webs) by
581 // def-use relationships of virtual registers. Mention of a physical
582 // register terminates the generation of equivalence classes as this
583 // indicates a use of a parameter, definition of a return value, use
584 // of a value returned from a call, or definition of a parameter to a
585 // call. Computations with physical register mentions are flagged
586 // as such so their containing webs will not be optimized.
587 void PPCVSXSwapRemoval::formWebs() {
589 LLVM_DEBUG(dbgs() << "\n*** Forming webs for swap removal ***\n\n");
591 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
593 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
595 LLVM_DEBUG(dbgs() << "\n" << SwapVector
[EntryIdx
].VSEId
<< " ");
596 LLVM_DEBUG(MI
->dump());
598 // It's sufficient to walk vector uses and join them to their unique
599 // definitions. In addition, check full vector register operands
600 // for physical regs. We exclude partial-vector register operands
601 // because we can handle them if copied to a full vector.
602 for (const MachineOperand
&MO
: MI
->operands()) {
606 Register Reg
= MO
.getReg();
607 if (!isVecReg(Reg
) && !isScalarVecReg(Reg
))
610 if (!Reg
.isVirtual()) {
611 if (!(MI
->isCopy() && isScalarVecReg(Reg
)))
612 SwapVector
[EntryIdx
].MentionsPhysVR
= 1;
619 MachineInstr
* DefMI
= MRI
->getVRegDef(Reg
);
620 assert(SwapMap
.contains(DefMI
) &&
621 "Inconsistency: def of vector reg not found in swap map!");
622 int DefIdx
= SwapMap
[DefMI
];
623 (void)EC
->unionSets(SwapVector
[DefIdx
].VSEId
,
624 SwapVector
[EntryIdx
].VSEId
);
626 LLVM_DEBUG(dbgs() << format("Unioning %d with %d\n",
627 SwapVector
[DefIdx
].VSEId
,
628 SwapVector
[EntryIdx
].VSEId
));
629 LLVM_DEBUG(dbgs() << " Def: ");
630 LLVM_DEBUG(DefMI
->dump());
635 // Walk the swap vector entries looking for conditions that prevent their
636 // containing computations from being optimized. When such conditions are
637 // found, mark the representative of the computation's equivalence class
639 void PPCVSXSwapRemoval::recordUnoptimizableWebs() {
641 LLVM_DEBUG(dbgs() << "\n*** Rejecting webs for swap removal ***\n\n");
643 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
644 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
646 // If representative is already rejected, don't waste further time.
647 if (SwapVector
[Repr
].WebRejected
)
650 // Reject webs containing mentions of physical or partial registers, or
651 // containing operations that we don't know how to handle in a lane-
653 if (SwapVector
[EntryIdx
].MentionsPhysVR
||
654 SwapVector
[EntryIdx
].MentionsPartialVR
||
655 !(SwapVector
[EntryIdx
].IsSwappable
|| SwapVector
[EntryIdx
].IsSwap
)) {
657 SwapVector
[Repr
].WebRejected
= 1;
660 dbgs() << format("Web %d rejected for physreg, partial reg, or not "
663 LLVM_DEBUG(dbgs() << " in " << EntryIdx
<< ": ");
664 LLVM_DEBUG(SwapVector
[EntryIdx
].VSEMI
->dump());
665 LLVM_DEBUG(dbgs() << "\n");
668 // Reject webs than contain swapping loads that feed something other
669 // than a swap instruction.
670 else if (SwapVector
[EntryIdx
].IsLoad
&& SwapVector
[EntryIdx
].IsSwap
) {
671 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
672 Register DefReg
= MI
->getOperand(0).getReg();
674 // We skip debug instructions in the analysis. (Note that debug
675 // location information is still maintained by this optimization
676 // because it remains on the LXVD2X and STXVD2X instructions after
677 // the XXPERMDIs are removed.)
678 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(DefReg
)) {
679 int UseIdx
= SwapMap
[&UseMI
];
681 if (!SwapVector
[UseIdx
].IsSwap
|| SwapVector
[UseIdx
].IsLoad
||
682 SwapVector
[UseIdx
].IsStore
) {
684 SwapVector
[Repr
].WebRejected
= 1;
686 LLVM_DEBUG(dbgs() << format(
687 "Web %d rejected for load not feeding swap\n", Repr
));
688 LLVM_DEBUG(dbgs() << " def " << EntryIdx
<< ": ");
689 LLVM_DEBUG(MI
->dump());
690 LLVM_DEBUG(dbgs() << " use " << UseIdx
<< ": ");
691 LLVM_DEBUG(UseMI
.dump());
692 LLVM_DEBUG(dbgs() << "\n");
695 // It is possible that the load feeds a swap and that swap feeds a
696 // store. In such a case, the code is actually trying to store a swapped
697 // vector. We must reject such webs.
698 if (SwapVector
[UseIdx
].IsSwap
&& !SwapVector
[UseIdx
].IsLoad
&&
699 !SwapVector
[UseIdx
].IsStore
) {
700 Register SwapDefReg
= UseMI
.getOperand(0).getReg();
701 for (MachineInstr
&UseOfUseMI
:
702 MRI
->use_nodbg_instructions(SwapDefReg
)) {
703 int UseOfUseIdx
= SwapMap
[&UseOfUseMI
];
704 if (SwapVector
[UseOfUseIdx
].IsStore
) {
705 SwapVector
[Repr
].WebRejected
= 1;
708 "Web %d rejected for load/swap feeding a store\n", Repr
));
709 LLVM_DEBUG(dbgs() << " def " << EntryIdx
<< ": ");
710 LLVM_DEBUG(MI
->dump());
711 LLVM_DEBUG(dbgs() << " use " << UseIdx
<< ": ");
712 LLVM_DEBUG(UseMI
.dump());
713 LLVM_DEBUG(dbgs() << "\n");
719 // Reject webs that contain swapping stores that are fed by something
720 // other than a swap instruction.
721 } else if (SwapVector
[EntryIdx
].IsStore
&& SwapVector
[EntryIdx
].IsSwap
) {
722 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
723 Register UseReg
= MI
->getOperand(0).getReg();
724 MachineInstr
*DefMI
= MRI
->getVRegDef(UseReg
);
725 Register DefReg
= DefMI
->getOperand(0).getReg();
726 int DefIdx
= SwapMap
[DefMI
];
728 if (!SwapVector
[DefIdx
].IsSwap
|| SwapVector
[DefIdx
].IsLoad
||
729 SwapVector
[DefIdx
].IsStore
) {
731 SwapVector
[Repr
].WebRejected
= 1;
733 LLVM_DEBUG(dbgs() << format(
734 "Web %d rejected for store not fed by swap\n", Repr
));
735 LLVM_DEBUG(dbgs() << " def " << DefIdx
<< ": ");
736 LLVM_DEBUG(DefMI
->dump());
737 LLVM_DEBUG(dbgs() << " use " << EntryIdx
<< ": ");
738 LLVM_DEBUG(MI
->dump());
739 LLVM_DEBUG(dbgs() << "\n");
742 // Ensure all uses of the register defined by DefMI feed store
744 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(DefReg
)) {
745 int UseIdx
= SwapMap
[&UseMI
];
747 if (SwapVector
[UseIdx
].VSEMI
->getOpcode() != MI
->getOpcode()) {
748 SwapVector
[Repr
].WebRejected
= 1;
752 "Web %d rejected for swap not feeding only stores\n", Repr
));
753 LLVM_DEBUG(dbgs() << " def "
755 LLVM_DEBUG(DefMI
->dump());
756 LLVM_DEBUG(dbgs() << " use " << UseIdx
<< ": ");
757 LLVM_DEBUG(SwapVector
[UseIdx
].VSEMI
->dump());
758 LLVM_DEBUG(dbgs() << "\n");
764 LLVM_DEBUG(dbgs() << "Swap vector after web analysis:\n\n");
765 LLVM_DEBUG(dumpSwapVector());
768 // Walk the swap vector entries looking for swaps fed by permuting loads
769 // and swaps that feed permuting stores. If the containing computation
770 // has not been marked rejected, mark each such swap for removal.
771 // (Removal is delayed in case optimization has disturbed the pattern,
772 // such that multiple loads feed the same swap, etc.)
773 void PPCVSXSwapRemoval::markSwapsForRemoval() {
775 LLVM_DEBUG(dbgs() << "\n*** Marking swaps for removal ***\n\n");
777 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
779 if (SwapVector
[EntryIdx
].IsLoad
&& SwapVector
[EntryIdx
].IsSwap
) {
780 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
782 if (!SwapVector
[Repr
].WebRejected
) {
783 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
784 Register DefReg
= MI
->getOperand(0).getReg();
786 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(DefReg
)) {
787 int UseIdx
= SwapMap
[&UseMI
];
788 SwapVector
[UseIdx
].WillRemove
= 1;
790 LLVM_DEBUG(dbgs() << "Marking swap fed by load for removal: ");
791 LLVM_DEBUG(UseMI
.dump());
795 } else if (SwapVector
[EntryIdx
].IsStore
&& SwapVector
[EntryIdx
].IsSwap
) {
796 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
798 if (!SwapVector
[Repr
].WebRejected
) {
799 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
800 Register UseReg
= MI
->getOperand(0).getReg();
801 MachineInstr
*DefMI
= MRI
->getVRegDef(UseReg
);
802 int DefIdx
= SwapMap
[DefMI
];
803 SwapVector
[DefIdx
].WillRemove
= 1;
805 LLVM_DEBUG(dbgs() << "Marking swap feeding store for removal: ");
806 LLVM_DEBUG(DefMI
->dump());
809 } else if (SwapVector
[EntryIdx
].IsSwappable
&&
810 SwapVector
[EntryIdx
].SpecialHandling
!= 0) {
811 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
813 if (!SwapVector
[Repr
].WebRejected
)
814 handleSpecialSwappables(EntryIdx
);
819 // Create an xxswapd instruction and insert it prior to the given point.
820 // MI is used to determine basic block and debug loc information.
821 // FIXME: When inserting a swap, we should check whether SrcReg is
822 // defined by another swap: SrcReg = XXPERMDI Reg, Reg, 2; If so,
823 // then instead we should generate a copy from Reg to DstReg.
824 void PPCVSXSwapRemoval::insertSwap(MachineInstr
*MI
,
825 MachineBasicBlock::iterator InsertPoint
,
826 unsigned DstReg
, unsigned SrcReg
) {
827 BuildMI(*MI
->getParent(), InsertPoint
, MI
->getDebugLoc(),
828 TII
->get(PPC::XXPERMDI
), DstReg
)
834 // The identified swap entry requires special handling to allow its
835 // containing computation to be optimized. Perform that handling
837 // FIXME: Additional opportunities will be phased in with subsequent
839 void PPCVSXSwapRemoval::handleSpecialSwappables(int EntryIdx
) {
840 switch (SwapVector
[EntryIdx
].SpecialHandling
) {
843 llvm_unreachable("Unexpected special handling type");
845 // For splats based on an index into a vector, add N/2 modulo N
846 // to the index, where N is the number of vector elements.
847 case SHValues::SH_SPLAT
: {
848 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
851 LLVM_DEBUG(dbgs() << "Changing splat: ");
852 LLVM_DEBUG(MI
->dump());
854 switch (MI
->getOpcode()) {
856 llvm_unreachable("Unexpected splat opcode");
857 case PPC::VSPLTB
: NElts
= 16; break;
858 case PPC::VSPLTH
: NElts
= 8; break;
860 case PPC::XXSPLTW
: NElts
= 4; break;
864 if (MI
->getOpcode() == PPC::XXSPLTW
)
865 EltNo
= MI
->getOperand(2).getImm();
867 EltNo
= MI
->getOperand(1).getImm();
869 EltNo
= (EltNo
+ NElts
/ 2) % NElts
;
870 if (MI
->getOpcode() == PPC::XXSPLTW
)
871 MI
->getOperand(2).setImm(EltNo
);
873 MI
->getOperand(1).setImm(EltNo
);
875 LLVM_DEBUG(dbgs() << " Into: ");
876 LLVM_DEBUG(MI
->dump());
880 // For an XXPERMDI that isn't handled otherwise, we need to
881 // reverse the order of the operands. If the selector operand
882 // has a value of 0 or 3, we need to change it to 3 or 0,
883 // respectively. Otherwise we should leave it alone. (This
884 // is equivalent to reversing the two bits of the selector
885 // operand and complementing the result.)
886 case SHValues::SH_XXPERMDI
: {
887 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
889 LLVM_DEBUG(dbgs() << "Changing XXPERMDI: ");
890 LLVM_DEBUG(MI
->dump());
892 unsigned Selector
= MI
->getOperand(3).getImm();
893 if (Selector
== 0 || Selector
== 3)
894 Selector
= 3 - Selector
;
895 MI
->getOperand(3).setImm(Selector
);
897 Register Reg1
= MI
->getOperand(1).getReg();
898 Register Reg2
= MI
->getOperand(2).getReg();
899 MI
->getOperand(1).setReg(Reg2
);
900 MI
->getOperand(2).setReg(Reg1
);
902 // We also need to swap kill flag associated with the register.
903 bool IsKill1
= MI
->getOperand(1).isKill();
904 bool IsKill2
= MI
->getOperand(2).isKill();
905 MI
->getOperand(1).setIsKill(IsKill2
);
906 MI
->getOperand(2).setIsKill(IsKill1
);
908 LLVM_DEBUG(dbgs() << " Into: ");
909 LLVM_DEBUG(MI
->dump());
913 // For a copy from a scalar floating-point register to a vector
914 // register, removing swaps will leave the copied value in the
915 // wrong lane. Insert a swap following the copy to fix this.
916 case SHValues::SH_COPYWIDEN
: {
917 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
919 LLVM_DEBUG(dbgs() << "Changing SUBREG_TO_REG: ");
920 LLVM_DEBUG(MI
->dump());
922 Register DstReg
= MI
->getOperand(0).getReg();
923 const TargetRegisterClass
*DstRC
= MRI
->getRegClass(DstReg
);
924 Register NewVReg
= MRI
->createVirtualRegister(DstRC
);
926 MI
->getOperand(0).setReg(NewVReg
);
927 LLVM_DEBUG(dbgs() << " Into: ");
928 LLVM_DEBUG(MI
->dump());
930 auto InsertPoint
= ++MachineBasicBlock::iterator(MI
);
932 // Note that an XXPERMDI requires a VSRC, so if the SUBREG_TO_REG
933 // is copying to a VRRC, we need to be careful to avoid a register
934 // assignment problem. In this case we must copy from VRRC to VSRC
935 // prior to the swap, and from VSRC to VRRC following the swap.
936 // Coalescing will usually remove all this mess.
937 if (DstRC
== &PPC::VRRCRegClass
) {
938 Register VSRCTmp1
= MRI
->createVirtualRegister(&PPC::VSRCRegClass
);
939 Register VSRCTmp2
= MRI
->createVirtualRegister(&PPC::VSRCRegClass
);
941 BuildMI(*MI
->getParent(), InsertPoint
, MI
->getDebugLoc(),
942 TII
->get(PPC::COPY
), VSRCTmp1
)
944 LLVM_DEBUG(std::prev(InsertPoint
)->dump());
946 insertSwap(MI
, InsertPoint
, VSRCTmp2
, VSRCTmp1
);
947 LLVM_DEBUG(std::prev(InsertPoint
)->dump());
949 BuildMI(*MI
->getParent(), InsertPoint
, MI
->getDebugLoc(),
950 TII
->get(PPC::COPY
), DstReg
)
952 LLVM_DEBUG(std::prev(InsertPoint
)->dump());
955 insertSwap(MI
, InsertPoint
, DstReg
, NewVReg
);
956 LLVM_DEBUG(std::prev(InsertPoint
)->dump());
963 // Walk the swap vector and replace each entry marked for removal with
965 bool PPCVSXSwapRemoval::removeSwaps() {
967 LLVM_DEBUG(dbgs() << "\n*** Removing swaps ***\n\n");
969 bool Changed
= false;
971 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
972 if (SwapVector
[EntryIdx
].WillRemove
) {
974 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
975 MachineBasicBlock
*MBB
= MI
->getParent();
976 BuildMI(*MBB
, MI
, MI
->getDebugLoc(), TII
->get(TargetOpcode::COPY
),
977 MI
->getOperand(0).getReg())
978 .add(MI
->getOperand(1));
980 LLVM_DEBUG(dbgs() << format("Replaced %d with copy: ",
981 SwapVector
[EntryIdx
].VSEId
));
982 LLVM_DEBUG(MI
->dump());
984 MI
->eraseFromParent();
991 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
992 // For debug purposes, dump the contents of the swap vector.
993 LLVM_DUMP_METHOD
void PPCVSXSwapRemoval::dumpSwapVector() {
995 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
997 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
998 int ID
= SwapVector
[EntryIdx
].VSEId
;
1000 dbgs() << format("%6d", ID
);
1001 dbgs() << format("%6d", EC
->getLeaderValue(ID
));
1002 dbgs() << format(" %bb.%3d", MI
->getParent()->getNumber());
1003 dbgs() << format(" %14s ", TII
->getName(MI
->getOpcode()).str().c_str());
1005 if (SwapVector
[EntryIdx
].IsLoad
)
1007 if (SwapVector
[EntryIdx
].IsStore
)
1009 if (SwapVector
[EntryIdx
].IsSwap
)
1011 if (SwapVector
[EntryIdx
].MentionsPhysVR
)
1012 dbgs() << "physreg ";
1013 if (SwapVector
[EntryIdx
].MentionsPartialVR
)
1014 dbgs() << "partialreg ";
1016 if (SwapVector
[EntryIdx
].IsSwappable
) {
1017 dbgs() << "swappable ";
1018 switch(SwapVector
[EntryIdx
].SpecialHandling
) {
1020 dbgs() << "special:**unknown**";
1025 dbgs() << "special:extract ";
1028 dbgs() << "special:insert ";
1031 dbgs() << "special:load ";
1034 dbgs() << "special:store ";
1037 dbgs() << "special:splat ";
1040 dbgs() << "special:xxpermdi ";
1043 dbgs() << "special:copywiden ";
1048 if (SwapVector
[EntryIdx
].WebRejected
)
1049 dbgs() << "rejected ";
1050 if (SwapVector
[EntryIdx
].WillRemove
)
1051 dbgs() << "remove ";
1055 // For no-asserts builds.
1064 } // end default namespace
1066 INITIALIZE_PASS_BEGIN(PPCVSXSwapRemoval
, DEBUG_TYPE
,
1067 "PowerPC VSX Swap Removal", false, false)
1068 INITIALIZE_PASS_END(PPCVSXSwapRemoval
, DEBUG_TYPE
,
1069 "PowerPC VSX Swap Removal", false, false)
1071 char PPCVSXSwapRemoval::ID
= 0;
1073 llvm::createPPCVSXSwapRemovalPass() { return new PPCVSXSwapRemoval(); }