blob: cbd426d516efb12aca469514d46bb1d0b1d71362 [file] [log] [blame]
Bill Schmidtfe723b92015-04-27 19:57:34 +00001//===----------- PPCVSXSwapRemoval.cpp - Remove VSX LE Swaps -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===---------------------------------------------------------------------===//
9//
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.
13//
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.
19//
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.
23//
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.
32//
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
36// instructions.
37//
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.
42//
43//===---------------------------------------------------------------------===//
44
45#include "PPCInstrInfo.h"
46#include "PPC.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"
57
58using namespace llvm;
59
60#define DEBUG_TYPE "ppc-vsx-swaps"
61
62namespace llvm {
63 void initializePPCVSXSwapRemovalPass(PassRegistry&);
64}
65
66namespace {
67
68// A PPCVSXSwapEntry is created for each machine instruction that
69// is relevant to a vector computation.
70struct PPCVSXSwapEntry {
71 // Pointer to the instruction.
72 MachineInstr *VSEMI;
73
74 // Unique ID (position in the swap vector).
75 int VSEId;
76
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 HasImplicitSubreg : 1;
83 unsigned int IsSwappable : 1;
84 unsigned int SpecialHandling : 3;
85 unsigned int WebRejected : 1;
86 unsigned int WillRemove : 1;
87};
88
89enum SHValues {
90 SH_NONE = 0,
Bill Schmidtfe723b92015-04-27 19:57:34 +000091 SH_EXTRACT,
92 SH_INSERT,
93 SH_NOSWAP_LD,
94 SH_NOSWAP_ST,
95 SH_SPLAT
96};
97
98struct PPCVSXSwapRemoval : public MachineFunctionPass {
99
100 static char ID;
101 const PPCInstrInfo *TII;
102 MachineFunction *MF;
103 MachineRegisterInfo *MRI;
104
105 // Swap entries are allocated in a vector for better performance.
106 std::vector<PPCVSXSwapEntry> SwapVector;
107
108 // A mapping is maintained between machine instructions and
109 // their swap entries. The key is the address of the MI.
110 DenseMap<MachineInstr*, int> SwapMap;
111
112 // Equivalence classes are used to gather webs of related computation.
113 // Swap entries are represented by their VSEId fields.
114 EquivalenceClasses<int> *EC;
115
116 PPCVSXSwapRemoval() : MachineFunctionPass(ID) {
117 initializePPCVSXSwapRemovalPass(*PassRegistry::getPassRegistry());
118 }
119
120private:
121 // Initialize data structures.
122 void initialize(MachineFunction &MFParm);
123
124 // Walk the machine instructions to gather vector usage information.
125 // Return true iff vector mentions are present.
126 bool gatherVectorInstructions();
127
128 // Add an entry to the swap vector and swap map.
129 int addSwapEntry(MachineInstr *MI, PPCVSXSwapEntry &SwapEntry);
130
131 // Hunt backwards through COPY and SUBREG_TO_REG chains for a
132 // source register. VecIdx indicates the swap vector entry to
133 // mark as mentioning a physical register if the search leads
134 // to one.
135 unsigned lookThruCopyLike(unsigned SrcReg, unsigned VecIdx);
136
137 // Generate equivalence classes for related computations (webs).
138 void formWebs();
139
140 // Analyze webs and determine those that cannot be optimized.
141 void recordUnoptimizableWebs();
142
143 // Record which swap instructions can be safely removed.
144 void markSwapsForRemoval();
145
146 // Remove swaps and update other instructions requiring special
147 // handling. Return true iff any changes are made.
148 bool removeSwaps();
149
150 // Update instructions requiring special handling.
151 void handleSpecialSwappables(int EntryIdx);
152
153 // Dump a description of the entries in the swap vector.
154 void dumpSwapVector();
155
156 // Return true iff the given register is in the given class.
157 bool isRegInClass(unsigned Reg, const TargetRegisterClass *RC) {
158 if (TargetRegisterInfo::isVirtualRegister(Reg))
159 return RC->hasSubClassEq(MRI->getRegClass(Reg));
160 if (RC->contains(Reg))
161 return true;
162 return false;
163 }
164
165 // Return true iff the given register is a full vector register.
166 bool isVecReg(unsigned Reg) {
167 return (isRegInClass(Reg, &PPC::VSRCRegClass) ||
168 isRegInClass(Reg, &PPC::VRRCRegClass));
169 }
170
171public:
172 // Main entry point for this pass.
173 bool runOnMachineFunction(MachineFunction &MF) override {
174 // If we don't have VSX on the subtarget, don't do anything.
175 const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>();
176 if (!STI.hasVSX())
177 return false;
178
179 bool Changed = false;
180 initialize(MF);
181
182 if (gatherVectorInstructions()) {
183 formWebs();
184 recordUnoptimizableWebs();
185 markSwapsForRemoval();
186 Changed = removeSwaps();
187 }
188
189 // FIXME: See the allocation of EC in initialize().
190 delete EC;
191 return Changed;
192 }
193};
194
195// Initialize data structures for this pass. In particular, clear the
196// swap vector and allocate the equivalence class mapping before
197// processing each function.
198void PPCVSXSwapRemoval::initialize(MachineFunction &MFParm) {
199 MF = &MFParm;
200 MRI = &MF->getRegInfo();
201 TII = static_cast<const PPCInstrInfo*>(MF->getSubtarget().getInstrInfo());
202
203 // An initial vector size of 256 appears to work well in practice.
204 // Small/medium functions with vector content tend not to incur a
205 // reallocation at this size. Three of the vector tests in
206 // projects/test-suite reallocate, which seems like a reasonable rate.
207 const int InitialVectorSize(256);
208 SwapVector.clear();
209 SwapVector.reserve(InitialVectorSize);
210
211 // FIXME: Currently we allocate EC each time because we don't have
212 // access to the set representation on which to call clear(). Should
213 // consider adding a clear() method to the EquivalenceClasses class.
214 EC = new EquivalenceClasses<int>;
215}
216
217// Create an entry in the swap vector for each instruction that mentions
218// a full vector register, recording various characteristics of the
219// instructions there.
220bool PPCVSXSwapRemoval::gatherVectorInstructions() {
221 bool RelevantFunction = false;
222
223 for (MachineBasicBlock &MBB : *MF) {
224 for (MachineInstr &MI : MBB) {
225
226 bool RelevantInstr = false;
227 bool ImplicitSubreg = false;
228
229 for (const MachineOperand &MO : MI.operands()) {
230 if (!MO.isReg())
231 continue;
232 unsigned Reg = MO.getReg();
233 if (isVecReg(Reg)) {
234 RelevantInstr = true;
235 if (MO.getSubReg() != 0)
236 ImplicitSubreg = true;
237 break;
238 }
239 }
240
241 if (!RelevantInstr)
242 continue;
243
244 RelevantFunction = true;
245
246 // Create a SwapEntry initialized to zeros, then fill in the
247 // instruction and ID fields before pushing it to the back
248 // of the swap vector.
249 PPCVSXSwapEntry SwapEntry{};
250 int VecIdx = addSwapEntry(&MI, SwapEntry);
251
252 if (ImplicitSubreg)
253 SwapVector[VecIdx].HasImplicitSubreg = 1;
254
255 switch(MI.getOpcode()) {
256 default:
257 // Unless noted otherwise, an instruction is considered
258 // safe for the optimization. There are a large number of
259 // such true-SIMD instructions (all vector math, logical,
260 // select, compare, etc.).
261 SwapVector[VecIdx].IsSwappable = 1;
262 break;
Bill Schmidt7c691fe2015-07-02 17:03:06 +0000263 case PPC::XXPERMDI: {
Bill Schmidtfe723b92015-04-27 19:57:34 +0000264 // This is a swap if it is of the form XXPERMDI t, s, s, 2.
265 // Unfortunately, MachineCSE ignores COPY and SUBREG_TO_REG, so we
266 // can also see XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), 2,
267 // for example. We have to look through chains of COPY and
268 // SUBREG_TO_REG to find the real source value for comparison.
269 // If the real source value is a physical register, then mark the
270 // XXPERMDI as mentioning a physical register.
Bill Schmidt7c691fe2015-07-02 17:03:06 +0000271 int immed = MI.getOperand(3).getImm();
272 if (immed == 2) {
Bill Schmidtfe723b92015-04-27 19:57:34 +0000273 unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(),
274 VecIdx);
275 unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(),
276 VecIdx);
277 if (trueReg1 == trueReg2)
278 SwapVector[VecIdx].IsSwap = 1;
279 }
Bill Schmidt7c691fe2015-07-02 17:03:06 +0000280 // This is a doubleword splat if it is of the form
281 // XXPERMDI t, s, s, 0 or XXPERMDI t, s, s, 3. As above we
282 // must look through chains of copy-likes to find the source
283 // register. We turn off the marking for mention of a physical
284 // register, because splatting it is safe; the optimization
285 // will not swap the value in the physical register.
286 else if (immed == 0 || immed == 3) {
287 unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(),
288 VecIdx);
289 unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(),
290 VecIdx);
291 if (trueReg1 == trueReg2) {
292 SwapVector[VecIdx].IsSwappable = 1;
293 SwapVector[VecIdx].MentionsPhysVR = 0;
294 }
295 }
296 // Any other form of XXPERMDI is lane-sensitive and unsafe
297 // for the optimization.
Bill Schmidtfe723b92015-04-27 19:57:34 +0000298 break;
Bill Schmidt7c691fe2015-07-02 17:03:06 +0000299 }
Bill Schmidtfe723b92015-04-27 19:57:34 +0000300 case PPC::LVX:
301 // Non-permuting loads are currently unsafe. We can use special
302 // handling for this in the future. By not marking these as
303 // IsSwap, we ensure computations containing them will be rejected
304 // for now.
305 SwapVector[VecIdx].IsLoad = 1;
306 break;
307 case PPC::LXVD2X:
308 case PPC::LXVW4X:
309 // Permuting loads are marked as both load and swap, and are
310 // safe for optimization.
311 SwapVector[VecIdx].IsLoad = 1;
312 SwapVector[VecIdx].IsSwap = 1;
313 break;
314 case PPC::STVX:
315 // Non-permuting stores are currently unsafe. We can use special
316 // handling for this in the future. By not marking these as
317 // IsSwap, we ensure computations containing them will be rejected
318 // for now.
319 SwapVector[VecIdx].IsStore = 1;
320 break;
321 case PPC::STXVD2X:
322 case PPC::STXVW4X:
323 // Permuting stores are marked as both store and swap, and are
324 // safe for optimization.
325 SwapVector[VecIdx].IsStore = 1;
326 SwapVector[VecIdx].IsSwap = 1;
327 break;
Bill Schmidtfe723b92015-04-27 19:57:34 +0000328 case PPC::COPY:
329 // These are fine provided they are moving between full vector
330 // register classes.
331 if (isVecReg(MI.getOperand(0).getReg()) &&
332 isVecReg(MI.getOperand(1).getReg()))
333 SwapVector[VecIdx].IsSwappable = 1;
334 break;
335 case PPC::VSPLTB:
336 case PPC::VSPLTH:
337 case PPC::VSPLTW:
338 // Splats are lane-sensitive, but we can use special handling
339 // to adjust the source lane for the splat. This is not yet
340 // implemented. When it is, we need to uncomment the following:
Bill Schmidt5fe2e252015-05-06 15:40:46 +0000341 SwapVector[VecIdx].IsSwappable = 1;
Bill Schmidtfe723b92015-04-27 19:57:34 +0000342 SwapVector[VecIdx].SpecialHandling = SHValues::SH_SPLAT;
343 break;
344 // The presence of the following lane-sensitive operations in a
345 // web will kill the optimization, at least for now. For these
346 // we do nothing, causing the optimization to fail.
347 // FIXME: Some of these could be permitted with special handling,
348 // and will be phased in as time permits.
349 // FIXME: There is no simple and maintainable way to express a set
350 // of opcodes having a common attribute in TableGen. Should this
351 // change, this is a prime candidate to use such a mechanism.
352 case PPC::INLINEASM:
353 case PPC::EXTRACT_SUBREG:
354 case PPC::INSERT_SUBREG:
355 case PPC::COPY_TO_REGCLASS:
356 case PPC::LVEBX:
357 case PPC::LVEHX:
358 case PPC::LVEWX:
359 case PPC::LVSL:
360 case PPC::LVSR:
361 case PPC::LVXL:
Bill Schmidtfe723b92015-04-27 19:57:34 +0000362 case PPC::STVEBX:
363 case PPC::STVEHX:
364 case PPC::STVEWX:
365 case PPC::STVXL:
366 case PPC::STXSDX:
367 case PPC::VCIPHER:
368 case PPC::VCIPHERLAST:
369 case PPC::VMRGHB:
370 case PPC::VMRGHH:
371 case PPC::VMRGHW:
372 case PPC::VMRGLB:
373 case PPC::VMRGLH:
374 case PPC::VMRGLW:
375 case PPC::VMULESB:
376 case PPC::VMULESH:
377 case PPC::VMULESW:
378 case PPC::VMULEUB:
379 case PPC::VMULEUH:
380 case PPC::VMULEUW:
381 case PPC::VMULOSB:
382 case PPC::VMULOSH:
383 case PPC::VMULOSW:
384 case PPC::VMULOUB:
385 case PPC::VMULOUH:
386 case PPC::VMULOUW:
387 case PPC::VNCIPHER:
388 case PPC::VNCIPHERLAST:
389 case PPC::VPERM:
390 case PPC::VPERMXOR:
391 case PPC::VPKPX:
392 case PPC::VPKSHSS:
393 case PPC::VPKSHUS:
Bill Schmidt5ed84cd2015-05-16 01:02:12 +0000394 case PPC::VPKSDSS:
395 case PPC::VPKSDUS:
Bill Schmidtfe723b92015-04-27 19:57:34 +0000396 case PPC::VPKSWSS:
397 case PPC::VPKSWUS:
Bill Schmidt5ed84cd2015-05-16 01:02:12 +0000398 case PPC::VPKUDUM:
399 case PPC::VPKUDUS:
Bill Schmidtfe723b92015-04-27 19:57:34 +0000400 case PPC::VPKUHUM:
401 case PPC::VPKUHUS:
402 case PPC::VPKUWUM:
403 case PPC::VPKUWUS:
404 case PPC::VPMSUMB:
405 case PPC::VPMSUMD:
406 case PPC::VPMSUMH:
407 case PPC::VPMSUMW:
408 case PPC::VRLB:
409 case PPC::VRLD:
410 case PPC::VRLH:
411 case PPC::VRLW:
412 case PPC::VSBOX:
413 case PPC::VSHASIGMAD:
414 case PPC::VSHASIGMAW:
415 case PPC::VSL:
416 case PPC::VSLDOI:
417 case PPC::VSLO:
418 case PPC::VSR:
419 case PPC::VSRO:
420 case PPC::VSUM2SWS:
421 case PPC::VSUM4SBS:
422 case PPC::VSUM4SHS:
423 case PPC::VSUM4UBS:
424 case PPC::VSUMSWS:
425 case PPC::VUPKHPX:
426 case PPC::VUPKHSB:
427 case PPC::VUPKHSH:
Bill Schmidt5ed84cd2015-05-16 01:02:12 +0000428 case PPC::VUPKHSW:
Bill Schmidtfe723b92015-04-27 19:57:34 +0000429 case PPC::VUPKLPX:
430 case PPC::VUPKLSB:
431 case PPC::VUPKLSH:
Bill Schmidt5ed84cd2015-05-16 01:02:12 +0000432 case PPC::VUPKLSW:
Bill Schmidtfe723b92015-04-27 19:57:34 +0000433 case PPC::XXMRGHW:
434 case PPC::XXMRGLW:
435 case PPC::XXSPLTW:
436 break;
437 }
438 }
439 }
440
441 if (RelevantFunction) {
442 DEBUG(dbgs() << "Swap vector when first built\n\n");
443 dumpSwapVector();
444 }
445
446 return RelevantFunction;
447}
448
449// Add an entry to the swap vector and swap map, and make a
450// singleton equivalence class for the entry.
451int PPCVSXSwapRemoval::addSwapEntry(MachineInstr *MI,
452 PPCVSXSwapEntry& SwapEntry) {
453 SwapEntry.VSEMI = MI;
454 SwapEntry.VSEId = SwapVector.size();
455 SwapVector.push_back(SwapEntry);
456 EC->insert(SwapEntry.VSEId);
457 SwapMap[MI] = SwapEntry.VSEId;
458 return SwapEntry.VSEId;
459}
460
461// This is used to find the "true" source register for an
462// XXPERMDI instruction, since MachineCSE does not handle the
463// "copy-like" operations (Copy and SubregToReg). Returns
464// the original SrcReg unless it is the target of a copy-like
465// operation, in which case we chain backwards through all
466// such operations to the ultimate source register. If a
467// physical register is encountered, we stop the search and
468// flag the swap entry indicated by VecIdx (the original
469// XXPERMDI) as mentioning a physical register. Similarly
470// for implicit subregister mentions (which should never
471// happen).
472unsigned PPCVSXSwapRemoval::lookThruCopyLike(unsigned SrcReg,
473 unsigned VecIdx) {
474 MachineInstr *MI = MRI->getVRegDef(SrcReg);
475 if (!MI->isCopyLike())
476 return SrcReg;
477
478 unsigned CopySrcReg, CopySrcSubreg;
479 if (MI->isCopy()) {
480 CopySrcReg = MI->getOperand(1).getReg();
481 CopySrcSubreg = MI->getOperand(1).getSubReg();
482 } else {
483 assert(MI->isSubregToReg() && "bad opcode for lookThruCopyLike");
484 CopySrcReg = MI->getOperand(2).getReg();
485 CopySrcSubreg = MI->getOperand(2).getSubReg();
486 }
487
488 if (!TargetRegisterInfo::isVirtualRegister(CopySrcReg)) {
489 SwapVector[VecIdx].MentionsPhysVR = 1;
490 return CopySrcReg;
491 }
492
493 if (CopySrcSubreg != 0) {
494 SwapVector[VecIdx].HasImplicitSubreg = 1;
495 return CopySrcReg;
496 }
497
498 return lookThruCopyLike(CopySrcReg, VecIdx);
499}
500
501// Generate equivalence classes for related computations (webs) by
502// def-use relationships of virtual registers. Mention of a physical
503// register terminates the generation of equivalence classes as this
504// indicates a use of a parameter, definition of a return value, use
505// of a value returned from a call, or definition of a parameter to a
506// call. Computations with physical register mentions are flagged
507// as such so their containing webs will not be optimized.
508void PPCVSXSwapRemoval::formWebs() {
509
510 DEBUG(dbgs() << "\n*** Forming webs for swap removal ***\n\n");
511
512 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
513
514 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
515
516 DEBUG(dbgs() << "\n" << SwapVector[EntryIdx].VSEId << " ");
517 DEBUG(MI->dump());
518
519 // It's sufficient to walk vector uses and join them to their unique
520 // definitions. In addition, check *all* vector register operands
521 // for physical regs.
522 for (const MachineOperand &MO : MI->operands()) {
523 if (!MO.isReg())
524 continue;
525
526 unsigned Reg = MO.getReg();
527 if (!isVecReg(Reg))
528 continue;
529
530 if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
531 SwapVector[EntryIdx].MentionsPhysVR = 1;
532 continue;
533 }
534
535 if (!MO.isUse())
536 continue;
537
538 MachineInstr* DefMI = MRI->getVRegDef(Reg);
539 assert(SwapMap.find(DefMI) != SwapMap.end() &&
540 "Inconsistency: def of vector reg not found in swap map!");
541 int DefIdx = SwapMap[DefMI];
542 (void)EC->unionSets(SwapVector[DefIdx].VSEId,
543 SwapVector[EntryIdx].VSEId);
544
545 DEBUG(dbgs() << format("Unioning %d with %d\n", SwapVector[DefIdx].VSEId,
546 SwapVector[EntryIdx].VSEId));
547 DEBUG(dbgs() << " Def: ");
548 DEBUG(DefMI->dump());
549 }
550 }
551}
552
553// Walk the swap vector entries looking for conditions that prevent their
554// containing computations from being optimized. When such conditions are
555// found, mark the representative of the computation's equivalence class
556// as rejected.
557void PPCVSXSwapRemoval::recordUnoptimizableWebs() {
558
559 DEBUG(dbgs() << "\n*** Rejecting webs for swap removal ***\n\n");
560
561 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
562 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
563
564 // Reject webs containing mentions of physical registers or implicit
565 // subregs, or containing operations that we don't know how to handle
566 // in a lane-permuted region.
567 if (SwapVector[EntryIdx].MentionsPhysVR ||
568 SwapVector[EntryIdx].HasImplicitSubreg ||
569 !(SwapVector[EntryIdx].IsSwappable || SwapVector[EntryIdx].IsSwap)) {
570
571 SwapVector[Repr].WebRejected = 1;
572
573 DEBUG(dbgs() <<
574 format("Web %d rejected for physreg, subreg, or not swap[pable]\n",
575 Repr));
576 DEBUG(dbgs() << " in " << EntryIdx << ": ");
577 DEBUG(SwapVector[EntryIdx].VSEMI->dump());
578 DEBUG(dbgs() << "\n");
579 }
580
581 // Reject webs than contain swapping loads that feed something other
582 // than a swap instruction.
583 else if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
584 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
585 unsigned DefReg = MI->getOperand(0).getReg();
586
587 // We skip debug instructions in the analysis. (Note that debug
588 // location information is still maintained by this optimization
589 // because it remains on the LXVD2X and STXVD2X instructions after
590 // the XXPERMDIs are removed.)
591 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
592 int UseIdx = SwapMap[&UseMI];
593
594 if (!SwapVector[UseIdx].IsSwap || SwapVector[UseIdx].IsLoad ||
595 SwapVector[UseIdx].IsStore) {
596
597 SwapVector[Repr].WebRejected = 1;
598
599 DEBUG(dbgs() <<
600 format("Web %d rejected for load not feeding swap\n", Repr));
601 DEBUG(dbgs() << " def " << EntryIdx << ": ");
602 DEBUG(MI->dump());
603 DEBUG(dbgs() << " use " << UseIdx << ": ");
604 DEBUG(UseMI.dump());
605 DEBUG(dbgs() << "\n");
606 }
607 }
608
609 // Reject webs than contain swapping stores that are fed by something
610 // other than a swap instruction.
611 } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
612 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
613 unsigned UseReg = MI->getOperand(0).getReg();
614 MachineInstr *DefMI = MRI->getVRegDef(UseReg);
615 int DefIdx = SwapMap[DefMI];
616
617 if (!SwapVector[DefIdx].IsSwap || SwapVector[DefIdx].IsLoad ||
618 SwapVector[DefIdx].IsStore) {
619
620 SwapVector[Repr].WebRejected = 1;
621
622 DEBUG(dbgs() <<
623 format("Web %d rejected for store not fed by swap\n", Repr));
624 DEBUG(dbgs() << " def " << DefIdx << ": ");
625 DEBUG(DefMI->dump());
626 DEBUG(dbgs() << " use " << EntryIdx << ": ");
627 DEBUG(MI->dump());
628 DEBUG(dbgs() << "\n");
629 }
630 }
631 }
632
633 DEBUG(dbgs() << "Swap vector after web analysis:\n\n");
634 dumpSwapVector();
635}
636
637// Walk the swap vector entries looking for swaps fed by permuting loads
638// and swaps that feed permuting stores. If the containing computation
639// has not been marked rejected, mark each such swap for removal.
640// (Removal is delayed in case optimization has disturbed the pattern,
641// such that multiple loads feed the same swap, etc.)
642void PPCVSXSwapRemoval::markSwapsForRemoval() {
643
644 DEBUG(dbgs() << "\n*** Marking swaps for removal ***\n\n");
645
646 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
647
648 if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
649 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
650
651 if (!SwapVector[Repr].WebRejected) {
652 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
653 unsigned DefReg = MI->getOperand(0).getReg();
654
655 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
656 int UseIdx = SwapMap[&UseMI];
657 SwapVector[UseIdx].WillRemove = 1;
658
659 DEBUG(dbgs() << "Marking swap fed by load for removal: ");
660 DEBUG(UseMI.dump());
661 }
662 }
663
664 } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
665 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
666
667 if (!SwapVector[Repr].WebRejected) {
668 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
669 unsigned UseReg = MI->getOperand(0).getReg();
670 MachineInstr *DefMI = MRI->getVRegDef(UseReg);
671 int DefIdx = SwapMap[DefMI];
672 SwapVector[DefIdx].WillRemove = 1;
673
674 DEBUG(dbgs() << "Marking swap feeding store for removal: ");
675 DEBUG(DefMI->dump());
676 }
677
678 } else if (SwapVector[EntryIdx].IsSwappable &&
Bill Schmidt5fe2e252015-05-06 15:40:46 +0000679 SwapVector[EntryIdx].SpecialHandling != 0) {
680 int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
681
682 if (!SwapVector[Repr].WebRejected)
683 handleSpecialSwappables(EntryIdx);
684 }
Bill Schmidtfe723b92015-04-27 19:57:34 +0000685 }
686}
687
688// The identified swap entry requires special handling to allow its
689// containing computation to be optimized. Perform that handling
690// here.
691// FIXME: This code is to be phased in with subsequent patches.
692void PPCVSXSwapRemoval::handleSpecialSwappables(int EntryIdx) {
Bill Schmidt5fe2e252015-05-06 15:40:46 +0000693 switch (SwapVector[EntryIdx].SpecialHandling) {
694
695 default:
696 assert(false && "Unexpected special handling type");
697 break;
698
699 // For splats based on an index into a vector, add N/2 modulo N
700 // to the index, where N is the number of vector elements.
701 case SHValues::SH_SPLAT: {
702 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
703 unsigned NElts;
704
705 DEBUG(dbgs() << "Changing splat: ");
706 DEBUG(MI->dump());
707
708 switch (MI->getOpcode()) {
709 default:
710 assert(false && "Unexpected splat opcode");
711 case PPC::VSPLTB: NElts = 16; break;
712 case PPC::VSPLTH: NElts = 8; break;
713 case PPC::VSPLTW: NElts = 4; break;
714 }
715
716 unsigned EltNo = MI->getOperand(1).getImm();
717 EltNo = (EltNo + NElts / 2) % NElts;
718 MI->getOperand(1).setImm(EltNo);
719
720 DEBUG(dbgs() << " Into: ");
721 DEBUG(MI->dump());
722 break;
723 }
724
725 }
Bill Schmidtfe723b92015-04-27 19:57:34 +0000726}
727
728// Walk the swap vector and replace each entry marked for removal with
729// a copy operation.
730bool PPCVSXSwapRemoval::removeSwaps() {
731
732 DEBUG(dbgs() << "\n*** Removing swaps ***\n\n");
733
734 bool Changed = false;
735
736 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
737 if (SwapVector[EntryIdx].WillRemove) {
738 Changed = true;
739 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
740 MachineBasicBlock *MBB = MI->getParent();
741 BuildMI(*MBB, MI, MI->getDebugLoc(),
742 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
743 .addOperand(MI->getOperand(1));
744
745 DEBUG(dbgs() << format("Replaced %d with copy: ",
746 SwapVector[EntryIdx].VSEId));
747 DEBUG(MI->dump());
748
749 MI->eraseFromParent();
750 }
751 }
752
753 return Changed;
754}
755
756// For debug purposes, dump the contents of the swap vector.
757void PPCVSXSwapRemoval::dumpSwapVector() {
758
759 for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
760
761 MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
762 int ID = SwapVector[EntryIdx].VSEId;
763
764 DEBUG(dbgs() << format("%6d", ID));
765 DEBUG(dbgs() << format("%6d", EC->getLeaderValue(ID)));
766 DEBUG(dbgs() << format(" BB#%3d", MI->getParent()->getNumber()));
767 DEBUG(dbgs() << format(" %14s ", TII->getName(MI->getOpcode())));
768
769 if (SwapVector[EntryIdx].IsLoad)
770 DEBUG(dbgs() << "load ");
771 if (SwapVector[EntryIdx].IsStore)
772 DEBUG(dbgs() << "store ");
773 if (SwapVector[EntryIdx].IsSwap)
774 DEBUG(dbgs() << "swap ");
775 if (SwapVector[EntryIdx].MentionsPhysVR)
776 DEBUG(dbgs() << "physreg ");
777 if (SwapVector[EntryIdx].HasImplicitSubreg)
778 DEBUG(dbgs() << "implsubreg ");
779
780 if (SwapVector[EntryIdx].IsSwappable) {
781 DEBUG(dbgs() << "swappable ");
782 switch(SwapVector[EntryIdx].SpecialHandling) {
783 default:
784 DEBUG(dbgs() << "special:**unknown**");
785 break;
786 case SH_NONE:
787 break;
Bill Schmidtfe723b92015-04-27 19:57:34 +0000788 case SH_EXTRACT:
789 DEBUG(dbgs() << "special:extract ");
790 break;
791 case SH_INSERT:
792 DEBUG(dbgs() << "special:insert ");
793 break;
794 case SH_NOSWAP_LD:
795 DEBUG(dbgs() << "special:load ");
796 break;
797 case SH_NOSWAP_ST:
798 DEBUG(dbgs() << "special:store ");
799 break;
800 case SH_SPLAT:
801 DEBUG(dbgs() << "special:splat ");
802 break;
803 }
804 }
805
806 if (SwapVector[EntryIdx].WebRejected)
807 DEBUG(dbgs() << "rejected ");
808 if (SwapVector[EntryIdx].WillRemove)
809 DEBUG(dbgs() << "remove ");
810
811 DEBUG(dbgs() << "\n");
Bill Schmidte71db852015-04-27 20:22:35 +0000812
813 // For no-asserts builds.
814 (void)MI;
815 (void)ID;
Bill Schmidtfe723b92015-04-27 19:57:34 +0000816 }
817
818 DEBUG(dbgs() << "\n");
819}
820
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000821} // end default namespace
Bill Schmidtfe723b92015-04-27 19:57:34 +0000822
823INITIALIZE_PASS_BEGIN(PPCVSXSwapRemoval, DEBUG_TYPE,
824 "PowerPC VSX Swap Removal", false, false)
825INITIALIZE_PASS_END(PPCVSXSwapRemoval, DEBUG_TYPE,
826 "PowerPC VSX Swap Removal", false, false)
827
828char PPCVSXSwapRemoval::ID = 0;
829FunctionPass*
830llvm::createPPCVSXSwapRemovalPass() { return new PPCVSXSwapRemoval(); }