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