]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/lib/Target/ARM/A15SDOptimizer.cpp
MFC r355940:
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / lib / Target / ARM / A15SDOptimizer.cpp
1 //=== A15SDOptimizerPass.cpp - Optimize DPR and SPR register accesses on A15==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The Cortex-A15 processor employs a tracking scheme in its register renaming
10 // in order to process each instruction's micro-ops speculatively and
11 // out-of-order with appropriate forwarding. The ARM architecture allows VFP
12 // instructions to read and write 32-bit S-registers.  Each S-register
13 // corresponds to one half (upper or lower) of an overlaid 64-bit D-register.
14 //
15 // There are several instruction patterns which can be used to provide this
16 // capability which can provide higher performance than other, potentially more
17 // direct patterns, specifically around when one micro-op reads a D-register
18 // operand that has recently been written as one or more S-register results.
19 //
20 // This file defines a pre-regalloc pass which looks for SPR producers which
21 // are going to be used by a DPR (or QPR) consumers and creates the more
22 // optimized access pattern.
23 //
24 //===----------------------------------------------------------------------===//
25
26 #include "ARM.h"
27 #include "ARMBaseInstrInfo.h"
28 #include "ARMBaseRegisterInfo.h"
29 #include "ARMSubtarget.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/TargetRegisterInfo.h"
37 #include "llvm/CodeGen/TargetSubtargetInfo.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <map>
41 #include <set>
42
43 using namespace llvm;
44
45 #define DEBUG_TYPE "a15-sd-optimizer"
46
47 namespace {
48   struct A15SDOptimizer : public MachineFunctionPass {
49     static char ID;
50     A15SDOptimizer() : MachineFunctionPass(ID) {}
51
52     bool runOnMachineFunction(MachineFunction &Fn) override;
53
54     StringRef getPassName() const override { return "ARM A15 S->D optimizer"; }
55
56   private:
57     const ARMBaseInstrInfo *TII;
58     const TargetRegisterInfo *TRI;
59     MachineRegisterInfo *MRI;
60
61     bool runOnInstruction(MachineInstr *MI);
62
63     //
64     // Instruction builder helpers
65     //
66     unsigned createDupLane(MachineBasicBlock &MBB,
67                            MachineBasicBlock::iterator InsertBefore,
68                            const DebugLoc &DL, unsigned Reg, unsigned Lane,
69                            bool QPR = false);
70
71     unsigned createExtractSubreg(MachineBasicBlock &MBB,
72                                  MachineBasicBlock::iterator InsertBefore,
73                                  const DebugLoc &DL, unsigned DReg,
74                                  unsigned Lane, const TargetRegisterClass *TRC);
75
76     unsigned createVExt(MachineBasicBlock &MBB,
77                         MachineBasicBlock::iterator InsertBefore,
78                         const DebugLoc &DL, unsigned Ssub0, unsigned Ssub1);
79
80     unsigned createRegSequence(MachineBasicBlock &MBB,
81                                MachineBasicBlock::iterator InsertBefore,
82                                const DebugLoc &DL, unsigned Reg1,
83                                unsigned Reg2);
84
85     unsigned createInsertSubreg(MachineBasicBlock &MBB,
86                                 MachineBasicBlock::iterator InsertBefore,
87                                 const DebugLoc &DL, unsigned DReg,
88                                 unsigned Lane, unsigned ToInsert);
89
90     unsigned createImplicitDef(MachineBasicBlock &MBB,
91                                MachineBasicBlock::iterator InsertBefore,
92                                const DebugLoc &DL);
93
94     //
95     // Various property checkers
96     //
97     bool usesRegClass(MachineOperand &MO, const TargetRegisterClass *TRC);
98     bool hasPartialWrite(MachineInstr *MI);
99     SmallVector<unsigned, 8> getReadDPRs(MachineInstr *MI);
100     unsigned getDPRLaneFromSPR(unsigned SReg);
101
102     //
103     // Methods used for getting the definitions of partial registers
104     //
105
106     MachineInstr *elideCopies(MachineInstr *MI);
107     void elideCopiesAndPHIs(MachineInstr *MI,
108                             SmallVectorImpl<MachineInstr*> &Outs);
109
110     //
111     // Pattern optimization methods
112     //
113     unsigned optimizeAllLanesPattern(MachineInstr *MI, unsigned Reg);
114     unsigned optimizeSDPattern(MachineInstr *MI);
115     unsigned getPrefSPRLane(unsigned SReg);
116
117     //
118     // Sanitizing method - used to make sure if don't leave dead code around.
119     //
120     void eraseInstrWithNoUses(MachineInstr *MI);
121
122     //
123     // A map used to track the changes done by this pass.
124     //
125     std::map<MachineInstr*, unsigned> Replacements;
126     std::set<MachineInstr *> DeadInstr;
127   };
128   char A15SDOptimizer::ID = 0;
129 } // end anonymous namespace
130
131 // Returns true if this is a use of a SPR register.
132 bool A15SDOptimizer::usesRegClass(MachineOperand &MO,
133                                   const TargetRegisterClass *TRC) {
134   if (!MO.isReg())
135     return false;
136   unsigned Reg = MO.getReg();
137
138   if (TargetRegisterInfo::isVirtualRegister(Reg))
139     return MRI->getRegClass(Reg)->hasSuperClassEq(TRC);
140   else
141     return TRC->contains(Reg);
142 }
143
144 unsigned A15SDOptimizer::getDPRLaneFromSPR(unsigned SReg) {
145   unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1,
146                                            &ARM::DPRRegClass);
147   if (DReg != ARM::NoRegister) return ARM::ssub_1;
148   return ARM::ssub_0;
149 }
150
151 // Get the subreg type that is most likely to be coalesced
152 // for an SPR register that will be used in VDUP32d pseudo.
153 unsigned A15SDOptimizer::getPrefSPRLane(unsigned SReg) {
154   if (!TRI->isVirtualRegister(SReg))
155     return getDPRLaneFromSPR(SReg);
156
157   MachineInstr *MI = MRI->getVRegDef(SReg);
158   if (!MI) return ARM::ssub_0;
159   MachineOperand *MO = MI->findRegisterDefOperand(SReg);
160
161   assert(MO->isReg() && "Non-register operand found!");
162   if (!MO) return ARM::ssub_0;
163
164   if (MI->isCopy() && usesRegClass(MI->getOperand(1),
165                                     &ARM::SPRRegClass)) {
166     SReg = MI->getOperand(1).getReg();
167   }
168
169   if (TargetRegisterInfo::isVirtualRegister(SReg)) {
170     if (MO->getSubReg() == ARM::ssub_1) return ARM::ssub_1;
171     return ARM::ssub_0;
172   }
173   return getDPRLaneFromSPR(SReg);
174 }
175
176 // MI is known to be dead. Figure out what instructions
177 // are also made dead by this and mark them for removal.
178 void A15SDOptimizer::eraseInstrWithNoUses(MachineInstr *MI) {
179   SmallVector<MachineInstr *, 8> Front;
180   DeadInstr.insert(MI);
181
182   LLVM_DEBUG(dbgs() << "Deleting base instruction " << *MI << "\n");
183   Front.push_back(MI);
184
185   while (Front.size() != 0) {
186     MI = Front.back();
187     Front.pop_back();
188
189     // MI is already known to be dead. We need to see
190     // if other instructions can also be removed.
191     for (MachineOperand &MO : MI->operands()) {
192       if ((!MO.isReg()) || (!MO.isUse()))
193         continue;
194       unsigned Reg = MO.getReg();
195       if (!TRI->isVirtualRegister(Reg))
196         continue;
197       MachineOperand *Op = MI->findRegisterDefOperand(Reg);
198
199       if (!Op)
200         continue;
201
202       MachineInstr *Def = Op->getParent();
203
204       // We don't need to do anything if we have already marked
205       // this instruction as being dead.
206       if (DeadInstr.find(Def) != DeadInstr.end())
207         continue;
208
209       // Check if all the uses of this instruction are marked as
210       // dead. If so, we can also mark this instruction as being
211       // dead.
212       bool IsDead = true;
213       for (MachineOperand &MODef : Def->operands()) {
214         if ((!MODef.isReg()) || (!MODef.isDef()))
215           continue;
216         unsigned DefReg = MODef.getReg();
217         if (!TRI->isVirtualRegister(DefReg)) {
218           IsDead = false;
219           break;
220         }
221         for (MachineInstr &Use : MRI->use_instructions(Reg)) {
222           // We don't care about self references.
223           if (&Use == Def)
224             continue;
225           if (DeadInstr.find(&Use) == DeadInstr.end()) {
226             IsDead = false;
227             break;
228           }
229         }
230       }
231
232       if (!IsDead) continue;
233
234       LLVM_DEBUG(dbgs() << "Deleting instruction " << *Def << "\n");
235       DeadInstr.insert(Def);
236     }
237   }
238 }
239
240 // Creates the more optimized patterns and generally does all the code
241 // transformations in this pass.
242 unsigned A15SDOptimizer::optimizeSDPattern(MachineInstr *MI) {
243   if (MI->isCopy()) {
244     return optimizeAllLanesPattern(MI, MI->getOperand(1).getReg());
245   }
246
247   if (MI->isInsertSubreg()) {
248     unsigned DPRReg = MI->getOperand(1).getReg();
249     unsigned SPRReg = MI->getOperand(2).getReg();
250
251     if (TRI->isVirtualRegister(DPRReg) && TRI->isVirtualRegister(SPRReg)) {
252       MachineInstr *DPRMI = MRI->getVRegDef(MI->getOperand(1).getReg());
253       MachineInstr *SPRMI = MRI->getVRegDef(MI->getOperand(2).getReg());
254
255       if (DPRMI && SPRMI) {
256         // See if the first operand of this insert_subreg is IMPLICIT_DEF
257         MachineInstr *ECDef = elideCopies(DPRMI);
258         if (ECDef && ECDef->isImplicitDef()) {
259           // Another corner case - if we're inserting something that is purely
260           // a subreg copy of a DPR, just use that DPR.
261
262           MachineInstr *EC = elideCopies(SPRMI);
263           // Is it a subreg copy of ssub_0?
264           if (EC && EC->isCopy() &&
265               EC->getOperand(1).getSubReg() == ARM::ssub_0) {
266             LLVM_DEBUG(dbgs() << "Found a subreg copy: " << *SPRMI);
267
268             // Find the thing we're subreg copying out of - is it of the same
269             // regclass as DPRMI? (i.e. a DPR or QPR).
270             unsigned FullReg = SPRMI->getOperand(1).getReg();
271             const TargetRegisterClass *TRC =
272               MRI->getRegClass(MI->getOperand(1).getReg());
273             if (TRC->hasSuperClassEq(MRI->getRegClass(FullReg))) {
274               LLVM_DEBUG(dbgs() << "Subreg copy is compatible - returning ");
275               LLVM_DEBUG(dbgs() << printReg(FullReg) << "\n");
276               eraseInstrWithNoUses(MI);
277               return FullReg;
278             }
279           }
280
281           return optimizeAllLanesPattern(MI, MI->getOperand(2).getReg());
282         }
283       }
284     }
285     return optimizeAllLanesPattern(MI, MI->getOperand(0).getReg());
286   }
287
288   if (MI->isRegSequence() && usesRegClass(MI->getOperand(1),
289                                           &ARM::SPRRegClass)) {
290     // See if all bar one of the operands are IMPLICIT_DEF and insert the
291     // optimizer pattern accordingly.
292     unsigned NumImplicit = 0, NumTotal = 0;
293     unsigned NonImplicitReg = ~0U;
294
295     for (unsigned I = 1; I < MI->getNumExplicitOperands(); ++I) {
296       if (!MI->getOperand(I).isReg())
297         continue;
298       ++NumTotal;
299       unsigned OpReg = MI->getOperand(I).getReg();
300
301       if (!TRI->isVirtualRegister(OpReg))
302         break;
303
304       MachineInstr *Def = MRI->getVRegDef(OpReg);
305       if (!Def)
306         break;
307       if (Def->isImplicitDef())
308         ++NumImplicit;
309       else
310         NonImplicitReg = MI->getOperand(I).getReg();
311     }
312
313     if (NumImplicit == NumTotal - 1)
314       return optimizeAllLanesPattern(MI, NonImplicitReg);
315     else
316       return optimizeAllLanesPattern(MI, MI->getOperand(0).getReg());
317   }
318
319   llvm_unreachable("Unhandled update pattern!");
320 }
321
322 // Return true if this MachineInstr inserts a scalar (SPR) value into
323 // a D or Q register.
324 bool A15SDOptimizer::hasPartialWrite(MachineInstr *MI) {
325   // The only way we can do a partial register update is through a COPY,
326   // INSERT_SUBREG or REG_SEQUENCE.
327   if (MI->isCopy() && usesRegClass(MI->getOperand(1), &ARM::SPRRegClass))
328     return true;
329
330   if (MI->isInsertSubreg() && usesRegClass(MI->getOperand(2),
331                                            &ARM::SPRRegClass))
332     return true;
333
334   if (MI->isRegSequence() && usesRegClass(MI->getOperand(1), &ARM::SPRRegClass))
335     return true;
336
337   return false;
338 }
339
340 // Looks through full copies to get the instruction that defines the input
341 // operand for MI.
342 MachineInstr *A15SDOptimizer::elideCopies(MachineInstr *MI) {
343   if (!MI->isFullCopy())
344     return MI;
345   if (!TRI->isVirtualRegister(MI->getOperand(1).getReg()))
346     return nullptr;
347   MachineInstr *Def = MRI->getVRegDef(MI->getOperand(1).getReg());
348   if (!Def)
349     return nullptr;
350   return elideCopies(Def);
351 }
352
353 // Look through full copies and PHIs to get the set of non-copy MachineInstrs
354 // that can produce MI.
355 void A15SDOptimizer::elideCopiesAndPHIs(MachineInstr *MI,
356                                         SmallVectorImpl<MachineInstr*> &Outs) {
357    // Looking through PHIs may create loops so we need to track what
358    // instructions we have visited before.
359    std::set<MachineInstr *> Reached;
360    SmallVector<MachineInstr *, 8> Front;
361    Front.push_back(MI);
362    while (Front.size() != 0) {
363      MI = Front.back();
364      Front.pop_back();
365
366      // If we have already explored this MachineInstr, ignore it.
367      if (Reached.find(MI) != Reached.end())
368        continue;
369      Reached.insert(MI);
370      if (MI->isPHI()) {
371        for (unsigned I = 1, E = MI->getNumOperands(); I != E; I += 2) {
372          unsigned Reg = MI->getOperand(I).getReg();
373          if (!TRI->isVirtualRegister(Reg)) {
374            continue;
375          }
376          MachineInstr *NewMI = MRI->getVRegDef(Reg);
377          if (!NewMI)
378            continue;
379          Front.push_back(NewMI);
380        }
381      } else if (MI->isFullCopy()) {
382        if (!TRI->isVirtualRegister(MI->getOperand(1).getReg()))
383          continue;
384        MachineInstr *NewMI = MRI->getVRegDef(MI->getOperand(1).getReg());
385        if (!NewMI)
386          continue;
387        Front.push_back(NewMI);
388      } else {
389        LLVM_DEBUG(dbgs() << "Found partial copy" << *MI << "\n");
390        Outs.push_back(MI);
391      }
392    }
393 }
394
395 // Return the DPR virtual registers that are read by this machine instruction
396 // (if any).
397 SmallVector<unsigned, 8> A15SDOptimizer::getReadDPRs(MachineInstr *MI) {
398   if (MI->isCopyLike() || MI->isInsertSubreg() || MI->isRegSequence() ||
399       MI->isKill())
400     return SmallVector<unsigned, 8>();
401
402   SmallVector<unsigned, 8> Defs;
403   for (MachineOperand &MO : MI->operands()) {
404     if (!MO.isReg() || !MO.isUse())
405       continue;
406     if (!usesRegClass(MO, &ARM::DPRRegClass) &&
407         !usesRegClass(MO, &ARM::QPRRegClass) &&
408         !usesRegClass(MO, &ARM::DPairRegClass)) // Treat DPair as QPR
409       continue;
410
411     Defs.push_back(MO.getReg());
412   }
413   return Defs;
414 }
415
416 // Creates a DPR register from an SPR one by using a VDUP.
417 unsigned A15SDOptimizer::createDupLane(MachineBasicBlock &MBB,
418                                        MachineBasicBlock::iterator InsertBefore,
419                                        const DebugLoc &DL, unsigned Reg,
420                                        unsigned Lane, bool QPR) {
421   unsigned Out = MRI->createVirtualRegister(QPR ? &ARM::QPRRegClass :
422                                                   &ARM::DPRRegClass);
423   BuildMI(MBB, InsertBefore, DL,
424           TII->get(QPR ? ARM::VDUPLN32q : ARM::VDUPLN32d), Out)
425       .addReg(Reg)
426       .addImm(Lane)
427       .add(predOps(ARMCC::AL));
428
429   return Out;
430 }
431
432 // Creates a SPR register from a DPR by copying the value in lane 0.
433 unsigned A15SDOptimizer::createExtractSubreg(
434     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
435     const DebugLoc &DL, unsigned DReg, unsigned Lane,
436     const TargetRegisterClass *TRC) {
437   unsigned Out = MRI->createVirtualRegister(TRC);
438   BuildMI(MBB,
439           InsertBefore,
440           DL,
441           TII->get(TargetOpcode::COPY), Out)
442     .addReg(DReg, 0, Lane);
443
444   return Out;
445 }
446
447 // Takes two SPR registers and creates a DPR by using a REG_SEQUENCE.
448 unsigned A15SDOptimizer::createRegSequence(
449     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
450     const DebugLoc &DL, unsigned Reg1, unsigned Reg2) {
451   unsigned Out = MRI->createVirtualRegister(&ARM::QPRRegClass);
452   BuildMI(MBB,
453           InsertBefore,
454           DL,
455           TII->get(TargetOpcode::REG_SEQUENCE), Out)
456     .addReg(Reg1)
457     .addImm(ARM::dsub_0)
458     .addReg(Reg2)
459     .addImm(ARM::dsub_1);
460   return Out;
461 }
462
463 // Takes two DPR registers that have previously been VDUPed (Ssub0 and Ssub1)
464 // and merges them into one DPR register.
465 unsigned A15SDOptimizer::createVExt(MachineBasicBlock &MBB,
466                                     MachineBasicBlock::iterator InsertBefore,
467                                     const DebugLoc &DL, unsigned Ssub0,
468                                     unsigned Ssub1) {
469   unsigned Out = MRI->createVirtualRegister(&ARM::DPRRegClass);
470   BuildMI(MBB, InsertBefore, DL, TII->get(ARM::VEXTd32), Out)
471       .addReg(Ssub0)
472       .addReg(Ssub1)
473       .addImm(1)
474       .add(predOps(ARMCC::AL));
475   return Out;
476 }
477
478 unsigned A15SDOptimizer::createInsertSubreg(
479     MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore,
480     const DebugLoc &DL, unsigned DReg, unsigned Lane, unsigned ToInsert) {
481   unsigned Out = MRI->createVirtualRegister(&ARM::DPR_VFP2RegClass);
482   BuildMI(MBB,
483           InsertBefore,
484           DL,
485           TII->get(TargetOpcode::INSERT_SUBREG), Out)
486     .addReg(DReg)
487     .addReg(ToInsert)
488     .addImm(Lane);
489
490   return Out;
491 }
492
493 unsigned
494 A15SDOptimizer::createImplicitDef(MachineBasicBlock &MBB,
495                                   MachineBasicBlock::iterator InsertBefore,
496                                   const DebugLoc &DL) {
497   unsigned Out = MRI->createVirtualRegister(&ARM::DPRRegClass);
498   BuildMI(MBB,
499           InsertBefore,
500           DL,
501           TII->get(TargetOpcode::IMPLICIT_DEF), Out);
502   return Out;
503 }
504
505 // This function inserts instructions in order to optimize interactions between
506 // SPR registers and DPR/QPR registers. It does so by performing VDUPs on all
507 // lanes, and the using VEXT instructions to recompose the result.
508 unsigned
509 A15SDOptimizer::optimizeAllLanesPattern(MachineInstr *MI, unsigned Reg) {
510   MachineBasicBlock::iterator InsertPt(MI);
511   DebugLoc DL = MI->getDebugLoc();
512   MachineBasicBlock &MBB = *MI->getParent();
513   InsertPt++;
514   unsigned Out;
515
516   // DPair has the same length as QPR and also has two DPRs as subreg.
517   // Treat DPair as QPR.
518   if (MRI->getRegClass(Reg)->hasSuperClassEq(&ARM::QPRRegClass) ||
519       MRI->getRegClass(Reg)->hasSuperClassEq(&ARM::DPairRegClass)) {
520     unsigned DSub0 = createExtractSubreg(MBB, InsertPt, DL, Reg,
521                                          ARM::dsub_0, &ARM::DPRRegClass);
522     unsigned DSub1 = createExtractSubreg(MBB, InsertPt, DL, Reg,
523                                          ARM::dsub_1, &ARM::DPRRegClass);
524
525     unsigned Out1 = createDupLane(MBB, InsertPt, DL, DSub0, 0);
526     unsigned Out2 = createDupLane(MBB, InsertPt, DL, DSub0, 1);
527     Out = createVExt(MBB, InsertPt, DL, Out1, Out2);
528
529     unsigned Out3 = createDupLane(MBB, InsertPt, DL, DSub1, 0);
530     unsigned Out4 = createDupLane(MBB, InsertPt, DL, DSub1, 1);
531     Out2 = createVExt(MBB, InsertPt, DL, Out3, Out4);
532
533     Out = createRegSequence(MBB, InsertPt, DL, Out, Out2);
534
535   } else if (MRI->getRegClass(Reg)->hasSuperClassEq(&ARM::DPRRegClass)) {
536     unsigned Out1 = createDupLane(MBB, InsertPt, DL, Reg, 0);
537     unsigned Out2 = createDupLane(MBB, InsertPt, DL, Reg, 1);
538     Out = createVExt(MBB, InsertPt, DL, Out1, Out2);
539
540   } else {
541     assert(MRI->getRegClass(Reg)->hasSuperClassEq(&ARM::SPRRegClass) &&
542            "Found unexpected regclass!");
543
544     unsigned PrefLane = getPrefSPRLane(Reg);
545     unsigned Lane;
546     switch (PrefLane) {
547       case ARM::ssub_0: Lane = 0; break;
548       case ARM::ssub_1: Lane = 1; break;
549       default: llvm_unreachable("Unknown preferred lane!");
550     }
551
552     // Treat DPair as QPR
553     bool UsesQPR = usesRegClass(MI->getOperand(0), &ARM::QPRRegClass) ||
554                    usesRegClass(MI->getOperand(0), &ARM::DPairRegClass);
555
556     Out = createImplicitDef(MBB, InsertPt, DL);
557     Out = createInsertSubreg(MBB, InsertPt, DL, Out, PrefLane, Reg);
558     Out = createDupLane(MBB, InsertPt, DL, Out, Lane, UsesQPR);
559     eraseInstrWithNoUses(MI);
560   }
561   return Out;
562 }
563
564 bool A15SDOptimizer::runOnInstruction(MachineInstr *MI) {
565   // We look for instructions that write S registers that are then read as
566   // D/Q registers. These can only be caused by COPY, INSERT_SUBREG and
567   // REG_SEQUENCE pseudos that insert an SPR value into a DPR register or
568   // merge two SPR values to form a DPR register.  In order avoid false
569   // positives we make sure that there is an SPR producer so we look past
570   // COPY and PHI nodes to find it.
571   //
572   // The best code pattern for when an SPR producer is going to be used by a
573   // DPR or QPR consumer depends on whether the other lanes of the
574   // corresponding DPR/QPR are currently defined.
575   //
576   // We can handle these efficiently, depending on the type of
577   // pseudo-instruction that is producing the pattern
578   //
579   //   * COPY:          * VDUP all lanes and merge the results together
580   //                      using VEXTs.
581   //
582   //   * INSERT_SUBREG: * If the SPR value was originally in another DPR/QPR
583   //                      lane, and the other lane(s) of the DPR/QPR register
584   //                      that we are inserting in are undefined, use the
585   //                      original DPR/QPR value.
586   //                    * Otherwise, fall back on the same stategy as COPY.
587   //
588   //   * REG_SEQUENCE:  * If all except one of the input operands are
589   //                      IMPLICIT_DEFs, insert the VDUP pattern for just the
590   //                      defined input operand
591   //                    * Otherwise, fall back on the same stategy as COPY.
592   //
593
594   // First, get all the reads of D-registers done by this instruction.
595   SmallVector<unsigned, 8> Defs = getReadDPRs(MI);
596   bool Modified = false;
597
598   for (SmallVectorImpl<unsigned>::iterator I = Defs.begin(), E = Defs.end();
599      I != E; ++I) {
600     // Follow the def-use chain for this DPR through COPYs, and also through
601     // PHIs (which are essentially multi-way COPYs). It is because of PHIs that
602     // we can end up with multiple defs of this DPR.
603
604     SmallVector<MachineInstr *, 8> DefSrcs;
605     if (!TRI->isVirtualRegister(*I))
606       continue;
607     MachineInstr *Def = MRI->getVRegDef(*I);
608     if (!Def)
609       continue;
610
611     elideCopiesAndPHIs(Def, DefSrcs);
612
613     for (MachineInstr *MI : DefSrcs) {
614       // If we've already analyzed and replaced this operand, don't do
615       // anything.
616       if (Replacements.find(MI) != Replacements.end())
617         continue;
618
619       // Now, work out if the instruction causes a SPR->DPR dependency.
620       if (!hasPartialWrite(MI))
621         continue;
622
623       // Collect all the uses of this MI's DPR def for updating later.
624       SmallVector<MachineOperand*, 8> Uses;
625       unsigned DPRDefReg = MI->getOperand(0).getReg();
626       for (MachineRegisterInfo::use_iterator I = MRI->use_begin(DPRDefReg),
627              E = MRI->use_end(); I != E; ++I)
628         Uses.push_back(&*I);
629
630       // We can optimize this.
631       unsigned NewReg = optimizeSDPattern(MI);
632
633       if (NewReg != 0) {
634         Modified = true;
635         for (SmallVectorImpl<MachineOperand *>::const_iterator I = Uses.begin(),
636                E = Uses.end(); I != E; ++I) {
637           // Make sure to constrain the register class of the new register to
638           // match what we're replacing. Otherwise we can optimize a DPR_VFP2
639           // reference into a plain DPR, and that will end poorly. NewReg is
640           // always virtual here, so there will always be a matching subclass
641           // to find.
642           MRI->constrainRegClass(NewReg, MRI->getRegClass((*I)->getReg()));
643
644           LLVM_DEBUG(dbgs() << "Replacing operand " << **I << " with "
645                             << printReg(NewReg) << "\n");
646           (*I)->substVirtReg(NewReg, 0, *TRI);
647         }
648       }
649       Replacements[MI] = NewReg;
650     }
651   }
652   return Modified;
653 }
654
655 bool A15SDOptimizer::runOnMachineFunction(MachineFunction &Fn) {
656   if (skipFunction(Fn.getFunction()))
657     return false;
658
659   const ARMSubtarget &STI = Fn.getSubtarget<ARMSubtarget>();
660   // Since the A15SDOptimizer pass can insert VDUP instructions, it can only be
661   // enabled when NEON is available.
662   if (!(STI.useSplatVFPToNeon() && STI.hasNEON()))
663     return false;
664
665   TII = STI.getInstrInfo();
666   TRI = STI.getRegisterInfo();
667   MRI = &Fn.getRegInfo();
668   bool Modified = false;
669
670   LLVM_DEBUG(dbgs() << "Running on function " << Fn.getName() << "\n");
671
672   DeadInstr.clear();
673   Replacements.clear();
674
675   for (MachineBasicBlock &MBB : Fn) {
676     for (MachineInstr &MI : MBB) {
677       Modified |= runOnInstruction(&MI);
678     }
679   }
680
681   for (MachineInstr *MI : DeadInstr) {
682     MI->eraseFromParent();
683   }
684
685   return Modified;
686 }
687
688 FunctionPass *llvm::createA15SDOptimizerPass() {
689   return new A15SDOptimizer();
690 }