]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/PowerPC/PPCVSXSwapRemoval.cpp
MFV r308265: Update tzdata to 2016i.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / PowerPC / PPCVSXSwapRemoval.cpp
1 //===----------- 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
58 using namespace llvm;
59
60 #define DEBUG_TYPE "ppc-vsx-swaps"
61
62 namespace llvm {
63   void initializePPCVSXSwapRemovalPass(PassRegistry&);
64 }
65
66 namespace {
67
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.
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 IsSwappable : 1;
83   unsigned int MentionsPartialVR : 1;
84   unsigned int SpecialHandling : 3;
85   unsigned int WebRejected : 1;
86   unsigned int WillRemove : 1;
87 };
88
89 enum SHValues {
90   SH_NONE = 0,
91   SH_EXTRACT,
92   SH_INSERT,
93   SH_NOSWAP_LD,
94   SH_NOSWAP_ST,
95   SH_SPLAT,
96   SH_XXPERMDI,
97   SH_COPYWIDEN
98 };
99
100 struct PPCVSXSwapRemoval : public MachineFunctionPass {
101
102   static char ID;
103   const PPCInstrInfo *TII;
104   MachineFunction *MF;
105   MachineRegisterInfo *MRI;
106
107   // Swap entries are allocated in a vector for better performance.
108   std::vector<PPCVSXSwapEntry> SwapVector;
109
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;
113
114   // Equivalence classes are used to gather webs of related computation.
115   // Swap entries are represented by their VSEId fields.
116   EquivalenceClasses<int> *EC;
117
118   PPCVSXSwapRemoval() : MachineFunctionPass(ID) {
119     initializePPCVSXSwapRemovalPass(*PassRegistry::getPassRegistry());
120   }
121
122 private:
123   // Initialize data structures.
124   void initialize(MachineFunction &MFParm);
125
126   // Walk the machine instructions to gather vector usage information.
127   // Return true iff vector mentions are present.
128   bool gatherVectorInstructions();
129
130   // Add an entry to the swap vector and swap map.
131   int addSwapEntry(MachineInstr *MI, PPCVSXSwapEntry &SwapEntry);
132
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
136   // to one.
137   unsigned lookThruCopyLike(unsigned SrcReg, unsigned VecIdx);
138
139   // Generate equivalence classes for related computations (webs).
140   void formWebs();
141
142   // Analyze webs and determine those that cannot be optimized.
143   void recordUnoptimizableWebs();
144
145   // Record which swap instructions can be safely removed.
146   void markSwapsForRemoval();
147
148   // Remove swaps and update other instructions requiring special
149   // handling.  Return true iff any changes are made.
150   bool removeSwaps();
151
152   // Insert a swap instruction from SrcReg to DstReg at the given
153   // InsertPoint.
154   void insertSwap(MachineInstr *MI, MachineBasicBlock::iterator InsertPoint,
155                   unsigned DstReg, unsigned SrcReg);
156
157   // Update instructions requiring special handling.
158   void handleSpecialSwappables(int EntryIdx);
159
160   // Dump a description of the entries in the swap vector.
161   void dumpSwapVector();
162
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     return RC->contains(Reg);
168   }
169
170   // Return true iff the given register is a full vector register.
171   bool isVecReg(unsigned Reg) {
172     return (isRegInClass(Reg, &PPC::VSRCRegClass) ||
173             isRegInClass(Reg, &PPC::VRRCRegClass));
174   }
175
176   // Return true iff the given register is a partial vector register.
177   bool isScalarVecReg(unsigned Reg) {
178     return (isRegInClass(Reg, &PPC::VSFRCRegClass) ||
179             isRegInClass(Reg, &PPC::VSSRCRegClass));
180   }
181
182   // Return true iff the given register mentions all or part of a
183   // vector register.  Also sets Partial to true if the mention
184   // is for just the floating-point register overlap of the register.
185   bool isAnyVecReg(unsigned Reg, bool &Partial) {
186     if (isScalarVecReg(Reg))
187       Partial = true;
188     return isScalarVecReg(Reg) || isVecReg(Reg);
189   }
190
191 public:
192   // Main entry point for this pass.
193   bool runOnMachineFunction(MachineFunction &MF) override {
194     // If we don't have VSX on the subtarget, don't do anything.
195     const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>();
196     if (!STI.hasVSX())
197       return false;
198
199     bool Changed = false;
200     initialize(MF);
201
202     if (gatherVectorInstructions()) {
203       formWebs();
204       recordUnoptimizableWebs();
205       markSwapsForRemoval();
206       Changed = removeSwaps();
207     }
208
209     // FIXME: See the allocation of EC in initialize().
210     delete EC;
211     return Changed;
212   }
213 };
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.
218 void 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.
240 bool PPCVSXSwapRemoval::gatherVectorInstructions() {
241   bool RelevantFunction = false;
242
243   for (MachineBasicBlock &MBB : *MF) {
244     for (MachineInstr &MI : MBB) {
245
246       if (MI.isDebugValue())
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         unsigned Reg = MO.getReg();
256         if (isAnyVecReg(Reg, Partial)) {
257           RelevantInstr = true;
258           break;
259         }
260       }
261
262       if (!RelevantInstr)
263         continue;
264
265       RelevantFunction = true;
266
267       // Create a SwapEntry initialized to zeros, then fill in the
268       // instruction and ID fields before pushing it to the back
269       // of the swap vector.
270       PPCVSXSwapEntry SwapEntry{};
271       int VecIdx = addSwapEntry(&MI, SwapEntry);
272
273       switch(MI.getOpcode()) {
274       default:
275         // Unless noted otherwise, an instruction is considered
276         // safe for the optimization.  There are a large number of
277         // such true-SIMD instructions (all vector math, logical,
278         // select, compare, etc.).  However, if the instruction
279         // mentions a partial vector register and does not have
280         // special handling defined, it is not swappable.
281         if (Partial)
282           SwapVector[VecIdx].MentionsPartialVR = 1;
283         else
284           SwapVector[VecIdx].IsSwappable = 1;
285         break;
286       case PPC::XXPERMDI: {
287         // This is a swap if it is of the form XXPERMDI t, s, s, 2.
288         // Unfortunately, MachineCSE ignores COPY and SUBREG_TO_REG, so we
289         // can also see XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), 2,
290         // for example.  We have to look through chains of COPY and
291         // SUBREG_TO_REG to find the real source value for comparison.
292         // If the real source value is a physical register, then mark the
293         // XXPERMDI as mentioning a physical register.
294         int immed = MI.getOperand(3).getImm();
295         if (immed == 2) {
296           unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(),
297                                                VecIdx);
298           unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(),
299                                                VecIdx);
300           if (trueReg1 == trueReg2)
301             SwapVector[VecIdx].IsSwap = 1;
302           else {
303             // We can still handle these if the two registers are not
304             // identical, by adjusting the form of the XXPERMDI.
305             SwapVector[VecIdx].IsSwappable = 1;
306             SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
307           }
308         // This is a doubleword splat if it is of the form
309         // XXPERMDI t, s, s, 0 or XXPERMDI t, s, s, 3.  As above we
310         // must look through chains of copy-likes to find the source
311         // register.  We turn off the marking for mention of a physical
312         // register, because splatting it is safe; the optimization
313         // will not swap the value in the physical register.  Whether
314         // or not the two input registers are identical, we can handle
315         // these by adjusting the form of the XXPERMDI.
316         } else if (immed == 0 || immed == 3) {
317
318           SwapVector[VecIdx].IsSwappable = 1;
319           SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
320
321           unsigned trueReg1 = lookThruCopyLike(MI.getOperand(1).getReg(),
322                                                VecIdx);
323           unsigned trueReg2 = lookThruCopyLike(MI.getOperand(2).getReg(),
324                                                VecIdx);
325           if (trueReg1 == trueReg2)
326             SwapVector[VecIdx].MentionsPhysVR = 0;
327
328         } else {
329           // We can still handle these by adjusting the form of the XXPERMDI.
330           SwapVector[VecIdx].IsSwappable = 1;
331           SwapVector[VecIdx].SpecialHandling = SHValues::SH_XXPERMDI;
332         }
333         break;
334       }
335       case PPC::LVX:
336         // Non-permuting loads are currently unsafe.  We can use special
337         // handling for this in the future.  By not marking these as
338         // IsSwap, we ensure computations containing them will be rejected
339         // for now.
340         SwapVector[VecIdx].IsLoad = 1;
341         break;
342       case PPC::LXVD2X:
343       case PPC::LXVW4X:
344         // Permuting loads are marked as both load and swap, and are
345         // safe for optimization.
346         SwapVector[VecIdx].IsLoad = 1;
347         SwapVector[VecIdx].IsSwap = 1;
348         break;
349       case PPC::LXSDX:
350       case PPC::LXSSPX:
351         // A load of a floating-point value into the high-order half of
352         // a vector register is safe, provided that we introduce a swap
353         // following the load, which will be done by the SUBREG_TO_REG
354         // support.  So just mark these as safe.
355         SwapVector[VecIdx].IsLoad = 1;
356         SwapVector[VecIdx].IsSwappable = 1;
357         break;
358       case PPC::STVX:
359         // Non-permuting stores are currently unsafe.  We can use special
360         // handling for this in the future.  By not marking these as
361         // IsSwap, we ensure computations containing them will be rejected
362         // for now.
363         SwapVector[VecIdx].IsStore = 1;
364         break;
365       case PPC::STXVD2X:
366       case PPC::STXVW4X:
367         // Permuting stores are marked as both store and swap, and are
368         // safe for optimization.
369         SwapVector[VecIdx].IsStore = 1;
370         SwapVector[VecIdx].IsSwap = 1;
371         break;
372       case PPC::COPY:
373         // These are fine provided they are moving between full vector
374         // register classes.
375         if (isVecReg(MI.getOperand(0).getReg()) &&
376             isVecReg(MI.getOperand(1).getReg()))
377           SwapVector[VecIdx].IsSwappable = 1;
378         // If we have a copy from one scalar floating-point register
379         // to another, we can accept this even if it is a physical
380         // register.  The only way this gets involved is if it feeds
381         // a SUBREG_TO_REG, which is handled by introducing a swap.
382         else if (isScalarVecReg(MI.getOperand(0).getReg()) &&
383                  isScalarVecReg(MI.getOperand(1).getReg()))
384           SwapVector[VecIdx].IsSwappable = 1;
385         break;
386       case PPC::SUBREG_TO_REG: {
387         // These are fine provided they are moving between full vector
388         // register classes.  If they are moving from a scalar
389         // floating-point class to a vector class, we can handle those
390         // as well, provided we introduce a swap.  It is generally the
391         // case that we will introduce fewer swaps than we remove, but
392         // (FIXME) a cost model could be used.  However, introduced
393         // swaps could potentially be CSEd, so this is not trivial.
394         if (isVecReg(MI.getOperand(0).getReg()) &&
395             isVecReg(MI.getOperand(2).getReg()))
396           SwapVector[VecIdx].IsSwappable = 1;
397         else if (isVecReg(MI.getOperand(0).getReg()) &&
398                  isScalarVecReg(MI.getOperand(2).getReg())) {
399           SwapVector[VecIdx].IsSwappable = 1;
400           SwapVector[VecIdx].SpecialHandling = SHValues::SH_COPYWIDEN;
401         }
402         break;
403       }
404       case PPC::VSPLTB:
405       case PPC::VSPLTH:
406       case PPC::VSPLTW:
407         // Splats are lane-sensitive, but we can use special handling
408         // to adjust the source lane for the splat.  This is not yet
409         // implemented.  When it is, we need to uncomment the following:
410         SwapVector[VecIdx].IsSwappable = 1;
411         SwapVector[VecIdx].SpecialHandling = SHValues::SH_SPLAT;
412         break;
413       // The presence of the following lane-sensitive operations in a
414       // web will kill the optimization, at least for now.  For these
415       // we do nothing, causing the optimization to fail.
416       // FIXME: Some of these could be permitted with special handling,
417       // and will be phased in as time permits.
418       // FIXME: There is no simple and maintainable way to express a set
419       // of opcodes having a common attribute in TableGen.  Should this
420       // change, this is a prime candidate to use such a mechanism.
421       case PPC::INLINEASM:
422       case PPC::EXTRACT_SUBREG:
423       case PPC::INSERT_SUBREG:
424       case PPC::COPY_TO_REGCLASS:
425       case PPC::LVEBX:
426       case PPC::LVEHX:
427       case PPC::LVEWX:
428       case PPC::LVSL:
429       case PPC::LVSR:
430       case PPC::LVXL:
431       case PPC::STVEBX:
432       case PPC::STVEHX:
433       case PPC::STVEWX:
434       case PPC::STVXL:
435         // We can handle STXSDX and STXSSPX similarly to LXSDX and LXSSPX,
436         // by adding special handling for narrowing copies as well as
437         // widening ones.  However, I've experimented with this, and in
438         // practice we currently do not appear to use STXSDX fed by 
439         // a narrowing copy from a full vector register.  Since I can't
440         // generate any useful test cases, I've left this alone for now.
441       case PPC::STXSDX:
442       case PPC::STXSSPX:
443       case PPC::VCIPHER:
444       case PPC::VCIPHERLAST:
445       case PPC::VMRGHB:
446       case PPC::VMRGHH:
447       case PPC::VMRGHW:
448       case PPC::VMRGLB:
449       case PPC::VMRGLH:
450       case PPC::VMRGLW:
451       case PPC::VMULESB:
452       case PPC::VMULESH:
453       case PPC::VMULESW:
454       case PPC::VMULEUB:
455       case PPC::VMULEUH:
456       case PPC::VMULEUW:
457       case PPC::VMULOSB:
458       case PPC::VMULOSH:
459       case PPC::VMULOSW:
460       case PPC::VMULOUB:
461       case PPC::VMULOUH:
462       case PPC::VMULOUW:
463       case PPC::VNCIPHER:
464       case PPC::VNCIPHERLAST:
465       case PPC::VPERM:
466       case PPC::VPERMXOR:
467       case PPC::VPKPX:
468       case PPC::VPKSHSS:
469       case PPC::VPKSHUS:
470       case PPC::VPKSDSS:
471       case PPC::VPKSDUS:
472       case PPC::VPKSWSS:
473       case PPC::VPKSWUS:
474       case PPC::VPKUDUM:
475       case PPC::VPKUDUS:
476       case PPC::VPKUHUM:
477       case PPC::VPKUHUS:
478       case PPC::VPKUWUM:
479       case PPC::VPKUWUS:
480       case PPC::VPMSUMB:
481       case PPC::VPMSUMD:
482       case PPC::VPMSUMH:
483       case PPC::VPMSUMW:
484       case PPC::VRLB:
485       case PPC::VRLD:
486       case PPC::VRLH:
487       case PPC::VRLW:
488       case PPC::VSBOX:
489       case PPC::VSHASIGMAD:
490       case PPC::VSHASIGMAW:
491       case PPC::VSL:
492       case PPC::VSLDOI:
493       case PPC::VSLO:
494       case PPC::VSR:
495       case PPC::VSRO:
496       case PPC::VSUM2SWS:
497       case PPC::VSUM4SBS:
498       case PPC::VSUM4SHS:
499       case PPC::VSUM4UBS:
500       case PPC::VSUMSWS:
501       case PPC::VUPKHPX:
502       case PPC::VUPKHSB:
503       case PPC::VUPKHSH:
504       case PPC::VUPKHSW:
505       case PPC::VUPKLPX:
506       case PPC::VUPKLSB:
507       case PPC::VUPKLSH:
508       case PPC::VUPKLSW:
509       case PPC::XXMRGHW:
510       case PPC::XXMRGLW:
511       // XXSLDWI could be replaced by a general permute with one of three
512       // permute control vectors (for shift values 1, 2, 3).  However,
513       // VPERM has a more restrictive register class.
514       case PPC::XXSLDWI:
515       case PPC::XXSPLTW:
516         break;
517       }
518     }
519   }
520
521   if (RelevantFunction) {
522     DEBUG(dbgs() << "Swap vector when first built\n\n");
523     dumpSwapVector();
524   }
525
526   return RelevantFunction;
527 }
528
529 // Add an entry to the swap vector and swap map, and make a
530 // singleton equivalence class for the entry.
531 int PPCVSXSwapRemoval::addSwapEntry(MachineInstr *MI,
532                                   PPCVSXSwapEntry& SwapEntry) {
533   SwapEntry.VSEMI = MI;
534   SwapEntry.VSEId = SwapVector.size();
535   SwapVector.push_back(SwapEntry);
536   EC->insert(SwapEntry.VSEId);
537   SwapMap[MI] = SwapEntry.VSEId;
538   return SwapEntry.VSEId;
539 }
540
541 // This is used to find the "true" source register for an
542 // XXPERMDI instruction, since MachineCSE does not handle the
543 // "copy-like" operations (Copy and SubregToReg).  Returns
544 // the original SrcReg unless it is the target of a copy-like
545 // operation, in which case we chain backwards through all
546 // such operations to the ultimate source register.  If a
547 // physical register is encountered, we stop the search and
548 // flag the swap entry indicated by VecIdx (the original
549 // XXPERMDI) as mentioning a physical register.
550 unsigned PPCVSXSwapRemoval::lookThruCopyLike(unsigned SrcReg,
551                                              unsigned VecIdx) {
552   MachineInstr *MI = MRI->getVRegDef(SrcReg);
553   if (!MI->isCopyLike())
554     return SrcReg;
555
556   unsigned CopySrcReg;
557   if (MI->isCopy())
558     CopySrcReg = MI->getOperand(1).getReg();
559   else {
560     assert(MI->isSubregToReg() && "bad opcode for lookThruCopyLike");
561     CopySrcReg = MI->getOperand(2).getReg();
562   }
563
564   if (!TargetRegisterInfo::isVirtualRegister(CopySrcReg)) {
565     if (!isScalarVecReg(CopySrcReg))
566       SwapVector[VecIdx].MentionsPhysVR = 1;
567     return CopySrcReg;
568   }
569
570   return lookThruCopyLike(CopySrcReg, VecIdx);
571 }
572
573 // Generate equivalence classes for related computations (webs) by
574 // def-use relationships of virtual registers.  Mention of a physical
575 // register terminates the generation of equivalence classes as this
576 // indicates a use of a parameter, definition of a return value, use
577 // of a value returned from a call, or definition of a parameter to a
578 // call.  Computations with physical register mentions are flagged
579 // as such so their containing webs will not be optimized.
580 void PPCVSXSwapRemoval::formWebs() {
581
582   DEBUG(dbgs() << "\n*** Forming webs for swap removal ***\n\n");
583
584   for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
585
586     MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
587
588     DEBUG(dbgs() << "\n" << SwapVector[EntryIdx].VSEId << " ");
589     DEBUG(MI->dump());
590
591     // It's sufficient to walk vector uses and join them to their unique
592     // definitions.  In addition, check full vector register operands
593     // for physical regs.  We exclude partial-vector register operands
594     // because we can handle them if copied to a full vector.
595     for (const MachineOperand &MO : MI->operands()) {
596       if (!MO.isReg())
597         continue;
598
599       unsigned Reg = MO.getReg();
600       if (!isVecReg(Reg) && !isScalarVecReg(Reg))
601         continue;
602
603       if (!TargetRegisterInfo::isVirtualRegister(Reg)) {
604         if (!(MI->isCopy() && isScalarVecReg(Reg)))
605           SwapVector[EntryIdx].MentionsPhysVR = 1;
606         continue;
607       }
608
609       if (!MO.isUse())
610         continue;
611
612       MachineInstr* DefMI = MRI->getVRegDef(Reg);
613       assert(SwapMap.find(DefMI) != SwapMap.end() &&
614              "Inconsistency: def of vector reg not found in swap map!");
615       int DefIdx = SwapMap[DefMI];
616       (void)EC->unionSets(SwapVector[DefIdx].VSEId,
617                           SwapVector[EntryIdx].VSEId);
618
619       DEBUG(dbgs() << format("Unioning %d with %d\n", SwapVector[DefIdx].VSEId,
620                              SwapVector[EntryIdx].VSEId));
621       DEBUG(dbgs() << "  Def: ");
622       DEBUG(DefMI->dump());
623     }
624   }
625 }
626
627 // Walk the swap vector entries looking for conditions that prevent their
628 // containing computations from being optimized.  When such conditions are
629 // found, mark the representative of the computation's equivalence class
630 // as rejected.
631 void PPCVSXSwapRemoval::recordUnoptimizableWebs() {
632
633   DEBUG(dbgs() << "\n*** Rejecting webs for swap removal ***\n\n");
634
635   for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
636     int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
637
638     // If representative is already rejected, don't waste further time.
639     if (SwapVector[Repr].WebRejected)
640       continue;
641
642     // Reject webs containing mentions of physical or partial registers, or
643     // containing operations that we don't know how to handle in a lane-
644     // permuted region.
645     if (SwapVector[EntryIdx].MentionsPhysVR ||
646         SwapVector[EntryIdx].MentionsPartialVR ||
647         !(SwapVector[EntryIdx].IsSwappable || SwapVector[EntryIdx].IsSwap)) {
648
649       SwapVector[Repr].WebRejected = 1;
650
651       DEBUG(dbgs() <<
652             format("Web %d rejected for physreg, partial reg, or not "
653                    "swap[pable]\n", Repr));
654       DEBUG(dbgs() << "  in " << EntryIdx << ": ");
655       DEBUG(SwapVector[EntryIdx].VSEMI->dump());
656       DEBUG(dbgs() << "\n");
657     }
658
659     // Reject webs than contain swapping loads that feed something other
660     // than a swap instruction.
661     else if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
662       MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
663       unsigned DefReg = MI->getOperand(0).getReg();
664
665       // We skip debug instructions in the analysis.  (Note that debug
666       // location information is still maintained by this optimization
667       // because it remains on the LXVD2X and STXVD2X instructions after
668       // the XXPERMDIs are removed.)
669       for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
670         int UseIdx = SwapMap[&UseMI];
671
672         if (!SwapVector[UseIdx].IsSwap || SwapVector[UseIdx].IsLoad ||
673             SwapVector[UseIdx].IsStore) {
674
675           SwapVector[Repr].WebRejected = 1;
676
677           DEBUG(dbgs() <<
678                 format("Web %d rejected for load not feeding swap\n", Repr));
679           DEBUG(dbgs() << "  def " << EntryIdx << ": ");
680           DEBUG(MI->dump());
681           DEBUG(dbgs() << "  use " << UseIdx << ": ");
682           DEBUG(UseMI.dump());
683           DEBUG(dbgs() << "\n");
684         }
685       }
686
687     // Reject webs that contain swapping stores that are fed by something
688     // other than a swap instruction.
689     } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
690       MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
691       unsigned UseReg = MI->getOperand(0).getReg();
692       MachineInstr *DefMI = MRI->getVRegDef(UseReg);
693       int DefIdx = SwapMap[DefMI];
694
695       if (!SwapVector[DefIdx].IsSwap || SwapVector[DefIdx].IsLoad ||
696           SwapVector[DefIdx].IsStore) {
697
698         SwapVector[Repr].WebRejected = 1;
699
700         DEBUG(dbgs() <<
701               format("Web %d rejected for store not fed by swap\n", Repr));
702         DEBUG(dbgs() << "  def " << DefIdx << ": ");
703         DEBUG(DefMI->dump());
704         DEBUG(dbgs() << "  use " << EntryIdx << ": ");
705         DEBUG(MI->dump());
706         DEBUG(dbgs() << "\n");
707       }
708     }
709   }
710
711   DEBUG(dbgs() << "Swap vector after web analysis:\n\n");
712   dumpSwapVector();
713 }
714
715 // Walk the swap vector entries looking for swaps fed by permuting loads
716 // and swaps that feed permuting stores.  If the containing computation
717 // has not been marked rejected, mark each such swap for removal.
718 // (Removal is delayed in case optimization has disturbed the pattern,
719 // such that multiple loads feed the same swap, etc.)
720 void PPCVSXSwapRemoval::markSwapsForRemoval() {
721
722   DEBUG(dbgs() << "\n*** Marking swaps for removal ***\n\n");
723
724   for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
725
726     if (SwapVector[EntryIdx].IsLoad && SwapVector[EntryIdx].IsSwap) {
727       int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
728
729       if (!SwapVector[Repr].WebRejected) {
730         MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
731         unsigned DefReg = MI->getOperand(0).getReg();
732
733         for (MachineInstr &UseMI : MRI->use_nodbg_instructions(DefReg)) {
734           int UseIdx = SwapMap[&UseMI];
735           SwapVector[UseIdx].WillRemove = 1;
736
737           DEBUG(dbgs() << "Marking swap fed by load for removal: ");
738           DEBUG(UseMI.dump());
739         }
740       }
741
742     } else if (SwapVector[EntryIdx].IsStore && SwapVector[EntryIdx].IsSwap) {
743       int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
744
745       if (!SwapVector[Repr].WebRejected) {
746         MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
747         unsigned UseReg = MI->getOperand(0).getReg();
748         MachineInstr *DefMI = MRI->getVRegDef(UseReg);
749         int DefIdx = SwapMap[DefMI];
750         SwapVector[DefIdx].WillRemove = 1;
751
752         DEBUG(dbgs() << "Marking swap feeding store for removal: ");
753         DEBUG(DefMI->dump());
754       }
755
756     } else if (SwapVector[EntryIdx].IsSwappable &&
757                SwapVector[EntryIdx].SpecialHandling != 0) {
758       int Repr = EC->getLeaderValue(SwapVector[EntryIdx].VSEId);
759
760       if (!SwapVector[Repr].WebRejected)
761         handleSpecialSwappables(EntryIdx);
762     }
763   }
764 }
765
766 // Create an xxswapd instruction and insert it prior to the given point.
767 // MI is used to determine basic block and debug loc information.
768 // FIXME: When inserting a swap, we should check whether SrcReg is
769 // defined by another swap:  SrcReg = XXPERMDI Reg, Reg, 2;  If so,
770 // then instead we should generate a copy from Reg to DstReg.
771 void PPCVSXSwapRemoval::insertSwap(MachineInstr *MI,
772                                    MachineBasicBlock::iterator InsertPoint,
773                                    unsigned DstReg, unsigned SrcReg) {
774   BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
775           TII->get(PPC::XXPERMDI), DstReg)
776     .addReg(SrcReg)
777     .addReg(SrcReg)
778     .addImm(2);
779 }
780
781 // The identified swap entry requires special handling to allow its
782 // containing computation to be optimized.  Perform that handling
783 // here.
784 // FIXME: Additional opportunities will be phased in with subsequent
785 // patches.
786 void PPCVSXSwapRemoval::handleSpecialSwappables(int EntryIdx) {
787   switch (SwapVector[EntryIdx].SpecialHandling) {
788
789   default:
790     llvm_unreachable("Unexpected special handling type");
791
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;
796     unsigned NElts;
797
798     DEBUG(dbgs() << "Changing splat: ");
799     DEBUG(MI->dump());
800
801     switch (MI->getOpcode()) {
802     default:
803       llvm_unreachable("Unexpected splat opcode");
804     case PPC::VSPLTB: NElts = 16; break;
805     case PPC::VSPLTH: NElts = 8;  break;
806     case PPC::VSPLTW: NElts = 4;  break;
807     }
808
809     unsigned EltNo = MI->getOperand(1).getImm();
810     EltNo = (EltNo + NElts / 2) % NElts;
811     MI->getOperand(1).setImm(EltNo);
812
813     DEBUG(dbgs() << "  Into: ");
814     DEBUG(MI->dump());
815     break;
816   }
817
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;
826
827     DEBUG(dbgs() << "Changing XXPERMDI: ");
828     DEBUG(MI->dump());
829
830     unsigned Selector = MI->getOperand(3).getImm();
831     if (Selector == 0 || Selector == 3)
832       Selector = 3 - Selector;
833     MI->getOperand(3).setImm(Selector);
834
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);
839
840     DEBUG(dbgs() << "  Into: ");
841     DEBUG(MI->dump());
842     break;
843   }
844
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;
850
851     DEBUG(dbgs() << "Changing SUBREG_TO_REG: ");
852     DEBUG(MI->dump());
853
854     unsigned DstReg = MI->getOperand(0).getReg();
855     const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
856     unsigned NewVReg = MRI->createVirtualRegister(DstRC);
857
858     MI->getOperand(0).setReg(NewVReg);
859     DEBUG(dbgs() << "  Into: ");
860     DEBUG(MI->dump());
861
862     auto InsertPoint = ++MachineBasicBlock::iterator(MI);
863
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);
872
873       BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
874               TII->get(PPC::COPY), VSRCTmp1)
875         .addReg(NewVReg);
876       DEBUG(std::prev(InsertPoint)->dump());
877
878       insertSwap(MI, InsertPoint, VSRCTmp2, VSRCTmp1);
879       DEBUG(std::prev(InsertPoint)->dump());
880
881       BuildMI(*MI->getParent(), InsertPoint, MI->getDebugLoc(),
882               TII->get(PPC::COPY), DstReg)
883         .addReg(VSRCTmp2);
884       DEBUG(std::prev(InsertPoint)->dump());
885
886     } else {
887       insertSwap(MI, InsertPoint, DstReg, NewVReg);
888       DEBUG(std::prev(InsertPoint)->dump());
889     }
890     break;
891   }
892   }
893 }
894
895 // Walk the swap vector and replace each entry marked for removal with
896 // a copy operation.
897 bool PPCVSXSwapRemoval::removeSwaps() {
898
899   DEBUG(dbgs() << "\n*** Removing swaps ***\n\n");
900
901   bool Changed = false;
902
903   for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
904     if (SwapVector[EntryIdx].WillRemove) {
905       Changed = true;
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));
911
912       DEBUG(dbgs() << format("Replaced %d with copy: ",
913                              SwapVector[EntryIdx].VSEId));
914       DEBUG(MI->dump());
915
916       MI->eraseFromParent();
917     }
918   }
919
920   return Changed;
921 }
922
923 // For debug purposes, dump the contents of the swap vector.
924 void PPCVSXSwapRemoval::dumpSwapVector() {
925
926   for (unsigned EntryIdx = 0; EntryIdx < SwapVector.size(); ++EntryIdx) {
927
928     MachineInstr *MI = SwapVector[EntryIdx].VSEMI;
929     int ID = SwapVector[EntryIdx].VSEId;
930
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())));
935
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 ");
946
947     if (SwapVector[EntryIdx].IsSwappable) {
948       DEBUG(dbgs() << "swappable ");
949       switch(SwapVector[EntryIdx].SpecialHandling) {
950       default:
951         DEBUG(dbgs() << "special:**unknown**");
952         break;
953       case SH_NONE:
954         break;
955       case SH_EXTRACT:
956         DEBUG(dbgs() << "special:extract ");
957         break;
958       case SH_INSERT:
959         DEBUG(dbgs() << "special:insert ");
960         break;
961       case SH_NOSWAP_LD:
962         DEBUG(dbgs() << "special:load ");
963         break;
964       case SH_NOSWAP_ST:
965         DEBUG(dbgs() << "special:store ");
966         break;
967       case SH_SPLAT:
968         DEBUG(dbgs() << "special:splat ");
969         break;
970       case SH_XXPERMDI:
971         DEBUG(dbgs() << "special:xxpermdi ");
972         break;
973       case SH_COPYWIDEN:
974         DEBUG(dbgs() << "special:copywiden ");
975         break;
976       }
977     }
978
979     if (SwapVector[EntryIdx].WebRejected)
980       DEBUG(dbgs() << "rejected ");
981     if (SwapVector[EntryIdx].WillRemove)
982       DEBUG(dbgs() << "remove ");
983
984     DEBUG(dbgs() << "\n");
985
986     // For no-asserts builds.
987     (void)MI;
988     (void)ID;
989   }
990
991   DEBUG(dbgs() << "\n");
992 }
993
994 } // end default namespace
995
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)
1000
1001 char PPCVSXSwapRemoval::ID = 0;
1002 FunctionPass*
1003 llvm::createPPCVSXSwapRemovalPass() { return new PPCVSXSwapRemoval(); }