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 "PPCInstrBuilder.h"
46 #include "PPCInstrInfo.h"
47 #include "PPCTargetMachine.h"
48 #include "llvm/ADT/DenseMap.h"
49 #include "llvm/ADT/EquivalenceClasses.h"
50 #include "llvm/CodeGen/MachineFunctionPass.h"
51 #include "llvm/CodeGen/MachineInstrBuilder.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/Config/llvm-config.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/Format.h"
56 #include "llvm/Support/raw_ostream.h"
60 #define DEBUG_TYPE "ppc-vsx-swaps"
64 // A PPCVSXSwapEntry is created for each machine instruction that
65 // is relevant to a vector computation.
66 struct PPCVSXSwapEntry
{
67 // Pointer to the instruction.
70 // Unique ID (position in the swap vector).
73 // Attributes of this node.
74 unsigned int IsLoad
: 1;
75 unsigned int IsStore
: 1;
76 unsigned int IsSwap
: 1;
77 unsigned int MentionsPhysVR
: 1;
78 unsigned int IsSwappable
: 1;
79 unsigned int MentionsPartialVR
: 1;
80 unsigned int SpecialHandling
: 3;
81 unsigned int WebRejected
: 1;
82 unsigned int WillRemove
: 1;
96 struct PPCVSXSwapRemoval
: public MachineFunctionPass
{
99 const PPCInstrInfo
*TII
;
101 MachineRegisterInfo
*MRI
;
103 // Swap entries are allocated in a vector for better performance.
104 std::vector
<PPCVSXSwapEntry
> SwapVector
;
106 // A mapping is maintained between machine instructions and
107 // their swap entries. The key is the address of the MI.
108 DenseMap
<MachineInstr
*, int> SwapMap
;
110 // Equivalence classes are used to gather webs of related computation.
111 // Swap entries are represented by their VSEId fields.
112 EquivalenceClasses
<int> *EC
;
114 PPCVSXSwapRemoval() : MachineFunctionPass(ID
) {
115 initializePPCVSXSwapRemovalPass(*PassRegistry::getPassRegistry());
119 // Initialize data structures.
120 void initialize(MachineFunction
&MFParm
);
122 // Walk the machine instructions to gather vector usage information.
123 // Return true iff vector mentions are present.
124 bool gatherVectorInstructions();
126 // Add an entry to the swap vector and swap map.
127 int addSwapEntry(MachineInstr
*MI
, PPCVSXSwapEntry
&SwapEntry
);
129 // Hunt backwards through COPY and SUBREG_TO_REG chains for a
130 // source register. VecIdx indicates the swap vector entry to
131 // mark as mentioning a physical register if the search leads
133 unsigned lookThruCopyLike(unsigned SrcReg
, unsigned VecIdx
);
135 // Generate equivalence classes for related computations (webs).
138 // Analyze webs and determine those that cannot be optimized.
139 void recordUnoptimizableWebs();
141 // Record which swap instructions can be safely removed.
142 void markSwapsForRemoval();
144 // Remove swaps and update other instructions requiring special
145 // handling. Return true iff any changes are made.
148 // Insert a swap instruction from SrcReg to DstReg at the given
150 void insertSwap(MachineInstr
*MI
, MachineBasicBlock::iterator InsertPoint
,
151 unsigned DstReg
, unsigned SrcReg
);
153 // Update instructions requiring special handling.
154 void handleSpecialSwappables(int EntryIdx
);
156 // Dump a description of the entries in the swap vector.
157 void dumpSwapVector();
159 // Return true iff the given register is in the given class.
160 bool isRegInClass(unsigned Reg
, const TargetRegisterClass
*RC
) {
161 if (Register::isVirtualRegister(Reg
))
162 return RC
->hasSubClassEq(MRI
->getRegClass(Reg
));
163 return RC
->contains(Reg
);
166 // Return true iff the given register is a full vector register.
167 bool isVecReg(unsigned Reg
) {
168 return (isRegInClass(Reg
, &PPC::VSRCRegClass
) ||
169 isRegInClass(Reg
, &PPC::VRRCRegClass
));
172 // Return true iff the given register is a partial vector register.
173 bool isScalarVecReg(unsigned Reg
) {
174 return (isRegInClass(Reg
, &PPC::VSFRCRegClass
) ||
175 isRegInClass(Reg
, &PPC::VSSRCRegClass
));
178 // Return true iff the given register mentions all or part of a
179 // vector register. Also sets Partial to true if the mention
180 // is for just the floating-point register overlap of the register.
181 bool isAnyVecReg(unsigned Reg
, bool &Partial
) {
182 if (isScalarVecReg(Reg
))
184 return isScalarVecReg(Reg
) || isVecReg(Reg
);
188 // Main entry point for this pass.
189 bool runOnMachineFunction(MachineFunction
&MF
) override
{
190 if (skipFunction(MF
.getFunction()))
193 // If we don't have VSX on the subtarget, don't do anything.
194 // Also, on Power 9 the load and store ops preserve element order and so
195 // the swaps are not required.
196 const PPCSubtarget
&STI
= MF
.getSubtarget
<PPCSubtarget
>();
197 if (!STI
.hasVSX() || !STI
.needsSwapsForVSXMemOps())
200 bool Changed
= false;
203 if (gatherVectorInstructions()) {
205 recordUnoptimizableWebs();
206 markSwapsForRemoval();
207 Changed
= removeSwaps();
210 // FIXME: See the allocation of EC in initialize().
216 // Initialize data structures for this pass. In particular, clear the
217 // swap vector and allocate the equivalence class mapping before
218 // processing each function.
219 void PPCVSXSwapRemoval::initialize(MachineFunction
&MFParm
) {
221 MRI
= &MF
->getRegInfo();
222 TII
= MF
->getSubtarget
<PPCSubtarget
>().getInstrInfo();
224 // An initial vector size of 256 appears to work well in practice.
225 // Small/medium functions with vector content tend not to incur a
226 // reallocation at this size. Three of the vector tests in
227 // projects/test-suite reallocate, which seems like a reasonable rate.
228 const int InitialVectorSize(256);
230 SwapVector
.reserve(InitialVectorSize
);
232 // FIXME: Currently we allocate EC each time because we don't have
233 // access to the set representation on which to call clear(). Should
234 // consider adding a clear() method to the EquivalenceClasses class.
235 EC
= new EquivalenceClasses
<int>;
238 // Create an entry in the swap vector for each instruction that mentions
239 // a full vector register, recording various characteristics of the
240 // instructions there.
241 bool PPCVSXSwapRemoval::gatherVectorInstructions() {
242 bool RelevantFunction
= false;
244 for (MachineBasicBlock
&MBB
: *MF
) {
245 for (MachineInstr
&MI
: MBB
) {
247 if (MI
.isDebugInstr())
250 bool RelevantInstr
= false;
251 bool Partial
= false;
253 for (const MachineOperand
&MO
: MI
.operands()) {
256 Register Reg
= MO
.getReg();
257 // All operands need to be checked because there are instructions that
258 // operate on a partial register and produce a full register (such as
260 if (isAnyVecReg(Reg
, Partial
))
261 RelevantInstr
= true;
267 RelevantFunction
= true;
269 // Create a SwapEntry initialized to zeros, then fill in the
270 // instruction and ID fields before pushing it to the back
271 // of the swap vector.
272 PPCVSXSwapEntry SwapEntry
{};
273 int VecIdx
= addSwapEntry(&MI
, SwapEntry
);
275 switch(MI
.getOpcode()) {
277 // Unless noted otherwise, an instruction is considered
278 // safe for the optimization. There are a large number of
279 // such true-SIMD instructions (all vector math, logical,
280 // select, compare, etc.). However, if the instruction
281 // mentions a partial vector register and does not have
282 // special handling defined, it is not swappable.
284 SwapVector
[VecIdx
].MentionsPartialVR
= 1;
286 SwapVector
[VecIdx
].IsSwappable
= 1;
288 case PPC::XXPERMDI
: {
289 // This is a swap if it is of the form XXPERMDI t, s, s, 2.
290 // Unfortunately, MachineCSE ignores COPY and SUBREG_TO_REG, so we
291 // can also see XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), 2,
292 // for example. We have to look through chains of COPY and
293 // SUBREG_TO_REG to find the real source value for comparison.
294 // If the real source value is a physical register, then mark the
295 // XXPERMDI as mentioning a physical register.
296 int immed
= MI
.getOperand(3).getImm();
298 unsigned trueReg1
= lookThruCopyLike(MI
.getOperand(1).getReg(),
300 unsigned trueReg2
= lookThruCopyLike(MI
.getOperand(2).getReg(),
302 if (trueReg1
== trueReg2
)
303 SwapVector
[VecIdx
].IsSwap
= 1;
305 // We can still handle these if the two registers are not
306 // identical, by adjusting the form of the XXPERMDI.
307 SwapVector
[VecIdx
].IsSwappable
= 1;
308 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_XXPERMDI
;
310 // This is a doubleword splat if it is of the form
311 // XXPERMDI t, s, s, 0 or XXPERMDI t, s, s, 3. As above we
312 // must look through chains of copy-likes to find the source
313 // register. We turn off the marking for mention of a physical
314 // register, because splatting it is safe; the optimization
315 // will not swap the value in the physical register. Whether
316 // or not the two input registers are identical, we can handle
317 // these by adjusting the form of the XXPERMDI.
318 } else if (immed
== 0 || immed
== 3) {
320 SwapVector
[VecIdx
].IsSwappable
= 1;
321 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_XXPERMDI
;
323 unsigned trueReg1
= lookThruCopyLike(MI
.getOperand(1).getReg(),
325 unsigned trueReg2
= lookThruCopyLike(MI
.getOperand(2).getReg(),
327 if (trueReg1
== trueReg2
)
328 SwapVector
[VecIdx
].MentionsPhysVR
= 0;
331 // We can still handle these by adjusting the form of the XXPERMDI.
332 SwapVector
[VecIdx
].IsSwappable
= 1;
333 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_XXPERMDI
;
338 // Non-permuting loads are currently unsafe. We can use special
339 // handling for this in the future. By not marking these as
340 // IsSwap, we ensure computations containing them will be rejected
342 SwapVector
[VecIdx
].IsLoad
= 1;
346 // Permuting loads are marked as both load and swap, and are
347 // safe for optimization.
348 SwapVector
[VecIdx
].IsLoad
= 1;
349 SwapVector
[VecIdx
].IsSwap
= 1;
355 // A load of a floating-point value into the high-order half of
356 // a vector register is safe, provided that we introduce a swap
357 // following the load, which will be done by the SUBREG_TO_REG
358 // support. So just mark these as safe.
359 SwapVector
[VecIdx
].IsLoad
= 1;
360 SwapVector
[VecIdx
].IsSwappable
= 1;
363 // Non-permuting stores are currently unsafe. We can use special
364 // handling for this in the future. By not marking these as
365 // IsSwap, we ensure computations containing them will be rejected
367 SwapVector
[VecIdx
].IsStore
= 1;
371 // Permuting stores are marked as both store and swap, and are
372 // safe for optimization.
373 SwapVector
[VecIdx
].IsStore
= 1;
374 SwapVector
[VecIdx
].IsSwap
= 1;
377 // These are fine provided they are moving between full vector
379 if (isVecReg(MI
.getOperand(0).getReg()) &&
380 isVecReg(MI
.getOperand(1).getReg()))
381 SwapVector
[VecIdx
].IsSwappable
= 1;
382 // If we have a copy from one scalar floating-point register
383 // to another, we can accept this even if it is a physical
384 // register. The only way this gets involved is if it feeds
385 // a SUBREG_TO_REG, which is handled by introducing a swap.
386 else if (isScalarVecReg(MI
.getOperand(0).getReg()) &&
387 isScalarVecReg(MI
.getOperand(1).getReg()))
388 SwapVector
[VecIdx
].IsSwappable
= 1;
390 case PPC::SUBREG_TO_REG
: {
391 // These are fine provided they are moving between full vector
392 // register classes. If they are moving from a scalar
393 // floating-point class to a vector class, we can handle those
394 // as well, provided we introduce a swap. It is generally the
395 // case that we will introduce fewer swaps than we remove, but
396 // (FIXME) a cost model could be used. However, introduced
397 // swaps could potentially be CSEd, so this is not trivial.
398 if (isVecReg(MI
.getOperand(0).getReg()) &&
399 isVecReg(MI
.getOperand(2).getReg()))
400 SwapVector
[VecIdx
].IsSwappable
= 1;
401 else if (isVecReg(MI
.getOperand(0).getReg()) &&
402 isScalarVecReg(MI
.getOperand(2).getReg())) {
403 SwapVector
[VecIdx
].IsSwappable
= 1;
404 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_COPYWIDEN
;
412 // Splats are lane-sensitive, but we can use special handling
413 // to adjust the source lane for the splat.
414 SwapVector
[VecIdx
].IsSwappable
= 1;
415 SwapVector
[VecIdx
].SpecialHandling
= SHValues::SH_SPLAT
;
417 // The presence of the following lane-sensitive operations in a
418 // web will kill the optimization, at least for now. For these
419 // we do nothing, causing the optimization to fail.
420 // FIXME: Some of these could be permitted with special handling,
421 // and will be phased in as time permits.
422 // FIXME: There is no simple and maintainable way to express a set
423 // of opcodes having a common attribute in TableGen. Should this
424 // change, this is a prime candidate to use such a mechanism.
426 case PPC::INLINEASM_BR
:
427 case PPC::EXTRACT_SUBREG
:
428 case PPC::INSERT_SUBREG
:
429 case PPC::COPY_TO_REGCLASS
:
440 // We can handle STXSDX and STXSSPX similarly to LXSDX and LXSSPX,
441 // by adding special handling for narrowing copies as well as
442 // widening ones. However, I've experimented with this, and in
443 // practice we currently do not appear to use STXSDX fed by
444 // a narrowing copy from a full vector register. Since I can't
445 // generate any useful test cases, I've left this alone for now.
449 case PPC::VCIPHERLAST
:
469 case PPC::VNCIPHERLAST
:
494 case PPC::VSHASIGMAD
:
495 case PPC::VSHASIGMAW
:
516 // XXSLDWI could be replaced by a general permute with one of three
517 // permute control vectors (for shift values 1, 2, 3). However,
518 // VPERM has a more restrictive register class.
527 if (RelevantFunction
) {
528 LLVM_DEBUG(dbgs() << "Swap vector when first built\n\n");
529 LLVM_DEBUG(dumpSwapVector());
532 return RelevantFunction
;
535 // Add an entry to the swap vector and swap map, and make a
536 // singleton equivalence class for the entry.
537 int PPCVSXSwapRemoval::addSwapEntry(MachineInstr
*MI
,
538 PPCVSXSwapEntry
& SwapEntry
) {
539 SwapEntry
.VSEMI
= MI
;
540 SwapEntry
.VSEId
= SwapVector
.size();
541 SwapVector
.push_back(SwapEntry
);
542 EC
->insert(SwapEntry
.VSEId
);
543 SwapMap
[MI
] = SwapEntry
.VSEId
;
544 return SwapEntry
.VSEId
;
547 // This is used to find the "true" source register for an
548 // XXPERMDI instruction, since MachineCSE does not handle the
549 // "copy-like" operations (Copy and SubregToReg). Returns
550 // the original SrcReg unless it is the target of a copy-like
551 // operation, in which case we chain backwards through all
552 // such operations to the ultimate source register. If a
553 // physical register is encountered, we stop the search and
554 // flag the swap entry indicated by VecIdx (the original
555 // XXPERMDI) as mentioning a physical register.
556 unsigned PPCVSXSwapRemoval::lookThruCopyLike(unsigned SrcReg
,
558 MachineInstr
*MI
= MRI
->getVRegDef(SrcReg
);
559 if (!MI
->isCopyLike())
564 CopySrcReg
= MI
->getOperand(1).getReg();
566 assert(MI
->isSubregToReg() && "bad opcode for lookThruCopyLike");
567 CopySrcReg
= MI
->getOperand(2).getReg();
570 if (!Register::isVirtualRegister(CopySrcReg
)) {
571 if (!isScalarVecReg(CopySrcReg
))
572 SwapVector
[VecIdx
].MentionsPhysVR
= 1;
576 return lookThruCopyLike(CopySrcReg
, VecIdx
);
579 // Generate equivalence classes for related computations (webs) by
580 // def-use relationships of virtual registers. Mention of a physical
581 // register terminates the generation of equivalence classes as this
582 // indicates a use of a parameter, definition of a return value, use
583 // of a value returned from a call, or definition of a parameter to a
584 // call. Computations with physical register mentions are flagged
585 // as such so their containing webs will not be optimized.
586 void PPCVSXSwapRemoval::formWebs() {
588 LLVM_DEBUG(dbgs() << "\n*** Forming webs for swap removal ***\n\n");
590 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
592 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
594 LLVM_DEBUG(dbgs() << "\n" << SwapVector
[EntryIdx
].VSEId
<< " ");
595 LLVM_DEBUG(MI
->dump());
597 // It's sufficient to walk vector uses and join them to their unique
598 // definitions. In addition, check full vector register operands
599 // for physical regs. We exclude partial-vector register operands
600 // because we can handle them if copied to a full vector.
601 for (const MachineOperand
&MO
: MI
->operands()) {
605 Register Reg
= MO
.getReg();
606 if (!isVecReg(Reg
) && !isScalarVecReg(Reg
))
609 if (!Register::isVirtualRegister(Reg
)) {
610 if (!(MI
->isCopy() && isScalarVecReg(Reg
)))
611 SwapVector
[EntryIdx
].MentionsPhysVR
= 1;
618 MachineInstr
* DefMI
= MRI
->getVRegDef(Reg
);
619 assert(SwapMap
.find(DefMI
) != SwapMap
.end() &&
620 "Inconsistency: def of vector reg not found in swap map!");
621 int DefIdx
= SwapMap
[DefMI
];
622 (void)EC
->unionSets(SwapVector
[DefIdx
].VSEId
,
623 SwapVector
[EntryIdx
].VSEId
);
625 LLVM_DEBUG(dbgs() << format("Unioning %d with %d\n",
626 SwapVector
[DefIdx
].VSEId
,
627 SwapVector
[EntryIdx
].VSEId
));
628 LLVM_DEBUG(dbgs() << " Def: ");
629 LLVM_DEBUG(DefMI
->dump());
634 // Walk the swap vector entries looking for conditions that prevent their
635 // containing computations from being optimized. When such conditions are
636 // found, mark the representative of the computation's equivalence class
638 void PPCVSXSwapRemoval::recordUnoptimizableWebs() {
640 LLVM_DEBUG(dbgs() << "\n*** Rejecting webs for swap removal ***\n\n");
642 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
643 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
645 // If representative is already rejected, don't waste further time.
646 if (SwapVector
[Repr
].WebRejected
)
649 // Reject webs containing mentions of physical or partial registers, or
650 // containing operations that we don't know how to handle in a lane-
652 if (SwapVector
[EntryIdx
].MentionsPhysVR
||
653 SwapVector
[EntryIdx
].MentionsPartialVR
||
654 !(SwapVector
[EntryIdx
].IsSwappable
|| SwapVector
[EntryIdx
].IsSwap
)) {
656 SwapVector
[Repr
].WebRejected
= 1;
659 dbgs() << format("Web %d rejected for physreg, partial reg, or not "
662 LLVM_DEBUG(dbgs() << " in " << EntryIdx
<< ": ");
663 LLVM_DEBUG(SwapVector
[EntryIdx
].VSEMI
->dump());
664 LLVM_DEBUG(dbgs() << "\n");
667 // Reject webs than contain swapping loads that feed something other
668 // than a swap instruction.
669 else if (SwapVector
[EntryIdx
].IsLoad
&& SwapVector
[EntryIdx
].IsSwap
) {
670 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
671 Register DefReg
= MI
->getOperand(0).getReg();
673 // We skip debug instructions in the analysis. (Note that debug
674 // location information is still maintained by this optimization
675 // because it remains on the LXVD2X and STXVD2X instructions after
676 // the XXPERMDIs are removed.)
677 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(DefReg
)) {
678 int UseIdx
= SwapMap
[&UseMI
];
680 if (!SwapVector
[UseIdx
].IsSwap
|| SwapVector
[UseIdx
].IsLoad
||
681 SwapVector
[UseIdx
].IsStore
) {
683 SwapVector
[Repr
].WebRejected
= 1;
685 LLVM_DEBUG(dbgs() << format(
686 "Web %d rejected for load not feeding swap\n", Repr
));
687 LLVM_DEBUG(dbgs() << " def " << EntryIdx
<< ": ");
688 LLVM_DEBUG(MI
->dump());
689 LLVM_DEBUG(dbgs() << " use " << UseIdx
<< ": ");
690 LLVM_DEBUG(UseMI
.dump());
691 LLVM_DEBUG(dbgs() << "\n");
694 // It is possible that the load feeds a swap and that swap feeds a
695 // store. In such a case, the code is actually trying to store a swapped
696 // vector. We must reject such webs.
697 if (SwapVector
[UseIdx
].IsSwap
&& !SwapVector
[UseIdx
].IsLoad
&&
698 !SwapVector
[UseIdx
].IsStore
) {
699 Register SwapDefReg
= UseMI
.getOperand(0).getReg();
700 for (MachineInstr
&UseOfUseMI
:
701 MRI
->use_nodbg_instructions(SwapDefReg
)) {
702 int UseOfUseIdx
= SwapMap
[&UseOfUseMI
];
703 if (SwapVector
[UseOfUseIdx
].IsStore
) {
704 SwapVector
[Repr
].WebRejected
= 1;
707 "Web %d rejected for load/swap feeding a store\n", Repr
));
708 LLVM_DEBUG(dbgs() << " def " << EntryIdx
<< ": ");
709 LLVM_DEBUG(MI
->dump());
710 LLVM_DEBUG(dbgs() << " use " << UseIdx
<< ": ");
711 LLVM_DEBUG(UseMI
.dump());
712 LLVM_DEBUG(dbgs() << "\n");
718 // Reject webs that contain swapping stores that are fed by something
719 // other than a swap instruction.
720 } else if (SwapVector
[EntryIdx
].IsStore
&& SwapVector
[EntryIdx
].IsSwap
) {
721 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
722 Register UseReg
= MI
->getOperand(0).getReg();
723 MachineInstr
*DefMI
= MRI
->getVRegDef(UseReg
);
724 Register DefReg
= DefMI
->getOperand(0).getReg();
725 int DefIdx
= SwapMap
[DefMI
];
727 if (!SwapVector
[DefIdx
].IsSwap
|| SwapVector
[DefIdx
].IsLoad
||
728 SwapVector
[DefIdx
].IsStore
) {
730 SwapVector
[Repr
].WebRejected
= 1;
732 LLVM_DEBUG(dbgs() << format(
733 "Web %d rejected for store not fed by swap\n", Repr
));
734 LLVM_DEBUG(dbgs() << " def " << DefIdx
<< ": ");
735 LLVM_DEBUG(DefMI
->dump());
736 LLVM_DEBUG(dbgs() << " use " << EntryIdx
<< ": ");
737 LLVM_DEBUG(MI
->dump());
738 LLVM_DEBUG(dbgs() << "\n");
741 // Ensure all uses of the register defined by DefMI feed store
743 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(DefReg
)) {
744 int UseIdx
= SwapMap
[&UseMI
];
746 if (SwapVector
[UseIdx
].VSEMI
->getOpcode() != MI
->getOpcode()) {
747 SwapVector
[Repr
].WebRejected
= 1;
751 "Web %d rejected for swap not feeding only stores\n", Repr
));
752 LLVM_DEBUG(dbgs() << " def "
754 LLVM_DEBUG(DefMI
->dump());
755 LLVM_DEBUG(dbgs() << " use " << UseIdx
<< ": ");
756 LLVM_DEBUG(SwapVector
[UseIdx
].VSEMI
->dump());
757 LLVM_DEBUG(dbgs() << "\n");
763 LLVM_DEBUG(dbgs() << "Swap vector after web analysis:\n\n");
764 LLVM_DEBUG(dumpSwapVector());
767 // Walk the swap vector entries looking for swaps fed by permuting loads
768 // and swaps that feed permuting stores. If the containing computation
769 // has not been marked rejected, mark each such swap for removal.
770 // (Removal is delayed in case optimization has disturbed the pattern,
771 // such that multiple loads feed the same swap, etc.)
772 void PPCVSXSwapRemoval::markSwapsForRemoval() {
774 LLVM_DEBUG(dbgs() << "\n*** Marking swaps for removal ***\n\n");
776 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
778 if (SwapVector
[EntryIdx
].IsLoad
&& SwapVector
[EntryIdx
].IsSwap
) {
779 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
781 if (!SwapVector
[Repr
].WebRejected
) {
782 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
783 Register DefReg
= MI
->getOperand(0).getReg();
785 for (MachineInstr
&UseMI
: MRI
->use_nodbg_instructions(DefReg
)) {
786 int UseIdx
= SwapMap
[&UseMI
];
787 SwapVector
[UseIdx
].WillRemove
= 1;
789 LLVM_DEBUG(dbgs() << "Marking swap fed by load for removal: ");
790 LLVM_DEBUG(UseMI
.dump());
794 } else if (SwapVector
[EntryIdx
].IsStore
&& SwapVector
[EntryIdx
].IsSwap
) {
795 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
797 if (!SwapVector
[Repr
].WebRejected
) {
798 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
799 Register UseReg
= MI
->getOperand(0).getReg();
800 MachineInstr
*DefMI
= MRI
->getVRegDef(UseReg
);
801 int DefIdx
= SwapMap
[DefMI
];
802 SwapVector
[DefIdx
].WillRemove
= 1;
804 LLVM_DEBUG(dbgs() << "Marking swap feeding store for removal: ");
805 LLVM_DEBUG(DefMI
->dump());
808 } else if (SwapVector
[EntryIdx
].IsSwappable
&&
809 SwapVector
[EntryIdx
].SpecialHandling
!= 0) {
810 int Repr
= EC
->getLeaderValue(SwapVector
[EntryIdx
].VSEId
);
812 if (!SwapVector
[Repr
].WebRejected
)
813 handleSpecialSwappables(EntryIdx
);
818 // Create an xxswapd instruction and insert it prior to the given point.
819 // MI is used to determine basic block and debug loc information.
820 // FIXME: When inserting a swap, we should check whether SrcReg is
821 // defined by another swap: SrcReg = XXPERMDI Reg, Reg, 2; If so,
822 // then instead we should generate a copy from Reg to DstReg.
823 void PPCVSXSwapRemoval::insertSwap(MachineInstr
*MI
,
824 MachineBasicBlock::iterator InsertPoint
,
825 unsigned DstReg
, unsigned SrcReg
) {
826 BuildMI(*MI
->getParent(), InsertPoint
, MI
->getDebugLoc(),
827 TII
->get(PPC::XXPERMDI
), DstReg
)
833 // The identified swap entry requires special handling to allow its
834 // containing computation to be optimized. Perform that handling
836 // FIXME: Additional opportunities will be phased in with subsequent
838 void PPCVSXSwapRemoval::handleSpecialSwappables(int EntryIdx
) {
839 switch (SwapVector
[EntryIdx
].SpecialHandling
) {
842 llvm_unreachable("Unexpected special handling type");
844 // For splats based on an index into a vector, add N/2 modulo N
845 // to the index, where N is the number of vector elements.
846 case SHValues::SH_SPLAT
: {
847 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
850 LLVM_DEBUG(dbgs() << "Changing splat: ");
851 LLVM_DEBUG(MI
->dump());
853 switch (MI
->getOpcode()) {
855 llvm_unreachable("Unexpected splat opcode");
856 case PPC::VSPLTB
: NElts
= 16; break;
857 case PPC::VSPLTH
: NElts
= 8; break;
859 case PPC::XXSPLTW
: NElts
= 4; break;
863 if (MI
->getOpcode() == PPC::XXSPLTW
)
864 EltNo
= MI
->getOperand(2).getImm();
866 EltNo
= MI
->getOperand(1).getImm();
868 EltNo
= (EltNo
+ NElts
/ 2) % NElts
;
869 if (MI
->getOpcode() == PPC::XXSPLTW
)
870 MI
->getOperand(2).setImm(EltNo
);
872 MI
->getOperand(1).setImm(EltNo
);
874 LLVM_DEBUG(dbgs() << " Into: ");
875 LLVM_DEBUG(MI
->dump());
879 // For an XXPERMDI that isn't handled otherwise, we need to
880 // reverse the order of the operands. If the selector operand
881 // has a value of 0 or 3, we need to change it to 3 or 0,
882 // respectively. Otherwise we should leave it alone. (This
883 // is equivalent to reversing the two bits of the selector
884 // operand and complementing the result.)
885 case SHValues::SH_XXPERMDI
: {
886 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
888 LLVM_DEBUG(dbgs() << "Changing XXPERMDI: ");
889 LLVM_DEBUG(MI
->dump());
891 unsigned Selector
= MI
->getOperand(3).getImm();
892 if (Selector
== 0 || Selector
== 3)
893 Selector
= 3 - Selector
;
894 MI
->getOperand(3).setImm(Selector
);
896 Register Reg1
= MI
->getOperand(1).getReg();
897 Register Reg2
= MI
->getOperand(2).getReg();
898 MI
->getOperand(1).setReg(Reg2
);
899 MI
->getOperand(2).setReg(Reg1
);
901 // We also need to swap kill flag associated with the register.
902 bool IsKill1
= MI
->getOperand(1).isKill();
903 bool IsKill2
= MI
->getOperand(2).isKill();
904 MI
->getOperand(1).setIsKill(IsKill2
);
905 MI
->getOperand(2).setIsKill(IsKill1
);
907 LLVM_DEBUG(dbgs() << " Into: ");
908 LLVM_DEBUG(MI
->dump());
912 // For a copy from a scalar floating-point register to a vector
913 // register, removing swaps will leave the copied value in the
914 // wrong lane. Insert a swap following the copy to fix this.
915 case SHValues::SH_COPYWIDEN
: {
916 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
918 LLVM_DEBUG(dbgs() << "Changing SUBREG_TO_REG: ");
919 LLVM_DEBUG(MI
->dump());
921 Register DstReg
= MI
->getOperand(0).getReg();
922 const TargetRegisterClass
*DstRC
= MRI
->getRegClass(DstReg
);
923 Register NewVReg
= MRI
->createVirtualRegister(DstRC
);
925 MI
->getOperand(0).setReg(NewVReg
);
926 LLVM_DEBUG(dbgs() << " Into: ");
927 LLVM_DEBUG(MI
->dump());
929 auto InsertPoint
= ++MachineBasicBlock::iterator(MI
);
931 // Note that an XXPERMDI requires a VSRC, so if the SUBREG_TO_REG
932 // is copying to a VRRC, we need to be careful to avoid a register
933 // assignment problem. In this case we must copy from VRRC to VSRC
934 // prior to the swap, and from VSRC to VRRC following the swap.
935 // Coalescing will usually remove all this mess.
936 if (DstRC
== &PPC::VRRCRegClass
) {
937 Register VSRCTmp1
= MRI
->createVirtualRegister(&PPC::VSRCRegClass
);
938 Register VSRCTmp2
= MRI
->createVirtualRegister(&PPC::VSRCRegClass
);
940 BuildMI(*MI
->getParent(), InsertPoint
, MI
->getDebugLoc(),
941 TII
->get(PPC::COPY
), VSRCTmp1
)
943 LLVM_DEBUG(std::prev(InsertPoint
)->dump());
945 insertSwap(MI
, InsertPoint
, VSRCTmp2
, VSRCTmp1
);
946 LLVM_DEBUG(std::prev(InsertPoint
)->dump());
948 BuildMI(*MI
->getParent(), InsertPoint
, MI
->getDebugLoc(),
949 TII
->get(PPC::COPY
), DstReg
)
951 LLVM_DEBUG(std::prev(InsertPoint
)->dump());
954 insertSwap(MI
, InsertPoint
, DstReg
, NewVReg
);
955 LLVM_DEBUG(std::prev(InsertPoint
)->dump());
962 // Walk the swap vector and replace each entry marked for removal with
964 bool PPCVSXSwapRemoval::removeSwaps() {
966 LLVM_DEBUG(dbgs() << "\n*** Removing swaps ***\n\n");
968 bool Changed
= false;
970 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
971 if (SwapVector
[EntryIdx
].WillRemove
) {
973 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
974 MachineBasicBlock
*MBB
= MI
->getParent();
975 BuildMI(*MBB
, MI
, MI
->getDebugLoc(), TII
->get(TargetOpcode::COPY
),
976 MI
->getOperand(0).getReg())
977 .add(MI
->getOperand(1));
979 LLVM_DEBUG(dbgs() << format("Replaced %d with copy: ",
980 SwapVector
[EntryIdx
].VSEId
));
981 LLVM_DEBUG(MI
->dump());
983 MI
->eraseFromParent();
990 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
991 // For debug purposes, dump the contents of the swap vector.
992 LLVM_DUMP_METHOD
void PPCVSXSwapRemoval::dumpSwapVector() {
994 for (unsigned EntryIdx
= 0; EntryIdx
< SwapVector
.size(); ++EntryIdx
) {
996 MachineInstr
*MI
= SwapVector
[EntryIdx
].VSEMI
;
997 int ID
= SwapVector
[EntryIdx
].VSEId
;
999 dbgs() << format("%6d", ID
);
1000 dbgs() << format("%6d", EC
->getLeaderValue(ID
));
1001 dbgs() << format(" %bb.%3d", MI
->getParent()->getNumber());
1002 dbgs() << format(" %14s ", TII
->getName(MI
->getOpcode()).str().c_str());
1004 if (SwapVector
[EntryIdx
].IsLoad
)
1006 if (SwapVector
[EntryIdx
].IsStore
)
1008 if (SwapVector
[EntryIdx
].IsSwap
)
1010 if (SwapVector
[EntryIdx
].MentionsPhysVR
)
1011 dbgs() << "physreg ";
1012 if (SwapVector
[EntryIdx
].MentionsPartialVR
)
1013 dbgs() << "partialreg ";
1015 if (SwapVector
[EntryIdx
].IsSwappable
) {
1016 dbgs() << "swappable ";
1017 switch(SwapVector
[EntryIdx
].SpecialHandling
) {
1019 dbgs() << "special:**unknown**";
1024 dbgs() << "special:extract ";
1027 dbgs() << "special:insert ";
1030 dbgs() << "special:load ";
1033 dbgs() << "special:store ";
1036 dbgs() << "special:splat ";
1039 dbgs() << "special:xxpermdi ";
1042 dbgs() << "special:copywiden ";
1047 if (SwapVector
[EntryIdx
].WebRejected
)
1048 dbgs() << "rejected ";
1049 if (SwapVector
[EntryIdx
].WillRemove
)
1050 dbgs() << "remove ";
1054 // For no-asserts builds.
1063 } // end default namespace
1065 INITIALIZE_PASS_BEGIN(PPCVSXSwapRemoval
, DEBUG_TYPE
,
1066 "PowerPC VSX Swap Removal", false, false)
1067 INITIALIZE_PASS_END(PPCVSXSwapRemoval
, DEBUG_TYPE
,
1068 "PowerPC VSX Swap Removal", false, false)
1070 char PPCVSXSwapRemoval::ID
= 0;
1072 llvm::createPPCVSXSwapRemovalPass() { return new PPCVSXSwapRemoval(); }