LLVM 24.0.0git
PPCVSXSwapRemoval.cpp
Go to the documentation of this file.
1//===----------- PPCVSXSwapRemoval.cpp - Remove VSX LE Swaps -------------===//
2//
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
6//
7//===---------------------------------------------------------------------===//
8//
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.
12//
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.
18//
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.
22//
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.
31//
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
35// instructions.
36//
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.
41//
42//===---------------------------------------------------------------------===//
43
44#include "PPC.h"
45#include "PPCInstrInfo.h"
46#include "PPCTargetMachine.h"
47#include "llvm/ADT/DenseMap.h"
52#include "llvm/Config/llvm-config.h"
53#include "llvm/Support/Debug.h"
54#include "llvm/Support/Format.h"
56
57using namespace llvm;
58
59#define DEBUG_TYPE "ppc-vsx-swaps"
60
61namespace {
62
63// A PPCVSXSwapEntry is created for each machine instruction that
64// is relevant to a vector computation.
65struct PPCVSXSwapEntry {
66 // Pointer to the instruction.
67 MachineInstr *VSEMI;
68
69 // Unique ID (position in the swap vector).
70 int VSEId;
71
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;
82 unsigned int HasUnanalyzableDef : 1;
83};
84
85enum SHValues {
86 SH_NONE = 0,
87 SH_EXTRACT,
88 SH_INSERT,
89 SH_NOSWAP_LD,
90 SH_NOSWAP_ST,
91 SH_SPLAT,
92 SH_XXPERMDI,
93 SH_COPYWIDEN
94};
95
96struct PPCVSXSwapRemoval : public MachineFunctionPass {
97
98 static char ID;
99 const PPCInstrInfo *TII;
100 MachineFunction *MF;
102
103 // Swap entries are allocated in a vector for better performance.
104 std::vector<PPCVSXSwapEntry> SwapVector;
105
106 // A mapping is maintained between machine instructions and
107 // their swap entries. The key is the address of the MI.
109
110 // Equivalence classes are used to gather webs of related computation.
111 // Swap entries are represented by their VSEId fields.
113
114 PPCVSXSwapRemoval() : MachineFunctionPass(ID) {}
115
116private:
117 // Initialize data structures.
118 void initialize(MachineFunction &MFParm);
119
120 // Walk the machine instructions to gather vector usage information.
121 // Return true iff vector mentions are present.
122 bool gatherVectorInstructions();
123
124 // Add an entry to the swap vector and swap map.
125 int addSwapEntry(MachineInstr *MI, PPCVSXSwapEntry &SwapEntry);
126
127 // Hunt backwards through COPY and SUBREG_TO_REG chains for a
128 // source register. VecIdx indicates the swap vector entry to
129 // mark as mentioning a physical register if the search leads
130 // to one.
131 unsigned lookThruCopyLike(unsigned SrcReg, unsigned VecIdx);
132
133 // Generate equivalence classes for related computations (webs).
134 void formWebs();
135
136 // Analyze webs and determine those that cannot be optimized.
137 void recordUnoptimizableWebs();
138
139 // Record which swap instructions can be safely removed.
140 void markSwapsForRemoval();
141
142 // Remove swaps and update other instructions requiring special
143 // handling. Return true iff any changes are made.
144 bool removeSwaps();
145
146 // Insert a swap instruction from SrcReg to DstReg at the given
147 // InsertPoint.
149 unsigned DstReg, unsigned SrcReg);
150
151 // Update instructions requiring special handling.
152 void handleSpecialSwappables(int EntryIdx);
153
154 // Dump a description of the entries in the swap vector.
155 void dumpSwapVector();
156
157 // Return true iff the given register is in the given class.
158 bool isRegInClass(unsigned Reg, const TargetRegisterClass *RC) {
160 return RC->hasSubClassEq(MRI->getRegClass(Reg));
161 return RC->contains(Reg);
162 }
163
164 // Return true iff the given register is a full vector register.
165 bool isVecReg(unsigned Reg) {
166 return (isRegInClass(Reg, &PPC::VSRCRegClass) ||
167 isRegInClass(Reg, &PPC::VRRCRegClass));
168 }
169
170 // Return true iff the given register is a partial vector register.
171 bool isScalarVecReg(unsigned Reg) {
172 return (isRegInClass(Reg, &PPC::VSFRCRegClass) ||
173 isRegInClass(Reg, &PPC::VSSRCRegClass));
174 }
175
176 // Return true iff the given register mentions all or part of a
177 // vector register. Also sets Partial to true if the mention
178 // is for just the floating-point register overlap of the register.
179 bool isAnyVecReg(unsigned Reg, bool &Partial) {
180 if (isScalarVecReg(Reg))
181 Partial = true;
182 return isScalarVecReg(Reg) || isVecReg(Reg);
183 }
184
185public:
186 // Main entry point for this pass.
187 bool runOnMachineFunction(MachineFunction &MF) override {
188 if (skipFunction(MF.getFunction()))
189 return false;
190
191 // If we don't have VSX on the subtarget, don't do anything.
192 // Also, on Power 9 the load and store ops preserve element order and so
193 // the swaps are not required.
194 const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>();
195 if (!STI.hasVSX() || !STI.needsSwapsForVSXMemOps())
196 return false;
197
198 bool Changed = false;
199 initialize(MF);
200
201 if (gatherVectorInstructions()) {
202 formWebs();
203 recordUnoptimizableWebs();
204 markSwapsForRemoval();
205 Changed = removeSwaps();
206 }
207
208 // FIXME: See the allocation of EC in initialize().
209 delete EC;
210 return Changed;
211 }
212};
213} // end anonymous namespace
214
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.
218void PPCVSXSwapRemoval::initialize(MachineFunction &MFParm) {
219 MF = &MFParm;
220 MRI = &MF->getRegInfo();
221 TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo();
222
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);
228 SwapVector.clear();
229 SwapVector.reserve(InitialVectorSize);
230
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>;
235}
236
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.
240bool PPCVSXSwapRemoval::gatherVectorInstructions() {
241 bool RelevantFunction = false;
242
243 for (MachineBasicBlock &MBB : *MF) {
244 for (MachineInstr &MI : MBB) {
245
246 if (MI.isDebugInstr())
247 continue;
248
249 bool RelevantInstr = false;
250 bool Partial = false;
251
252 for (const MachineOperand &MO : MI.operands()) {
253 if (!MO.isReg())
254 continue;
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
258 // XXPERMDIs).
259 if (isAnyVecReg(Reg, Partial))
260 RelevantInstr = true;
261 }
262
263 if (!RelevantInstr)
264 continue;
265
266 RelevantFunction = true;
267
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);
273
274 switch(MI.getOpcode()) {
275 default:
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.
282 if (Partial)
283 SwapVector[VecIdx].MentionsPartialVR = 1;
284 else
285 SwapVector[VecIdx].IsSwappable = 1;
286 break;
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();
296 if (immed == 2) {
297 unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(),
298 VecIdx);
299 unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(),
300 VecIdx);
301 if (trueReg1 == trueReg2)
302 SwapVector[VecIdx].IsSwap = 1;
303 else {
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;
308 }
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) {
318
319 SwapVector[VecIdx].IsSwappable = 1;
320 SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
321
322 unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(),
323 VecIdx);
324 unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(),
325 VecIdx);
326 if (trueReg1 == trueReg2)
327 SwapVector[VecIdx].MentionsPhysVR = 0;
328
329 } else {
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;
333 }
334 break;
335 }
336 case PPC::LVX:
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
340 // for now.
341 SwapVector[VecIdx].IsLoad = 1;
342 break;
343 case PPC::LXVD2X:
344 case PPC::LXVW4X:
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;
349 break;
350 case PPC::LXSDX:
351 case PPC::LXSSPX:
352 case PPC::XFLOADf64:
353 case PPC::XFLOADf32:
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;
360 break;
361 case PPC::STVX:
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
365 // for now.
366 SwapVector[VecIdx].IsStore = 1;
367 break;
368 case PPC::STXVD2X:
369 case PPC::STXVW4X:
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;
374 break;
375 case PPC::COPY:
376 // These are fine provided they are moving between full vector
377 // register classes.
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;
388 break;
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(1).getReg()))
399 SwapVector[VecIdx].IsSwappable = 1;
400 else if (isVecReg(MI.getOperand(0).getReg()) &&
401 isScalarVecReg(MI.getOperand(1).getReg())) {
402 SwapVector[VecIdx].IsSwappable = 1;
403 SwapVector[VecIdx].SpecialHandling = SHValues::SH_COPYWIDEN;
404 }
405 break;
406 }
407 case PPC::VSPLTB:
408 case PPC::VSPLTH:
409 case PPC::VSPLTW:
410 case PPC::XXSPLTW:
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;
415 break;
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.
424 case PPC::INLINEASM:
425 case PPC::INLINEASM_BR:
426 case PPC::EXTRACT_SUBREG:
427 case PPC::INSERT_SUBREG:
428 case PPC::COPY_TO_REGCLASS:
429 case PPC::LVEBX:
430 case PPC::LVEHX:
431 case PPC::LVEWX:
432 case PPC::LVSL:
433 case PPC::LVSR:
434 case PPC::LVXL:
435 case PPC::STVEBX:
436 case PPC::STVEHX:
437 case PPC::STVEWX:
438 case PPC::STVXL:
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.
445 case PPC::STXSDX:
446 case PPC::STXSSPX:
447 case PPC::VCIPHER:
448 case PPC::VCIPHERLAST:
449 case PPC::VMRGHB:
450 case PPC::VMRGHH:
451 case PPC::VMRGHW:
452 case PPC::VMRGLB:
453 case PPC::VMRGLH:
454 case PPC::VMRGLW:
455 case PPC::VMULESB:
456 case PPC::VMULESH:
457 case PPC::VMULESW:
458 case PPC::VMULEUB:
459 case PPC::VMULEUH:
460 case PPC::VMULEUW:
461 case PPC::VMULOSB:
462 case PPC::VMULOSH:
463 case PPC::VMULOSW:
464 case PPC::VMULOUB:
465 case PPC::VMULOUH:
466 case PPC::VMULOUW:
467 case PPC::VNCIPHER:
468 case PPC::VNCIPHERLAST:
469 case PPC::VPERM:
470 case PPC::VPERMXOR:
471 case PPC::VPKPX:
472 case PPC::VPKSHSS:
473 case PPC::VPKSHUS:
474 case PPC::VPKSDSS:
475 case PPC::VPKSDUS:
476 case PPC::VPKSWSS:
477 case PPC::VPKSWUS:
478 case PPC::VPKUDUM:
479 case PPC::VPKUDUS:
480 case PPC::VPKUHUM:
481 case PPC::VPKUHUS:
482 case PPC::VPKUWUM:
483 case PPC::VPKUWUS:
484 case PPC::VPMSUMB:
485 case PPC::VPMSUMD:
486 case PPC::VPMSUMH:
487 case PPC::VPMSUMW:
488 case PPC::VRLB:
489 case PPC::VRLD:
490 case PPC::VRLH:
491 case PPC::VRLW:
492 case PPC::VSBOX:
493 case PPC::VSHASIGMAD:
494 case PPC::VSHASIGMAW:
495 case PPC::VSL:
496 case PPC::VSLDOI:
497 case PPC::VSLO:
498 case PPC::VSR:
499 case PPC::VSRO:
500 case PPC::VSUM2SWS:
501 case PPC::VSUM4SBS:
502 case PPC::VSUM4SHS:
503 case PPC::VSUM4UBS:
504 case PPC::VSUMSWS:
505 case PPC::VUPKHPX:
506 case PPC::VUPKHSB:
507 case PPC::VUPKHSH:
508 case PPC::VUPKHSW:
509 case PPC::VUPKLPX:
510 case PPC::VUPKLSB:
511 case PPC::VUPKLSH:
512 case PPC::VUPKLSW:
513 case PPC::XXMRGHW:
514 case PPC::XXMRGLW:
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.
518 case PPC::XXSLDWI:
519 case PPC::XSCVDPSPN:
520 case PPC::XSCVSPDPN:
521 case PPC::MTVSCR:
522 case PPC::MFVSCR:
523 break;
524 }
525 }
526 }
527
528 if (RelevantFunction) {
529 LLVM_DEBUG(dbgs() << "Swap vector when first built\n\n");
530 LLVM_DEBUG(dumpSwapVector());
531 }
532
533 return RelevantFunction;
534}
535
536// Add an entry to the swap vector and swap map, and make a
537// singleton equivalence class for the entry.
538int 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;
546}
547
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.
557unsigned PPCVSXSwapRemoval::lookThruCopyLike(unsigned SrcReg,
558 unsigned VecIdx) {
559 MachineInstr *MI = MRI->getVRegDef(SrcReg);
560 if (!MI->isCopyLike())
561 return SrcReg;
562
563 assert((MI->isCopy() || MI->isSubregToReg()) &&
564 "bad opcode for lookThruCopyLike");
565 unsigned CopySrcReg = MI->getOperand(1).getReg();
566
567 if (!Register::isVirtualRegister(CopySrcReg)) {
568 if (!isScalarVecReg(CopySrcReg))
569 SwapVector[VecIdx].MentionsPhysVR = 1;
570 return CopySrcReg;
571 }
572
573 return lookThruCopyLike(CopySrcReg, VecIdx);
574}
575
576// Generate equivalence classes for related computations (webs) by
577// def-use relationships of virtual registers. Mention of a physical
578// register terminates the generation of equivalence classes as this
579// indicates a use of a parameter, definition of a return value, use
580// of a value returned from a call, or definition of a parameter to a
581// call. Computations with physical register mentions are flagged
582// as such so their containing webs will not be optimized.
583void PPCVSXSwapRemoval::formWebs() {
584
585 LLVM_DEBUG(dbgs() << "\n*** Forming webs for swap removal ***\n\n");
586
587 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
588
589 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
590
591 LLVM_DEBUG(dbgs() << "\n" << SwapVector[EntryIdx].VSEId << " ");
592 LLVM_DEBUG(MI->dump());
593
594 // It's sufficient to walk vector uses and join them to their unique
595 // definitions. In addition, check full vector register operands
596 // for physical regs. We exclude partial-vector register operands
597 // because we can handle them if copied to a full vector.
598 for (const MachineOperand &MO : MI->operands()) {
599 if (!MO.isReg())
600 continue;
601
602 Register Reg = MO.getReg();
603 if (!isVecReg(Reg) && !isScalarVecReg(Reg))
604 continue;
605
606 if (!Reg.isVirtual()) {
607 if (!(MI->isCopy() && isScalarVecReg(Reg)))
608 SwapVector[EntryIdx].MentionsPhysVR = 1;
609 continue;
610 }
611
612 if (!MO.isUse())
613 continue;
614
615 MachineInstr *DefMI = MRI->getVRegDef(Reg);
616 if (!DefMI) {
617 SwapVector[EntryIdx].HasUnanalyzableDef = 1;
618 continue;
619 }
620
621 assert(SwapMap.contains(DefMI) &&
622 "Inconsistency: def of vector reg not found in swap map!");
623 int DefIdx = SwapMap[DefMI];
624 (void)EC->unionSets(SwapVector[DefIdx].VSEId,
625 SwapVector[EntryIdx].VSEId);
626
627 LLVM_DEBUG(dbgs() << format("Unioning %d with %d\n",
628 SwapVector[DefIdx].VSEId,
629 SwapVector[EntryIdx].VSEId));
630 LLVM_DEBUG(dbgs() << " Def: ");
632 }
633 }
634}
635
636// Walk the swap vector entries looking for conditions that prevent their
637// containing computations from being optimized. When such conditions are
638// found, mark the representative of the computation's equivalence class
639// as rejected.
640void PPCVSXSwapRemoval::recordUnoptimizableWebs() {
641
642 LLVM_DEBUG(dbgs() << "\n*** Rejecting webs for swap removal ***\n\n");
643
644 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
645 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
646
647 // If representative is already rejected, don't waste further time.
648 if (SwapVector[Repr].WebRejected)
649 continue;
650
651 // Reject webs containing mentions of physical or partial registers, or
652 // containing operations that we don't know how to handle in a lane-
653 // permuted region.
654 if (SwapVector[EntryIdx].MentionsPhysVR ||
655 SwapVector[EntryIdx].MentionsPartialVR ||
656 SwapVector[EntryIdx].HasUnanalyzableDef ||
657 !(SwapVector[EntryIdx].IsSwappable || SwapVector[EntryIdx].IsSwap)) {
658
659 SwapVector[Repr].WebRejected = 1;
660
661 LLVM_DEBUG(dbgs() << format("Web %d rejected for physreg, partial reg, "
662 "unanalyzable def, or not swap[pable]\n",
663 Repr));
664 LLVM_DEBUG(dbgs() << " in " << EntryIdx << ": ");
665 LLVM_DEBUG(SwapVector[EntryIdx].VSEMI->dump());
666 LLVM_DEBUG(dbgs() << "\n");
667 }
668
669 // Reject webs than contain swapping loads that feed something other
670 // than a swap instruction.
671 else if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
672 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
673 Register DefReg = MI->getOperand(0).getReg();
674
675 // We skip debug instructions in the analysis. (Note that debug
676 // location information is still maintained by this optimization
677 // because it remains on the LXVD2X and STXVD2X instructions after
678 // the XXPERMDIs are removed.)
679 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
680 int UseIdx = SwapMap[&UseMI];
681
682 if (!SwapVector[UseIdx].IsSwap || SwapVector[UseIdx].IsLoad ||
683 SwapVector[UseIdx].IsStore) {
684
685 SwapVector[Repr].WebRejected = 1;
686
688 "Web %d rejected for load not feeding swap\n", Repr));
689 LLVM_DEBUG(dbgs() << " def " << EntryIdx << ": ");
690 LLVM_DEBUG(MI->dump());
691 LLVM_DEBUG(dbgs() << " use " << UseIdx << ": ");
692 LLVM_DEBUG(UseMI.dump());
693 LLVM_DEBUG(dbgs() << "\n");
694 }
695
696 // It is possible that the load feeds a swap and that swap feeds a
697 // store. In such a case, the code is actually trying to store a swapped
698 // vector. We must reject such webs.
699 if (SwapVector[UseIdx].IsSwap && !SwapVector[UseIdx].IsLoad &&
700 !SwapVector[UseIdx].IsStore) {
701 Register SwapDefReg = UseMI.getOperand(0).getReg();
702 for (MachineInstr &UseOfUseMI :
703 MRI->use_nodbg_instructions(SwapDefReg)) {
704 int UseOfUseIdx = SwapMap[&UseOfUseMI];
705 if (SwapVector[UseOfUseIdx].IsStore) {
706 SwapVector[Repr].WebRejected = 1;
708 dbgs() << format(
709 "Web %d rejected for load/swap feeding a store\n", Repr));
710 LLVM_DEBUG(dbgs() << " def " << EntryIdx << ": ");
711 LLVM_DEBUG(MI->dump());
712 LLVM_DEBUG(dbgs() << " use " << UseIdx << ": ");
713 LLVM_DEBUG(UseMI.dump());
714 LLVM_DEBUG(dbgs() << "\n");
715 }
716 }
717 }
718 }
719
720 // Reject webs that contain swapping stores that are fed by something
721 // other than a swap instruction.
722 } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
723 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
724 Register UseReg = MI->getOperand(0).getReg();
725 MachineInstr *DefMI = MRI->getVRegDef(UseReg);
726 Register DefReg = DefMI->getOperand(0).getReg();
727 int DefIdx = SwapMap[DefMI];
728
729 if (!SwapVector[DefIdx].IsSwap || SwapVector[DefIdx].IsLoad ||
730 SwapVector[DefIdx].IsStore) {
731
732 SwapVector[Repr].WebRejected = 1;
733
735 "Web %d rejected for store not fed by swap\n", Repr));
736 LLVM_DEBUG(dbgs() << " def " << DefIdx << ": ");
738 LLVM_DEBUG(dbgs() << " use " << EntryIdx << ": ");
739 LLVM_DEBUG(MI->dump());
740 LLVM_DEBUG(dbgs() << "\n");
741 }
742
743 // Ensure all uses of the register defined by DefMI feed store
744 // instructions
745 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
746 int UseIdx = SwapMap[&UseMI];
747
748 if (SwapVector[UseIdx].VSEMI->getOpcode() != MI->getOpcode()) {
749 SwapVector[Repr].WebRejected = 1;
750
752 dbgs() << format(
753 "Web %d rejected for swap not feeding only stores\n", Repr));
754 LLVM_DEBUG(dbgs() << " def "
755 << " : ");
757 LLVM_DEBUG(dbgs() << " use " << UseIdx << ": ");
758 LLVM_DEBUG(SwapVector[UseIdx].VSEMI->dump());
759 LLVM_DEBUG(dbgs() << "\n");
760 }
761 }
762 }
763 }
764
765 LLVM_DEBUG(dbgs() << "Swap vector after web analysis:\n\n");
766 LLVM_DEBUG(dumpSwapVector());
767}
768
769// Walk the swap vector entries looking for swaps fed by permuting loads
770// and swaps that feed permuting stores. If the containing computation
771// has not been marked rejected, mark each such swap for removal.
772// (Removal is delayed in case optimization has disturbed the pattern,
773// such that multiple loads feed the same swap, etc.)
774void PPCVSXSwapRemoval::markSwapsForRemoval() {
775
776 LLVM_DEBUG(dbgs() << "\n*** Marking swaps for removal ***\n\n");
777
778 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
779
780 if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
781 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
782
783 if (!SwapVector[Repr].WebRejected) {
784 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
785 Register DefReg = MI->getOperand(0).getReg();
786
787 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
788 int UseIdx = SwapMap[&UseMI];
789 SwapVector[UseIdx].WillRemove = 1;
790
791 LLVM_DEBUG(dbgs() << "Marking swap fed by load for removal: ");
792 LLVM_DEBUG(UseMI.dump());
793 }
794 }
795
796 } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
797 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
798
799 if (!SwapVector[Repr].WebRejected) {
800 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
801 Register UseReg = MI->getOperand(0).getReg();
802 MachineInstr *DefMI = MRI->getVRegDef(UseReg);
803 int DefIdx = SwapMap[DefMI];
804 SwapVector[DefIdx].WillRemove = 1;
805
806 LLVM_DEBUG(dbgs() << "Marking swap feeding store for removal: ");
808 }
809
810 } else if (SwapVector[EntryIdx].IsSwappable &&
811 SwapVector[EntryIdx].SpecialHandling != 0) {
812 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
813
814 if (!SwapVector[Repr].WebRejected)
815 handleSpecialSwappables(EntryIdx);
816 }
817 }
818}
819
820// Create an xxswapd instruction and insert it prior to the given point.
821// MI is used to determine basic block and debug loc information.
822// FIXME: When inserting a swap, we should check whether SrcReg is
823// defined by another swap: SrcReg = XXPERMDI Reg, Reg, 2; If so,
824// then instead we should generate a copy from Reg to DstReg.
825void PPCVSXSwapRemoval::insertSwap(MachineInstr *MI,
826 MachineBasicBlock::iterator InsertPoint,
827 unsigned DstReg, unsigned SrcReg) {
828 BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
829 TII->get(PPC::XXPERMDI), DstReg)
830 .addReg(SrcReg)
831 .addReg(SrcReg)
832 .addImm(2);
833}
834
835// The identified swap entry requires special handling to allow its
836// containing computation to be optimized. Perform that handling
837// here.
838// FIXME: Additional opportunities will be phased in with subsequent
839// patches.
840void PPCVSXSwapRemoval::handleSpecialSwappables(int EntryIdx) {
841 switch (SwapVector[EntryIdx].SpecialHandling) {
842
843 default:
844 llvm_unreachable("Unexpected special handling type");
845
846 // For splats based on an index into a vector, add N/2 modulo N
847 // to the index, where N is the number of vector elements.
848 case SHValues::SH_SPLAT: {
849 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
850 unsigned NElts;
851
852 LLVM_DEBUG(dbgs() << "Changing splat: ");
853 LLVM_DEBUG(MI->dump());
854
855 switch (MI->getOpcode()) {
856 default:
857 llvm_unreachable("Unexpected splat opcode");
858 case PPC::VSPLTB: NElts = 16; break;
859 case PPC::VSPLTH: NElts = 8; break;
860 case PPC::VSPLTW:
861 case PPC::XXSPLTW: NElts = 4; break;
862 }
863
864 unsigned EltNo;
865 if (MI->getOpcode() == PPC::XXSPLTW)
866 EltNo = MI->getOperand(2).getImm();
867 else
868 EltNo = MI->getOperand(1).getImm();
869
870 EltNo = (EltNo + NElts / 2) % NElts;
871 if (MI->getOpcode() == PPC::XXSPLTW)
872 MI->getOperand(2).setImm(EltNo);
873 else
874 MI->getOperand(1).setImm(EltNo);
875
876 LLVM_DEBUG(dbgs() << " Into: ");
877 LLVM_DEBUG(MI->dump());
878 break;
879 }
880
881 // For an XXPERMDI that isn't handled otherwise, we need to
882 // reverse the order of the operands. If the selector operand
883 // has a value of 0 or 3, we need to change it to 3 or 0,
884 // respectively. Otherwise we should leave it alone. (This
885 // is equivalent to reversing the two bits of the selector
886 // operand and complementing the result.)
887 case SHValues::SH_XXPERMDI: {
888 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
889
890 LLVM_DEBUG(dbgs() << "Changing XXPERMDI: ");
891 LLVM_DEBUG(MI->dump());
892
893 unsigned Selector = MI->getOperand(3).getImm();
894 if (Selector == 0 || Selector == 3)
895 Selector = 3 - Selector;
896 MI->getOperand(3).setImm(Selector);
897
898 Register Reg1 = MI->getOperand(1).getReg();
899 Register Reg2 = MI->getOperand(2).getReg();
900 MI->getOperand(1).setReg(Reg2);
901 MI->getOperand(2).setReg(Reg1);
902
903 // We also need to swap kill flag associated with the register.
904 bool IsKill1 = MI->getOperand(1).isKill();
905 bool IsKill2 = MI->getOperand(2).isKill();
906 MI->getOperand(1).setIsKill(IsKill2);
907 MI->getOperand(2).setIsKill(IsKill1);
908
909 LLVM_DEBUG(dbgs() << " Into: ");
910 LLVM_DEBUG(MI->dump());
911 break;
912 }
913
914 // For a copy from a scalar floating-point register to a vector
915 // register, removing swaps will leave the copied value in the
916 // wrong lane. Insert a swap following the copy to fix this.
917 case SHValues::SH_COPYWIDEN: {
918 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
919
920 LLVM_DEBUG(dbgs() << "Changing SUBREG_TO_REG: ");
921 LLVM_DEBUG(MI->dump());
922
923 Register DstReg = MI->getOperand(0).getReg();
924 const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
925 Register NewVReg = MRI->createVirtualRegister(DstRC);
926
927 MI->getOperand(0).setReg(NewVReg);
928 LLVM_DEBUG(dbgs() << " Into: ");
929 LLVM_DEBUG(MI->dump());
930
931 auto InsertPoint = ++MachineBasicBlock::iterator(MI);
932
933 // Note that an XXPERMDI requires a VSRC, so if the SUBREG_TO_REG
934 // is copying to a VRRC, we need to be careful to avoid a register
935 // assignment problem. In this case we must copy from VRRC to VSRC
936 // prior to the swap, and from VSRC to VRRC following the swap.
937 // Coalescing will usually remove all this mess.
938 if (DstRC == &PPC::VRRCRegClass) {
939 Register VSRCTmp1 = MRI->createVirtualRegister(&PPC::VSRCRegClass);
940 Register VSRCTmp2 = MRI->createVirtualRegister(&PPC::VSRCRegClass);
941
942 BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
943 TII->get(PPC::COPY), VSRCTmp1)
944 .addReg(NewVReg);
945 LLVM_DEBUG(std::prev(InsertPoint)->dump());
946
947 insertSwap(MI, InsertPoint, VSRCTmp2, VSRCTmp1);
948 LLVM_DEBUG(std::prev(InsertPoint)->dump());
949
950 BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
951 TII->get(PPC::COPY), DstReg)
952 .addReg(VSRCTmp2);
953 LLVM_DEBUG(std::prev(InsertPoint)->dump());
954
955 } else {
956 insertSwap(MI, InsertPoint, DstReg, NewVReg);
957 LLVM_DEBUG(std::prev(InsertPoint)->dump());
958 }
959 break;
960 }
961 }
962}
963
964// Walk the swap vector and replace each entry marked for removal with
965// a copy operation.
966bool PPCVSXSwapRemoval::removeSwaps() {
967
968 LLVM_DEBUG(dbgs() << "\n*** Removing swaps ***\n\n");
969
970 bool Changed = false;
971
972 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
973 if (SwapVector[EntryIdx].WillRemove) {
974 Changed = true;
975 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
976 MachineBasicBlock *MBB = MI->getParent();
977 BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(TargetOpcode::COPY),
978 MI->getOperand(0).getReg())
979 .add(MI->getOperand(1));
980
981 LLVM_DEBUG(dbgs() << format("Replaced %d with copy: ",
982 SwapVector[EntryIdx].VSEId));
983 LLVM_DEBUG(MI->dump());
984
985 MI->eraseFromParent();
986 }
987 }
988
989 return Changed;
990}
991
992#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
993// For debug purposes, dump the contents of the swap vector.
994LLVM_DUMP_METHOD void PPCVSXSwapRemoval::dumpSwapVector() {
995
996 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
997
998 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
999 int ID = SwapVector[EntryIdx].VSEId;
1000
1001 dbgs() << format("%6d", ID);
1002 dbgs() << format("%6d", EC->getLeaderValue(ID));
1003 dbgs() << format(" %bb.%3d", MI->getParent()->getNumber());
1004 dbgs() << format(" %14s ", TII->getName(MI->getOpcode()).str().c_str());
1005
1006 if (SwapVector[EntryIdx].IsLoad)
1007 dbgs() << "load ";
1008 if (SwapVector[EntryIdx].IsStore)
1009 dbgs() << "store ";
1010 if (SwapVector[EntryIdx].IsSwap)
1011 dbgs() << "swap ";
1012 if (SwapVector[EntryIdx].MentionsPhysVR)
1013 dbgs() << "physreg ";
1014 if (SwapVector[EntryIdx].MentionsPartialVR)
1015 dbgs() << "partialreg ";
1016 if (SwapVector[EntryIdx].HasUnanalyzableDef)
1017 dbgs() << "unanalyzabledef ";
1018
1019 if (SwapVector[EntryIdx].IsSwappable) {
1020 dbgs() << "swappable ";
1021 switch(SwapVector[EntryIdx].SpecialHandling) {
1022 default:
1023 dbgs() << "special:**unknown**";
1024 break;
1025 case SH_NONE:
1026 break;
1027 case SH_EXTRACT:
1028 dbgs() << "special:extract ";
1029 break;
1030 case SH_INSERT:
1031 dbgs() << "special:insert ";
1032 break;
1033 case SH_NOSWAP_LD:
1034 dbgs() << "special:load ";
1035 break;
1036 case SH_NOSWAP_ST:
1037 dbgs() << "special:store ";
1038 break;
1039 case SH_SPLAT:
1040 dbgs() << "special:splat ";
1041 break;
1042 case SH_XXPERMDI:
1043 dbgs() << "special:xxpermdi ";
1044 break;
1045 case SH_COPYWIDEN:
1046 dbgs() << "special:copywiden ";
1047 break;
1048 }
1049 }
1050
1051 if (SwapVector[EntryIdx].WebRejected)
1052 dbgs() << "rejected ";
1053 if (SwapVector[EntryIdx].WillRemove)
1054 dbgs() << "remove ";
1055
1056 dbgs() << "\n";
1057
1058 // For no-asserts builds.
1059 (void)MI;
1060 (void)ID;
1061 }
1062
1063 dbgs() << "\n";
1064}
1065#endif
1066
1068 "PowerPC VSX Swap Removal", false, false)
1070 "PowerPC VSX Swap Removal", false, false)
1071
1072char PPCVSXSwapRemoval::ID = 0;
1074llvm::createPPCVSXSwapRemovalPass() { return new PPCVSXSwapRemoval(); }
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static bool isRegInClass(const MachineOperand &MO, const TargetRegisterClass *Class)
MachineBasicBlock & MBB
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:678
This file defines the DenseMap class.
Generic implementation of equivalence classes through the use Tarjan's efficient union-find algorithm...
#define DEBUG_TYPE
static Register UseReg(const MachineOperand &MO)
const HexagonInstrInfo * TII
static bool isVecReg(unsigned Reg)
IRTranslator LLVM IR MI
Register Reg
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
#define LLVM_DEBUG(...)
Definition Debug.h:119
static void initialize(TargetLibraryInfoImpl &TLI, const Triple &T, const llvm::StringTable &StandardNames, VectorLibrary VecLib)
Initialize the set of available library functions based on the specified target triple.
This represents a collection of equivalence classes and supports three efficient operations: insert a...
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
bool hasSubClassEq(const MCRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Register getReg(unsigned Idx) const
Get the register for the operand index.
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
Representation of each machine instruction.
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
Register getReg() const
getReg - Returns the register number.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI LLVM_READONLY MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
bool needsSwapsForVSXMemOps() const
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
static constexpr bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:66
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
FunctionPass * createPPCVSXSwapRemovalPass()
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58