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 //===---------------------------------------------------------------------===//
45 #include "PPCInstrInfo.h"
47 #include "PPCInstrBuilder.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/Support/Debug.h"
55 #include "llvm/Support/Format.h"
56 #include "llvm/Support/raw_ostream.h"
60 #define DEBUG_TYPE "ppc-vsx-swaps"
63 void initializePPCVSXSwapRemovalPass(PassRegistry&);
68 // A PPCVSXSwapEntry is created for each machine instruction that
69 // is relevant to a vector computation.
70 struct PPCVSXSwapEntry {
71 // Pointer to the instruction.
74 // Unique ID (position in the swap vector).
77 // Attributes of this node.
78 unsigned int IsLoad : 1;
79 unsigned int IsStore : 1;
80 unsigned int IsSwap : 1;
81 unsigned int MentionsPhysVR : 1;
82 unsigned int IsSwappable : 1;
83 unsigned int MentionsPartialVR : 1;
84 unsigned int SpecialHandling : 3;
85 unsigned int WebRejected : 1;
86 unsigned int WillRemove : 1;
100 struct PPCVSXSwapRemoval : public MachineFunctionPass {
103 const PPCInstrInfo *TII;
105 MachineRegisterInfo *MRI;
107 // Swap entries are allocated in a vector for better performance.
108 std::vector<PPCVSXSwapEntry> SwapVector;
110 // A mapping is maintained between machine instructions and
111 // their swap entries. The key is the address of the MI.
112 DenseMap<MachineInstr*, int> SwapMap;
114 // Equivalence classes are used to gather webs of related computation.
115 // Swap entries are represented by their VSEId fields.
116 EquivalenceClasses<int> *EC;
118 PPCVSXSwapRemoval() : MachineFunctionPass(ID) {
119 initializePPCVSXSwapRemovalPass(*PassRegistry::getPassRegistry());
123 // Initialize data structures.
124 void initialize(MachineFunction &MFParm);
126 // Walk the machine instructions to gather vector usage information.
127 // Return true iff vector mentions are present.
128 bool gatherVectorInstructions();
130 // Add an entry to the swap vector and swap map.
131 int addSwapEntry(MachineInstr *MI, PPCVSXSwapEntry &SwapEntry);
133 // Hunt backwards through COPY and SUBREG_TO_REG chains for a
134 // source register. VecIdx indicates the swap vector entry to
135 // mark as mentioning a physical register if the search leads
137 unsigned lookThruCopyLike(unsigned SrcReg, unsigned VecIdx);
139 // Generate equivalence classes for related computations (webs).
142 // Analyze webs and determine those that cannot be optimized.
143 void recordUnoptimizableWebs();
145 // Record which swap instructions can be safely removed.
146 void markSwapsForRemoval();
148 // Remove swaps and update other instructions requiring special
149 // handling. Return true iff any changes are made.
152 // Insert a swap instruction from SrcReg to DstReg at the given
154 void insertSwap(MachineInstr *MI, MachineBasicBlock::iterator InsertPoint,
155 unsigned DstReg, unsigned SrcReg);
157 // Update instructions requiring special handling.
158 void handleSpecialSwappables(int EntryIdx);
160 // Dump a description of the entries in the swap vector.
161 void dumpSwapVector();
163 // Return true iff the given register is in the given class.
164 bool isRegInClass(unsigned Reg, const TargetRegisterClass *RC) {
165 if (TargetRegisterInfo::isVirtualRegister(Reg))
166 return RC->hasSubClassEq(MRI->getRegClass(Reg));
167 if (RC->contains(Reg))
172 // Return true iff the given register is a full vector register.
173 bool isVecReg(unsigned Reg) {
174 return (isRegInClass(Reg, &PPC::VSRCRegClass) ||
175 isRegInClass(Reg, &PPC::VRRCRegClass));
178 // Return true iff the given register is a partial vector register.
179 bool isScalarVecReg(unsigned Reg) {
180 return (isRegInClass(Reg, &PPC::VSFRCRegClass) ||
181 isRegInClass(Reg, &PPC::VSSRCRegClass));
184 // Return true iff the given register mentions all or part of a
185 // vector register. Also sets Partial to true if the mention
186 // is for just the floating-point register overlap of the register.
187 bool isAnyVecReg(unsigned Reg, bool &Partial) {
188 if (isScalarVecReg(Reg))
190 return isScalarVecReg(Reg) || isVecReg(Reg);
194 // Main entry point for this pass.
195 bool runOnMachineFunction(MachineFunction &MF) override {
196 // If we don't have VSX on the subtarget, don't do anything.
197 const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>();
201 bool Changed = false;
204 if (gatherVectorInstructions()) {
206 recordUnoptimizableWebs();
207 markSwapsForRemoval();
208 Changed = removeSwaps();
211 // FIXME: See the allocation of EC in initialize().
217 // Initialize data structures for this pass. In particular, clear the
218 // swap vector and allocate the equivalence class mapping before
219 // processing each function.
220 void PPCVSXSwapRemoval::initialize(MachineFunction &MFParm) {
222 MRI = &MF->getRegInfo();
223 TII = static_cast<const PPCInstrInfo*>(MF->getSubtarget().getInstrInfo());
225 // An initial vector size of 256 appears to work well in practice.
226 // Small/medium functions with vector content tend not to incur a
227 // reallocation at this size. Three of the vector tests in
228 // projects/test-suite reallocate, which seems like a reasonable rate.
229 const int InitialVectorSize(256);
231 SwapVector.reserve(InitialVectorSize);
233 // FIXME: Currently we allocate EC each time because we don't have
234 // access to the set representation on which to call clear(). Should
235 // consider adding a clear() method to the EquivalenceClasses class.
236 EC = new EquivalenceClasses<int>;
239 // Create an entry in the swap vector for each instruction that mentions
240 // a full vector register, recording various characteristics of the
241 // instructions there.
242 bool PPCVSXSwapRemoval::gatherVectorInstructions() {
243 bool RelevantFunction = false;
245 for (MachineBasicBlock &MBB : *MF) {
246 for (MachineInstr &MI : MBB) {
248 bool RelevantInstr = false;
249 bool Partial = false;
251 for (const MachineOperand &MO : MI.operands()) {
254 unsigned Reg = MO.getReg();
255 if (isAnyVecReg(Reg, Partial)) {
256 RelevantInstr = true;
264 RelevantFunction = true;
266 // Create a SwapEntry initialized to zeros, then fill in the
267 // instruction and ID fields before pushing it to the back
268 // of the swap vector.
269 PPCVSXSwapEntry SwapEntry{};
270 int VecIdx = addSwapEntry(&MI, SwapEntry);
272 switch(MI.getOpcode()) {
274 // Unless noted otherwise, an instruction is considered
275 // safe for the optimization. There are a large number of
276 // such true-SIMD instructions (all vector math, logical,
277 // select, compare, etc.). However, if the instruction
278 // mentions a partial vector register and does not have
279 // special handling defined, it is not swappable.
281 SwapVector[VecIdx].MentionsPartialVR = 1;
283 SwapVector[VecIdx].IsSwappable = 1;
285 case PPC::XXPERMDI: {
286 // This is a swap if it is of the form XXPERMDI t, s, s, 2.
287 // Unfortunately, MachineCSE ignores COPY and SUBREG_TO_REG, so we
288 // can also see XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), 2,
289 // for example. We have to look through chains of COPY and
290 // SUBREG_TO_REG to find the real source value for comparison.
291 // If the real source value is a physical register, then mark the
292 // XXPERMDI as mentioning a physical register.
293 int immed = MI.getOperand(3).getImm();
295 unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(),
297 unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(),
299 if (trueReg1 == trueReg2)
300 SwapVector[VecIdx].IsSwap = 1;
302 // We can still handle these if the two registers are not
303 // identical, by adjusting the form of the XXPERMDI.
304 SwapVector[VecIdx].IsSwappable = 1;
305 SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
307 // This is a doubleword splat if it is of the form
308 // XXPERMDI t, s, s, 0 or XXPERMDI t, s, s, 3. As above we
309 // must look through chains of copy-likes to find the source
310 // register. We turn off the marking for mention of a physical
311 // register, because splatting it is safe; the optimization
312 // will not swap the value in the physical register. Whether
313 // or not the two input registers are identical, we can handle
314 // these by adjusting the form of the XXPERMDI.
315 } else if (immed == 0 || immed == 3) {
317 SwapVector[VecIdx].IsSwappable = 1;
318 SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
320 unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(),
322 unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(),
324 if (trueReg1 == trueReg2)
325 SwapVector[VecIdx].MentionsPhysVR = 0;
328 // We can still handle these by adjusting the form of the XXPERMDI.
329 SwapVector[VecIdx].IsSwappable = 1;
330 SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
335 // Non-permuting loads are currently unsafe. We can use special
336 // handling for this in the future. By not marking these as
337 // IsSwap, we ensure computations containing them will be rejected
339 SwapVector[VecIdx].IsLoad = 1;
343 // Permuting loads are marked as both load and swap, and are
344 // safe for optimization.
345 SwapVector[VecIdx].IsLoad = 1;
346 SwapVector[VecIdx].IsSwap = 1;
350 // A load of a floating-point value into the high-order half of
351 // a vector register is safe, provided that we introduce a swap
352 // following the load, which will be done by the SUBREG_TO_REG
353 // support. So just mark these as safe.
354 SwapVector[VecIdx].IsLoad = 1;
355 SwapVector[VecIdx].IsSwappable = 1;
358 // Non-permuting stores are currently unsafe. We can use special
359 // handling for this in the future. By not marking these as
360 // IsSwap, we ensure computations containing them will be rejected
362 SwapVector[VecIdx].IsStore = 1;
366 // Permuting stores are marked as both store and swap, and are
367 // safe for optimization.
368 SwapVector[VecIdx].IsStore = 1;
369 SwapVector[VecIdx].IsSwap = 1;
372 // These are fine provided they are moving between full vector
374 if (isVecReg(MI.getOperand(0).getReg()) &&
375 isVecReg(MI.getOperand(1).getReg()))
376 SwapVector[VecIdx].IsSwappable = 1;
377 // If we have a copy from one scalar floating-point register
378 // to another, we can accept this even if it is a physical
379 // register. The only way this gets involved is if it feeds
380 // a SUBREG_TO_REG, which is handled by introducing a swap.
381 else if (isScalarVecReg(MI.getOperand(0).getReg()) &&
382 isScalarVecReg(MI.getOperand(1).getReg()))
383 SwapVector[VecIdx].IsSwappable = 1;
385 case PPC::SUBREG_TO_REG: {
386 // These are fine provided they are moving between full vector
387 // register classes. If they are moving from a scalar
388 // floating-point class to a vector class, we can handle those
389 // as well, provided we introduce a swap. It is generally the
390 // case that we will introduce fewer swaps than we remove, but
391 // (FIXME) a cost model could be used. However, introduced
392 // swaps could potentially be CSEd, so this is not trivial.
393 if (isVecReg(MI.getOperand(0).getReg()) &&
394 isVecReg(MI.getOperand(2).getReg()))
395 SwapVector[VecIdx].IsSwappable = 1;
396 else if (isVecReg(MI.getOperand(0).getReg()) &&
397 isScalarVecReg(MI.getOperand(2).getReg())) {
398 SwapVector[VecIdx].IsSwappable = 1;
399 SwapVector[VecIdx].SpecialHandling = SHValues::SH_COPYWIDEN;
406 // Splats are lane-sensitive, but we can use special handling
407 // to adjust the source lane for the splat. This is not yet
408 // implemented. When it is, we need to uncomment the following:
409 SwapVector[VecIdx].IsSwappable = 1;
410 SwapVector[VecIdx].SpecialHandling = SHValues::SH_SPLAT;
412 // The presence of the following lane-sensitive operations in a
413 // web will kill the optimization, at least for now. For these
414 // we do nothing, causing the optimization to fail.
415 // FIXME: Some of these could be permitted with special handling,
416 // and will be phased in as time permits.
417 // FIXME: There is no simple and maintainable way to express a set
418 // of opcodes having a common attribute in TableGen. Should this
419 // change, this is a prime candidate to use such a mechanism.
421 case PPC::EXTRACT_SUBREG:
422 case PPC::INSERT_SUBREG:
423 case PPC::COPY_TO_REGCLASS:
434 // We can handle STXSDX and STXSSPX similarly to LXSDX and LXSSPX,
435 // by adding special handling for narrowing copies as well as
436 // widening ones. However, I've experimented with this, and in
437 // practice we currently do not appear to use STXSDX fed by
438 // a narrowing copy from a full vector register. Since I can't
439 // generate any useful test cases, I've left this alone for now.
443 case PPC::VCIPHERLAST:
463 case PPC::VNCIPHERLAST:
488 case PPC::VSHASIGMAD:
489 case PPC::VSHASIGMAW:
510 // XXSLDWI could be replaced by a general permute with one of three
511 // permute control vectors (for shift values 1, 2, 3). However,
512 // VPERM has a more restrictive register class.
520 if (RelevantFunction) {
521 DEBUG(dbgs() << "Swap vector when first built\n\n");
525 return RelevantFunction;
528 // Add an entry to the swap vector and swap map, and make a
529 // singleton equivalence class for the entry.
530 int PPCVSXSwapRemoval::addSwapEntry(MachineInstr *MI,
531 PPCVSXSwapEntry& SwapEntry) {
532 SwapEntry.VSEMI = MI;
533 SwapEntry.VSEId = SwapVector.size();
534 SwapVector.push_back(SwapEntry);
535 EC->insert(SwapEntry.VSEId);
536 SwapMap[MI] = SwapEntry.VSEId;
537 return SwapEntry.VSEId;
540 // This is used to find the "true" source register for an
541 // XXPERMDI instruction, since MachineCSE does not handle the
542 // "copy-like" operations (Copy and SubregToReg). Returns
543 // the original SrcReg unless it is the target of a copy-like
544 // operation, in which case we chain backwards through all
545 // such operations to the ultimate source register. If a
546 // physical register is encountered, we stop the search and
547 // flag the swap entry indicated by VecIdx (the original
548 // XXPERMDI) as mentioning a physical register.
549 unsigned PPCVSXSwapRemoval::lookThruCopyLike(unsigned SrcReg,
551 MachineInstr *MI = MRI->getVRegDef(SrcReg);
552 if (!MI->isCopyLike())
557 CopySrcReg = MI->getOperand(1).getReg();
559 assert(MI->isSubregToReg() && "bad opcode for lookThruCopyLike");
560 CopySrcReg = MI->getOperand(2).getReg();
563 if (!TargetRegisterInfo::isVirtualRegister(CopySrcReg)) {
564 if (!isScalarVecReg(CopySrcReg))
565 SwapVector[VecIdx].MentionsPhysVR = 1;
569 return lookThruCopyLike(CopySrcReg, VecIdx);
572 // Generate equivalence classes for related computations (webs) by
573 // def-use relationships of virtual registers. Mention of a physical
574 // register terminates the generation of equivalence classes as this
575 // indicates a use of a parameter, definition of a return value, use
576 // of a value returned from a call, or definition of a parameter to a
577 // call. Computations with physical register mentions are flagged
578 // as such so their containing webs will not be optimized.
579 void PPCVSXSwapRemoval::formWebs() {
581 DEBUG(dbgs() << "\n*** Forming webs for swap removal ***\n\n");
583 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
585 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
587 DEBUG(dbgs() << "\n" << SwapVector[EntryIdx].VSEId << " ");
590 // It's sufficient to walk vector uses and join them to their unique
591 // definitions. In addition, check full vector register operands
592 // for physical regs. We exclude partial-vector register operands
593 // because we can handle them if copied to a full vector.
594 for (const MachineOperand &MO : MI->operands()) {
598 unsigned Reg = MO.getReg();
599 if (!isVecReg(Reg) && !isScalarVecReg(Reg))
602 if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
603 if (!(MI->isCopy() && isScalarVecReg(Reg)))
604 SwapVector[EntryIdx].MentionsPhysVR = 1;
611 MachineInstr* DefMI = MRI->getVRegDef(Reg);
612 assert(SwapMap.find(DefMI) != SwapMap.end() &&
613 "Inconsistency: def of vector reg not found in swap map!");
614 int DefIdx = SwapMap[DefMI];
615 (void)EC->unionSets(SwapVector[DefIdx].VSEId,
616 SwapVector[EntryIdx].VSEId);
618 DEBUG(dbgs() << format("Unioning %d with %d\n", SwapVector[DefIdx].VSEId,
619 SwapVector[EntryIdx].VSEId));
620 DEBUG(dbgs() << " Def: ");
621 DEBUG(DefMI->dump());
626 // Walk the swap vector entries looking for conditions that prevent their
627 // containing computations from being optimized. When such conditions are
628 // found, mark the representative of the computation's equivalence class
630 void PPCVSXSwapRemoval::recordUnoptimizableWebs() {
632 DEBUG(dbgs() << "\n*** Rejecting webs for swap removal ***\n\n");
634 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
635 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
637 // If representative is already rejected, don't waste further time.
638 if (SwapVector[Repr].WebRejected)
641 // Reject webs containing mentions of physical or partial registers, or
642 // containing operations that we don't know how to handle in a lane-
644 if (SwapVector[EntryIdx].MentionsPhysVR ||
645 SwapVector[EntryIdx].MentionsPartialVR ||
646 !(SwapVector[EntryIdx].IsSwappable || SwapVector[EntryIdx].IsSwap)) {
648 SwapVector[Repr].WebRejected = 1;
651 format("Web %d rejected for physreg, partial reg, or not "
652 "swap[pable]\n", Repr));
653 DEBUG(dbgs() << " in " << EntryIdx << ": ");
654 DEBUG(SwapVector[EntryIdx].VSEMI->dump());
655 DEBUG(dbgs() << "\n");
658 // Reject webs than contain swapping loads that feed something other
659 // than a swap instruction.
660 else if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
661 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
662 unsigned DefReg = MI->getOperand(0).getReg();
664 // We skip debug instructions in the analysis. (Note that debug
665 // location information is still maintained by this optimization
666 // because it remains on the LXVD2X and STXVD2X instructions after
667 // the XXPERMDIs are removed.)
668 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
669 int UseIdx = SwapMap[&UseMI];
671 if (!SwapVector[UseIdx].IsSwap || SwapVector[UseIdx].IsLoad ||
672 SwapVector[UseIdx].IsStore) {
674 SwapVector[Repr].WebRejected = 1;
677 format("Web %d rejected for load not feeding swap\n", Repr));
678 DEBUG(dbgs() << " def " << EntryIdx << ": ");
680 DEBUG(dbgs() << " use " << UseIdx << ": ");
682 DEBUG(dbgs() << "\n");
686 // Reject webs that contain swapping stores that are fed by something
687 // other than a swap instruction.
688 } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
689 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
690 unsigned UseReg = MI->getOperand(0).getReg();
691 MachineInstr *DefMI = MRI->getVRegDef(UseReg);
692 int DefIdx = SwapMap[DefMI];
694 if (!SwapVector[DefIdx].IsSwap || SwapVector[DefIdx].IsLoad ||
695 SwapVector[DefIdx].IsStore) {
697 SwapVector[Repr].WebRejected = 1;
700 format("Web %d rejected for store not fed by swap\n", Repr));
701 DEBUG(dbgs() << " def " << DefIdx << ": ");
702 DEBUG(DefMI->dump());
703 DEBUG(dbgs() << " use " << EntryIdx << ": ");
705 DEBUG(dbgs() << "\n");
710 DEBUG(dbgs() << "Swap vector after web analysis:\n\n");
714 // Walk the swap vector entries looking for swaps fed by permuting loads
715 // and swaps that feed permuting stores. If the containing computation
716 // has not been marked rejected, mark each such swap for removal.
717 // (Removal is delayed in case optimization has disturbed the pattern,
718 // such that multiple loads feed the same swap, etc.)
719 void PPCVSXSwapRemoval::markSwapsForRemoval() {
721 DEBUG(dbgs() << "\n*** Marking swaps for removal ***\n\n");
723 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
725 if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
726 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
728 if (!SwapVector[Repr].WebRejected) {
729 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
730 unsigned DefReg = MI->getOperand(0).getReg();
732 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
733 int UseIdx = SwapMap[&UseMI];
734 SwapVector[UseIdx].WillRemove = 1;
736 DEBUG(dbgs() << "Marking swap fed by load for removal: ");
741 } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
742 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
744 if (!SwapVector[Repr].WebRejected) {
745 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
746 unsigned UseReg = MI->getOperand(0).getReg();
747 MachineInstr *DefMI = MRI->getVRegDef(UseReg);
748 int DefIdx = SwapMap[DefMI];
749 SwapVector[DefIdx].WillRemove = 1;
751 DEBUG(dbgs() << "Marking swap feeding store for removal: ");
752 DEBUG(DefMI->dump());
755 } else if (SwapVector[EntryIdx].IsSwappable &&
756 SwapVector[EntryIdx].SpecialHandling != 0) {
757 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
759 if (!SwapVector[Repr].WebRejected)
760 handleSpecialSwappables(EntryIdx);
765 // Create an xxswapd instruction and insert it prior to the given point.
766 // MI is used to determine basic block and debug loc information.
767 // FIXME: When inserting a swap, we should check whether SrcReg is
768 // defined by another swap: SrcReg = XXPERMDI Reg, Reg, 2; If so,
769 // then instead we should generate a copy from Reg to DstReg.
770 void PPCVSXSwapRemoval::insertSwap(MachineInstr *MI,
771 MachineBasicBlock::iterator InsertPoint,
772 unsigned DstReg, unsigned SrcReg) {
773 BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
774 TII->get(PPC::XXPERMDI), DstReg)
780 // The identified swap entry requires special handling to allow its
781 // containing computation to be optimized. Perform that handling
783 // FIXME: Additional opportunities will be phased in with subsequent
785 void PPCVSXSwapRemoval::handleSpecialSwappables(int EntryIdx) {
786 switch (SwapVector[EntryIdx].SpecialHandling) {
789 assert(false && "Unexpected special handling type");
792 // For splats based on an index into a vector, add N/2 modulo N
793 // to the index, where N is the number of vector elements.
794 case SHValues::SH_SPLAT: {
795 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
798 DEBUG(dbgs() << "Changing splat: ");
801 switch (MI->getOpcode()) {
803 assert(false && "Unexpected splat opcode");
804 case PPC::VSPLTB: NElts = 16; break;
805 case PPC::VSPLTH: NElts = 8; break;
806 case PPC::VSPLTW: NElts = 4; break;
809 unsigned EltNo = MI->getOperand(1).getImm();
810 EltNo = (EltNo + NElts / 2) % NElts;
811 MI->getOperand(1).setImm(EltNo);
813 DEBUG(dbgs() << " Into: ");
818 // For an XXPERMDI that isn't handled otherwise, we need to
819 // reverse the order of the operands. If the selector operand
820 // has a value of 0 or 3, we need to change it to 3 or 0,
821 // respectively. Otherwise we should leave it alone. (This
822 // is equivalent to reversing the two bits of the selector
823 // operand and complementing the result.)
824 case SHValues::SH_XXPERMDI: {
825 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
827 DEBUG(dbgs() << "Changing XXPERMDI: ");
830 unsigned Selector = MI->getOperand(3).getImm();
831 if (Selector == 0 || Selector == 3)
832 Selector = 3 - Selector;
833 MI->getOperand(3).setImm(Selector);
835 unsigned Reg1 = MI->getOperand(1).getReg();
836 unsigned Reg2 = MI->getOperand(2).getReg();
837 MI->getOperand(1).setReg(Reg2);
838 MI->getOperand(2).setReg(Reg1);
840 DEBUG(dbgs() << " Into: ");
845 // For a copy from a scalar floating-point register to a vector
846 // register, removing swaps will leave the copied value in the
847 // wrong lane. Insert a swap following the copy to fix this.
848 case SHValues::SH_COPYWIDEN: {
849 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
851 DEBUG(dbgs() << "Changing SUBREG_TO_REG: ");
854 unsigned DstReg = MI->getOperand(0).getReg();
855 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
856 unsigned NewVReg = MRI->createVirtualRegister(DstRC);
858 MI->getOperand(0).setReg(NewVReg);
859 DEBUG(dbgs() << " Into: ");
862 MachineBasicBlock::iterator InsertPoint = MI->getNextNode();
864 // Note that an XXPERMDI requires a VSRC, so if the SUBREG_TO_REG
865 // is copying to a VRRC, we need to be careful to avoid a register
866 // assignment problem. In this case we must copy from VRRC to VSRC
867 // prior to the swap, and from VSRC to VRRC following the swap.
868 // Coalescing will usually remove all this mess.
869 if (DstRC == &PPC::VRRCRegClass) {
870 unsigned VSRCTmp1 = MRI->createVirtualRegister(&PPC::VSRCRegClass);
871 unsigned VSRCTmp2 = MRI->createVirtualRegister(&PPC::VSRCRegClass);
873 BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
874 TII->get(PPC::COPY), VSRCTmp1)
876 DEBUG(MI->getNextNode()->dump());
878 insertSwap(MI, InsertPoint, VSRCTmp2, VSRCTmp1);
879 DEBUG(MI->getNextNode()->getNextNode()->dump());
881 BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
882 TII->get(PPC::COPY), DstReg)
884 DEBUG(MI->getNextNode()->getNextNode()->getNextNode()->dump());
887 insertSwap(MI, InsertPoint, DstReg, NewVReg);
888 DEBUG(MI->getNextNode()->dump());
895 // Walk the swap vector and replace each entry marked for removal with
897 bool PPCVSXSwapRemoval::removeSwaps() {
899 DEBUG(dbgs() << "\n*** Removing swaps ***\n\n");
901 bool Changed = false;
903 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
904 if (SwapVector[EntryIdx].WillRemove) {
906 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
907 MachineBasicBlock *MBB = MI->getParent();
908 BuildMI(*MBB, MI, MI->getDebugLoc(),
909 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
910 .addOperand(MI->getOperand(1));
912 DEBUG(dbgs() << format("Replaced %d with copy: ",
913 SwapVector[EntryIdx].VSEId));
916 MI->eraseFromParent();
923 // For debug purposes, dump the contents of the swap vector.
924 void PPCVSXSwapRemoval::dumpSwapVector() {
926 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
928 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
929 int ID = SwapVector[EntryIdx].VSEId;
931 DEBUG(dbgs() << format("%6d", ID));
932 DEBUG(dbgs() << format("%6d", EC->getLeaderValue(ID)));
933 DEBUG(dbgs() << format(" BB#%3d", MI->getParent()->getNumber()));
934 DEBUG(dbgs() << format(" %14s ", TII->getName(MI->getOpcode())));
936 if (SwapVector[EntryIdx].IsLoad)
937 DEBUG(dbgs() << "load ");
938 if (SwapVector[EntryIdx].IsStore)
939 DEBUG(dbgs() << "store ");
940 if (SwapVector[EntryIdx].IsSwap)
941 DEBUG(dbgs() << "swap ");
942 if (SwapVector[EntryIdx].MentionsPhysVR)
943 DEBUG(dbgs() << "physreg ");
944 if (SwapVector[EntryIdx].MentionsPartialVR)
945 DEBUG(dbgs() << "partialreg ");
947 if (SwapVector[EntryIdx].IsSwappable) {
948 DEBUG(dbgs() << "swappable ");
949 switch(SwapVector[EntryIdx].SpecialHandling) {
951 DEBUG(dbgs() << "special:**unknown**");
956 DEBUG(dbgs() << "special:extract ");
959 DEBUG(dbgs() << "special:insert ");
962 DEBUG(dbgs() << "special:load ");
965 DEBUG(dbgs() << "special:store ");
968 DEBUG(dbgs() << "special:splat ");
971 DEBUG(dbgs() << "special:xxpermdi ");
974 DEBUG(dbgs() << "special:copywiden ");
979 if (SwapVector[EntryIdx].WebRejected)
980 DEBUG(dbgs() << "rejected ");
981 if (SwapVector[EntryIdx].WillRemove)
982 DEBUG(dbgs() << "remove ");
984 DEBUG(dbgs() << "\n");
986 // For no-asserts builds.
991 DEBUG(dbgs() << "\n");
994 } // end default namespace
996 INITIALIZE_PASS_BEGIN(PPCVSXSwapRemoval, DEBUG_TYPE,
997 "PowerPC VSX Swap Removal", false, false)
998 INITIALIZE_PASS_END(PPCVSXSwapRemoval, DEBUG_TYPE,
999 "PowerPC VSX Swap Removal", false, false)
1001 char PPCVSXSwapRemoval::ID = 0;
1003 llvm::createPPCVSXSwapRemovalPass() { return new PPCVSXSwapRemoval(); }