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