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