At -O0, multiple uses of a virtual registers in the same BB are being marked
[oota-llvm.git] / lib / CodeGen / TwoAddressInstructionPass.cpp
1 //===-- TwoAddressInstructionPass.cpp - Two-Address instruction pass ------===//
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 file implements the TwoAddress instruction pass which is used
11 // by most register allocators. Two-Address instructions are rewritten
12 // from:
13 //
14 //     A = B op C
15 //
16 // to:
17 //
18 //     A = B
19 //     A op= C
20 //
21 // Note that if a register allocator chooses to use this pass, that it
22 // has to be capable of handling the non-SSA nature of these rewritten
23 // virtual registers.
24 //
25 // It is also worth noting that the duplicate operand of the two
26 // address instruction is removed.
27 //
28 //===----------------------------------------------------------------------===//
29
30 #define DEBUG_TYPE "twoaddrinstr"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/Function.h"
33 #include "llvm/CodeGen/LiveVariables.h"
34 #include "llvm/CodeGen/MachineFunctionPass.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/Analysis/AliasAnalysis.h"
39 #include "llvm/MC/MCInstrItineraries.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/ADT/BitVector.h"
47 #include "llvm/ADT/DenseMap.h"
48 #include "llvm/ADT/SmallSet.h"
49 #include "llvm/ADT/Statistic.h"
50 #include "llvm/ADT/STLExtras.h"
51 using namespace llvm;
52
53 STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
54 STATISTIC(NumCommuted        , "Number of instructions commuted to coalesce");
55 STATISTIC(NumAggrCommuted    , "Number of instructions aggressively commuted");
56 STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
57 STATISTIC(Num3AddrSunk,        "Number of 3-address instructions sunk");
58 STATISTIC(NumReMats,           "Number of instructions re-materialized");
59 STATISTIC(NumDeletes,          "Number of dead instructions deleted");
60 STATISTIC(NumReSchedUps,       "Number of instructions re-scheduled up");
61 STATISTIC(NumReSchedDowns,     "Number of instructions re-scheduled down");
62
63 namespace {
64   class TwoAddressInstructionPass : public MachineFunctionPass {
65     const TargetInstrInfo *TII;
66     const TargetRegisterInfo *TRI;
67     const InstrItineraryData *InstrItins;
68     MachineRegisterInfo *MRI;
69     LiveVariables *LV;
70     AliasAnalysis *AA;
71
72     // DistanceMap - Keep track the distance of a MI from the start of the
73     // current basic block.
74     DenseMap<MachineInstr*, unsigned> DistanceMap;
75
76     // SrcRegMap - A map from virtual registers to physical registers which
77     // are likely targets to be coalesced to due to copies from physical
78     // registers to virtual registers. e.g. v1024 = move r0.
79     DenseMap<unsigned, unsigned> SrcRegMap;
80
81     // DstRegMap - A map from virtual registers to physical registers which
82     // are likely targets to be coalesced to due to copies to physical
83     // registers from virtual registers. e.g. r1 = move v1024.
84     DenseMap<unsigned, unsigned> DstRegMap;
85
86     /// RegSequences - Keep track the list of REG_SEQUENCE instructions seen
87     /// during the initial walk of the machine function.
88     SmallVector<MachineInstr*, 16> RegSequences;
89
90     bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
91                               unsigned Reg,
92                               MachineBasicBlock::iterator OldPos);
93
94     bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
95                              MachineInstr *MI, MachineInstr *DefMI,
96                              MachineBasicBlock *MBB, unsigned Loc);
97
98     bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
99                            unsigned &LastDef);
100
101     MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
102                                    unsigned Dist);
103
104     bool isProfitableToCommute(unsigned regB, unsigned regC,
105                                MachineInstr *MI, MachineBasicBlock *MBB,
106                                unsigned Dist);
107
108     bool CommuteInstruction(MachineBasicBlock::iterator &mi,
109                             MachineFunction::iterator &mbbi,
110                             unsigned RegB, unsigned RegC, unsigned Dist);
111
112     bool isProfitableToConv3Addr(unsigned RegA, unsigned RegB);
113
114     bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
115                             MachineBasicBlock::iterator &nmi,
116                             MachineFunction::iterator &mbbi,
117                             unsigned RegA, unsigned RegB, unsigned Dist);
118
119     typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
120     bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
121                                SmallVector<NewKill, 4> &NewKills,
122                                MachineBasicBlock *MBB, unsigned Dist);
123     bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
124                            MachineBasicBlock::iterator &nmi,
125                            MachineFunction::iterator &mbbi, unsigned Dist);
126
127     bool isDefTooClose(unsigned Reg, unsigned Dist,
128                        MachineInstr *MI, MachineBasicBlock *MBB);
129
130     bool RescheduleMIBelowKill(MachineBasicBlock *MBB,
131                                MachineBasicBlock::iterator &mi,
132                                MachineBasicBlock::iterator &nmi,
133                                unsigned Reg);
134     bool RescheduleKillAboveMI(MachineBasicBlock *MBB,
135                                MachineBasicBlock::iterator &mi,
136                                MachineBasicBlock::iterator &nmi,
137                                unsigned Reg);
138
139     bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
140                                  MachineBasicBlock::iterator &nmi,
141                                  MachineFunction::iterator &mbbi,
142                                  unsigned SrcIdx, unsigned DstIdx,
143                                  unsigned Dist,
144                                  SmallPtrSet<MachineInstr*, 8> &Processed);
145
146     void ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
147                   SmallPtrSet<MachineInstr*, 8> &Processed);
148
149     void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
150                      SmallPtrSet<MachineInstr*, 8> &Processed);
151
152     void CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs, unsigned DstReg);
153
154     /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
155     /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
156     /// sub-register references of the register defined by REG_SEQUENCE.
157     bool EliminateRegSequences();
158
159   public:
160     static char ID; // Pass identification, replacement for typeid
161     TwoAddressInstructionPass() : MachineFunctionPass(ID) {
162       initializeTwoAddressInstructionPassPass(*PassRegistry::getPassRegistry());
163     }
164
165     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
166       AU.setPreservesCFG();
167       AU.addRequired<AliasAnalysis>();
168       AU.addPreserved<LiveVariables>();
169       AU.addPreservedID(MachineLoopInfoID);
170       AU.addPreservedID(MachineDominatorsID);
171       AU.addPreservedID(PHIEliminationID);
172       MachineFunctionPass::getAnalysisUsage(AU);
173     }
174
175     /// runOnMachineFunction - Pass entry point.
176     bool runOnMachineFunction(MachineFunction&);
177   };
178 }
179
180 char TwoAddressInstructionPass::ID = 0;
181 INITIALIZE_PASS_BEGIN(TwoAddressInstructionPass, "twoaddressinstruction",
182                 "Two-Address instruction pass", false, false)
183 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
184 INITIALIZE_PASS_END(TwoAddressInstructionPass, "twoaddressinstruction",
185                 "Two-Address instruction pass", false, false)
186
187 char &llvm::TwoAddressInstructionPassID = TwoAddressInstructionPass::ID;
188
189 /// Sink3AddrInstruction - A two-address instruction has been converted to a
190 /// three-address instruction to avoid clobbering a register. Try to sink it
191 /// past the instruction that would kill the above mentioned register to reduce
192 /// register pressure.
193 bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
194                                            MachineInstr *MI, unsigned SavedReg,
195                                            MachineBasicBlock::iterator OldPos) {
196   // FIXME: Shouldn't we be trying to do this before we three-addressify the
197   // instruction?  After this transformation is done, we no longer need
198   // the instruction to be in three-address form.
199
200   // Check if it's safe to move this instruction.
201   bool SeenStore = true; // Be conservative.
202   if (!MI->isSafeToMove(TII, AA, SeenStore))
203     return false;
204
205   unsigned DefReg = 0;
206   SmallSet<unsigned, 4> UseRegs;
207
208   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
209     const MachineOperand &MO = MI->getOperand(i);
210     if (!MO.isReg())
211       continue;
212     unsigned MOReg = MO.getReg();
213     if (!MOReg)
214       continue;
215     if (MO.isUse() && MOReg != SavedReg)
216       UseRegs.insert(MO.getReg());
217     if (!MO.isDef())
218       continue;
219     if (MO.isImplicit())
220       // Don't try to move it if it implicitly defines a register.
221       return false;
222     if (DefReg)
223       // For now, don't move any instructions that define multiple registers.
224       return false;
225     DefReg = MO.getReg();
226   }
227
228   // Find the instruction that kills SavedReg.
229   MachineInstr *KillMI = NULL;
230   for (MachineRegisterInfo::use_nodbg_iterator
231          UI = MRI->use_nodbg_begin(SavedReg),
232          UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
233     MachineOperand &UseMO = UI.getOperand();
234     if (!UseMO.isKill())
235       continue;
236     KillMI = UseMO.getParent();
237     break;
238   }
239
240   // If we find the instruction that kills SavedReg, and it is in an
241   // appropriate location, we can try to sink the current instruction
242   // past it.
243   if (!KillMI || KillMI->getParent() != MBB || KillMI == MI ||
244       KillMI->getDesc().isTerminator())
245     return false;
246
247   // If any of the definitions are used by another instruction between the
248   // position and the kill use, then it's not safe to sink it.
249   // 
250   // FIXME: This can be sped up if there is an easy way to query whether an
251   // instruction is before or after another instruction. Then we can use
252   // MachineRegisterInfo def / use instead.
253   MachineOperand *KillMO = NULL;
254   MachineBasicBlock::iterator KillPos = KillMI;
255   ++KillPos;
256
257   unsigned NumVisited = 0;
258   for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
259     MachineInstr *OtherMI = I;
260     // DBG_VALUE cannot be counted against the limit.
261     if (OtherMI->isDebugValue())
262       continue;
263     if (NumVisited > 30)  // FIXME: Arbitrary limit to reduce compile time cost.
264       return false;
265     ++NumVisited;
266     for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
267       MachineOperand &MO = OtherMI->getOperand(i);
268       if (!MO.isReg())
269         continue;
270       unsigned MOReg = MO.getReg();
271       if (!MOReg)
272         continue;
273       if (DefReg == MOReg)
274         return false;
275
276       if (MO.isKill()) {
277         if (OtherMI == KillMI && MOReg == SavedReg)
278           // Save the operand that kills the register. We want to unset the kill
279           // marker if we can sink MI past it.
280           KillMO = &MO;
281         else if (UseRegs.count(MOReg))
282           // One of the uses is killed before the destination.
283           return false;
284       }
285     }
286   }
287
288   // Update kill and LV information.
289   KillMO->setIsKill(false);
290   KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
291   KillMO->setIsKill(true);
292   
293   if (LV)
294     LV->replaceKillInstruction(SavedReg, KillMI, MI);
295
296   // Move instruction to its destination.
297   MBB->remove(MI);
298   MBB->insert(KillPos, MI);
299
300   ++Num3AddrSunk;
301   return true;
302 }
303
304 /// isTwoAddrUse - Return true if the specified MI is using the specified
305 /// register as a two-address operand.
306 static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
307   const MCInstrDesc &MCID = UseMI->getDesc();
308   for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
309     MachineOperand &MO = UseMI->getOperand(i);
310     if (MO.isReg() && MO.getReg() == Reg &&
311         (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
312       // Earlier use is a two-address one.
313       return true;
314   }
315   return false;
316 }
317
318 /// isProfitableToReMat - Return true if the heuristics determines it is likely
319 /// to be profitable to re-materialize the definition of Reg rather than copy
320 /// the register.
321 bool
322 TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
323                                          const TargetRegisterClass *RC,
324                                          MachineInstr *MI, MachineInstr *DefMI,
325                                          MachineBasicBlock *MBB, unsigned Loc) {
326   bool OtherUse = false;
327   for (MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(Reg),
328          UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
329     MachineOperand &UseMO = UI.getOperand();
330     MachineInstr *UseMI = UseMO.getParent();
331     MachineBasicBlock *UseMBB = UseMI->getParent();
332     if (UseMBB == MBB) {
333       DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
334       if (DI != DistanceMap.end() && DI->second == Loc)
335         continue;  // Current use.
336       OtherUse = true;
337       // There is at least one other use in the MBB that will clobber the
338       // register. 
339       if (isTwoAddrUse(UseMI, Reg))
340         return true;
341     }
342   }
343
344   // If other uses in MBB are not two-address uses, then don't remat.
345   if (OtherUse)
346     return false;
347
348   // No other uses in the same block, remat if it's defined in the same
349   // block so it does not unnecessarily extend the live range.
350   return MBB == DefMI->getParent();
351 }
352
353 /// NoUseAfterLastDef - Return true if there are no intervening uses between the
354 /// last instruction in the MBB that defines the specified register and the
355 /// two-address instruction which is being processed. It also returns the last
356 /// def location by reference
357 bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
358                                            MachineBasicBlock *MBB, unsigned Dist,
359                                            unsigned &LastDef) {
360   LastDef = 0;
361   unsigned LastUse = Dist;
362   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
363          E = MRI->reg_end(); I != E; ++I) {
364     MachineOperand &MO = I.getOperand();
365     MachineInstr *MI = MO.getParent();
366     if (MI->getParent() != MBB || MI->isDebugValue())
367       continue;
368     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
369     if (DI == DistanceMap.end())
370       continue;
371     if (MO.isUse() && DI->second < LastUse)
372       LastUse = DI->second;
373     if (MO.isDef() && DI->second > LastDef)
374       LastDef = DI->second;
375   }
376
377   return !(LastUse > LastDef && LastUse < Dist);
378 }
379
380 MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
381                                                          MachineBasicBlock *MBB,
382                                                          unsigned Dist) {
383   unsigned LastUseDist = 0;
384   MachineInstr *LastUse = 0;
385   for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
386          E = MRI->reg_end(); I != E; ++I) {
387     MachineOperand &MO = I.getOperand();
388     MachineInstr *MI = MO.getParent();
389     if (MI->getParent() != MBB || MI->isDebugValue())
390       continue;
391     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
392     if (DI == DistanceMap.end())
393       continue;
394     if (DI->second >= Dist)
395       continue;
396
397     if (MO.isUse() && DI->second > LastUseDist) {
398       LastUse = DI->first;
399       LastUseDist = DI->second;
400     }
401   }
402   return LastUse;
403 }
404
405 /// isCopyToReg - Return true if the specified MI is a copy instruction or
406 /// a extract_subreg instruction. It also returns the source and destination
407 /// registers and whether they are physical registers by reference.
408 static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
409                         unsigned &SrcReg, unsigned &DstReg,
410                         bool &IsSrcPhys, bool &IsDstPhys) {
411   SrcReg = 0;
412   DstReg = 0;
413   if (MI.isCopy()) {
414     DstReg = MI.getOperand(0).getReg();
415     SrcReg = MI.getOperand(1).getReg();
416   } else if (MI.isInsertSubreg() || MI.isSubregToReg()) {
417     DstReg = MI.getOperand(0).getReg();
418     SrcReg = MI.getOperand(2).getReg();
419   } else
420     return false;
421
422   IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
423   IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
424   return true;
425 }
426
427 /// isKilled - Test if the given register value, which is used by the given
428 /// instruction, is killed by the given instruction. This looks through
429 /// coalescable copies to see if the original value is potentially not killed.
430 ///
431 /// For example, in this code:
432 ///
433 ///   %reg1034 = copy %reg1024
434 ///   %reg1035 = copy %reg1025<kill>
435 ///   %reg1036 = add %reg1034<kill>, %reg1035<kill>
436 ///
437 /// %reg1034 is not considered to be killed, since it is copied from a
438 /// register which is not killed. Treating it as not killed lets the
439 /// normal heuristics commute the (two-address) add, which lets
440 /// coalescing eliminate the extra copy.
441 ///
442 static bool isKilled(MachineInstr &MI, unsigned Reg,
443                      const MachineRegisterInfo *MRI,
444                      const TargetInstrInfo *TII) {
445   MachineInstr *DefMI = &MI;
446   for (;;) {
447     if (!DefMI->killsRegister(Reg))
448       return false;
449     if (TargetRegisterInfo::isPhysicalRegister(Reg))
450       return true;
451     MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
452     // If there are multiple defs, we can't do a simple analysis, so just
453     // go with what the kill flag says.
454     if (llvm::next(Begin) != MRI->def_end())
455       return true;
456     DefMI = &*Begin;
457     bool IsSrcPhys, IsDstPhys;
458     unsigned SrcReg,  DstReg;
459     // If the def is something other than a copy, then it isn't going to
460     // be coalesced, so follow the kill flag.
461     if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
462       return true;
463     Reg = SrcReg;
464   }
465 }
466
467 /// isTwoAddrUse - Return true if the specified MI uses the specified register
468 /// as a two-address use. If so, return the destination register by reference.
469 static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
470   const MCInstrDesc &MCID = MI.getDesc();
471   unsigned NumOps = MI.isInlineAsm()
472     ? MI.getNumOperands() : MCID.getNumOperands();
473   for (unsigned i = 0; i != NumOps; ++i) {
474     const MachineOperand &MO = MI.getOperand(i);
475     if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
476       continue;
477     unsigned ti;
478     if (MI.isRegTiedToDefOperand(i, &ti)) {
479       DstReg = MI.getOperand(ti).getReg();
480       return true;
481     }
482   }
483   return false;
484 }
485
486 /// findLocalKill - Look for an instruction below MI in the MBB that kills the
487 /// specified register. Returns null if there are any other Reg use between the
488 /// instructions.
489 static
490 MachineInstr *findLocalKill(unsigned Reg, MachineBasicBlock *MBB,
491                             MachineInstr *MI, MachineRegisterInfo *MRI,
492                             DenseMap<MachineInstr*, unsigned> &DistanceMap) {
493   MachineInstr *KillMI = 0;
494   for (MachineRegisterInfo::use_nodbg_iterator
495          UI = MRI->use_nodbg_begin(Reg),
496          UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
497     MachineInstr *UseMI = &*UI;
498     if (UseMI == MI || UseMI->getParent() != MBB)
499       continue;
500     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
501     if (DI != DistanceMap.end())
502       continue;
503     if (!UI.getOperand().isKill())
504       return 0;
505     if (KillMI)
506       return 0;  // -O0 kill markers cannot be trusted?
507     KillMI = UseMI;
508   }
509
510   return KillMI;
511 }
512
513 /// findOnlyInterestingUse - Given a register, if has a single in-basic block
514 /// use, return the use instruction if it's a copy or a two-address use.
515 static
516 MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
517                                      MachineRegisterInfo *MRI,
518                                      const TargetInstrInfo *TII,
519                                      bool &IsCopy,
520                                      unsigned &DstReg, bool &IsDstPhys) {
521   if (!MRI->hasOneNonDBGUse(Reg))
522     // None or more than one use.
523     return 0;
524   MachineInstr &UseMI = *MRI->use_nodbg_begin(Reg);
525   if (UseMI.getParent() != MBB)
526     return 0;
527   unsigned SrcReg;
528   bool IsSrcPhys;
529   if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
530     IsCopy = true;
531     return &UseMI;
532   }
533   IsDstPhys = false;
534   if (isTwoAddrUse(UseMI, Reg, DstReg)) {
535     IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
536     return &UseMI;
537   }
538   return 0;
539 }
540
541 /// getMappedReg - Return the physical register the specified virtual register
542 /// might be mapped to.
543 static unsigned
544 getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
545   while (TargetRegisterInfo::isVirtualRegister(Reg))  {
546     DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
547     if (SI == RegMap.end())
548       return 0;
549     Reg = SI->second;
550   }
551   if (TargetRegisterInfo::isPhysicalRegister(Reg))
552     return Reg;
553   return 0;
554 }
555
556 /// regsAreCompatible - Return true if the two registers are equal or aliased.
557 ///
558 static bool
559 regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
560   if (RegA == RegB)
561     return true;
562   if (!RegA || !RegB)
563     return false;
564   return TRI->regsOverlap(RegA, RegB);
565 }
566
567
568 /// isProfitableToReMat - Return true if it's potentially profitable to commute
569 /// the two-address instruction that's being processed.
570 bool
571 TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
572                                        MachineInstr *MI, MachineBasicBlock *MBB,
573                                        unsigned Dist) {
574   // Determine if it's profitable to commute this two address instruction. In
575   // general, we want no uses between this instruction and the definition of
576   // the two-address register.
577   // e.g.
578   // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
579   // %reg1029<def> = MOV8rr %reg1028
580   // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
581   // insert => %reg1030<def> = MOV8rr %reg1028
582   // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
583   // In this case, it might not be possible to coalesce the second MOV8rr
584   // instruction if the first one is coalesced. So it would be profitable to
585   // commute it:
586   // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
587   // %reg1029<def> = MOV8rr %reg1028
588   // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
589   // insert => %reg1030<def> = MOV8rr %reg1029
590   // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>  
591
592   if (!MI->killsRegister(regC))
593     return false;
594
595   // Ok, we have something like:
596   // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
597   // let's see if it's worth commuting it.
598
599   // Look for situations like this:
600   // %reg1024<def> = MOV r1
601   // %reg1025<def> = MOV r0
602   // %reg1026<def> = ADD %reg1024, %reg1025
603   // r0            = MOV %reg1026
604   // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
605   unsigned FromRegB = getMappedReg(regB, SrcRegMap);
606   unsigned FromRegC = getMappedReg(regC, SrcRegMap);
607   unsigned ToRegB = getMappedReg(regB, DstRegMap);
608   unsigned ToRegC = getMappedReg(regC, DstRegMap);
609   if ((FromRegB && ToRegB && !regsAreCompatible(FromRegB, ToRegB, TRI)) &&
610       ((!FromRegC && !ToRegC) ||
611        regsAreCompatible(FromRegB, ToRegC, TRI) ||
612        regsAreCompatible(FromRegC, ToRegB, TRI)))
613     return true;
614
615   // If there is a use of regC between its last def (could be livein) and this
616   // instruction, then bail.
617   unsigned LastDefC = 0;
618   if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
619     return false;
620
621   // If there is a use of regB between its last def (could be livein) and this
622   // instruction, then go ahead and make this transformation.
623   unsigned LastDefB = 0;
624   if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
625     return true;
626
627   // Since there are no intervening uses for both registers, then commute
628   // if the def of regC is closer. Its live interval is shorter.
629   return LastDefB && LastDefC && LastDefC > LastDefB;
630 }
631
632 /// CommuteInstruction - Commute a two-address instruction and update the basic
633 /// block, distance map, and live variables if needed. Return true if it is
634 /// successful.
635 bool
636 TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
637                                MachineFunction::iterator &mbbi,
638                                unsigned RegB, unsigned RegC, unsigned Dist) {
639   MachineInstr *MI = mi;
640   DEBUG(dbgs() << "2addr: COMMUTING  : " << *MI);
641   MachineInstr *NewMI = TII->commuteInstruction(MI);
642
643   if (NewMI == 0) {
644     DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
645     return false;
646   }
647
648   DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
649   // If the instruction changed to commute it, update livevar.
650   if (NewMI != MI) {
651     if (LV)
652       // Update live variables
653       LV->replaceKillInstruction(RegC, MI, NewMI);
654
655     mbbi->insert(mi, NewMI);           // Insert the new inst
656     mbbi->erase(mi);                   // Nuke the old inst.
657     mi = NewMI;
658     DistanceMap.insert(std::make_pair(NewMI, Dist));
659   }
660
661   // Update source register map.
662   unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
663   if (FromRegC) {
664     unsigned RegA = MI->getOperand(0).getReg();
665     SrcRegMap[RegA] = FromRegC;
666   }
667
668   return true;
669 }
670
671 /// isProfitableToConv3Addr - Return true if it is profitable to convert the
672 /// given 2-address instruction to a 3-address one.
673 bool
674 TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA,unsigned RegB){
675   // Look for situations like this:
676   // %reg1024<def> = MOV r1
677   // %reg1025<def> = MOV r0
678   // %reg1026<def> = ADD %reg1024, %reg1025
679   // r2            = MOV %reg1026
680   // Turn ADD into a 3-address instruction to avoid a copy.
681   unsigned FromRegB = getMappedReg(RegB, SrcRegMap);
682   if (!FromRegB)
683     return false;
684   unsigned ToRegA = getMappedReg(RegA, DstRegMap);
685   return (ToRegA && !regsAreCompatible(FromRegB, ToRegA, TRI));
686 }
687
688 /// ConvertInstTo3Addr - Convert the specified two-address instruction into a
689 /// three address one. Return true if this transformation was successful.
690 bool
691 TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
692                                               MachineBasicBlock::iterator &nmi,
693                                               MachineFunction::iterator &mbbi,
694                                               unsigned RegA, unsigned RegB,
695                                               unsigned Dist) {
696   MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
697   if (NewMI) {
698     DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
699     DEBUG(dbgs() << "2addr:         TO 3-ADDR: " << *NewMI);
700     bool Sunk = false;
701
702     if (NewMI->findRegisterUseOperand(RegB, false, TRI))
703       // FIXME: Temporary workaround. If the new instruction doesn't
704       // uses RegB, convertToThreeAddress must have created more
705       // then one instruction.
706       Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
707
708     mbbi->erase(mi); // Nuke the old inst.
709
710     if (!Sunk) {
711       DistanceMap.insert(std::make_pair(NewMI, Dist));
712       mi = NewMI;
713       nmi = llvm::next(mi);
714     }
715
716     // Update source and destination register maps.
717     SrcRegMap.erase(RegA);
718     DstRegMap.erase(RegB);
719     return true;
720   }
721
722   return false;
723 }
724
725 /// ScanUses - Scan forward recursively for only uses, update maps if the use
726 /// is a copy or a two-address instruction.
727 void
728 TwoAddressInstructionPass::ScanUses(unsigned DstReg, MachineBasicBlock *MBB,
729                                     SmallPtrSet<MachineInstr*, 8> &Processed) {
730   SmallVector<unsigned, 4> VirtRegPairs;
731   bool IsDstPhys;
732   bool IsCopy = false;
733   unsigned NewReg = 0;
734   unsigned Reg = DstReg;
735   while (MachineInstr *UseMI = findOnlyInterestingUse(Reg, MBB, MRI, TII,IsCopy,
736                                                       NewReg, IsDstPhys)) {
737     if (IsCopy && !Processed.insert(UseMI))
738       break;
739
740     DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
741     if (DI != DistanceMap.end())
742       // Earlier in the same MBB.Reached via a back edge.
743       break;
744
745     if (IsDstPhys) {
746       VirtRegPairs.push_back(NewReg);
747       break;
748     }
749     bool isNew = SrcRegMap.insert(std::make_pair(NewReg, Reg)).second;
750     if (!isNew)
751       assert(SrcRegMap[NewReg] == Reg && "Can't map to two src registers!");
752     VirtRegPairs.push_back(NewReg);
753     Reg = NewReg;
754   }
755
756   if (!VirtRegPairs.empty()) {
757     unsigned ToReg = VirtRegPairs.back();
758     VirtRegPairs.pop_back();
759     while (!VirtRegPairs.empty()) {
760       unsigned FromReg = VirtRegPairs.back();
761       VirtRegPairs.pop_back();
762       bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
763       if (!isNew)
764         assert(DstRegMap[FromReg] == ToReg &&"Can't map to two dst registers!");
765       ToReg = FromReg;
766     }
767     bool isNew = DstRegMap.insert(std::make_pair(DstReg, ToReg)).second;
768     if (!isNew)
769       assert(DstRegMap[DstReg] == ToReg && "Can't map to two dst registers!");
770   }
771 }
772
773 /// ProcessCopy - If the specified instruction is not yet processed, process it
774 /// if it's a copy. For a copy instruction, we find the physical registers the
775 /// source and destination registers might be mapped to. These are kept in
776 /// point-to maps used to determine future optimizations. e.g.
777 /// v1024 = mov r0
778 /// v1025 = mov r1
779 /// v1026 = add v1024, v1025
780 /// r1    = mov r1026
781 /// If 'add' is a two-address instruction, v1024, v1026 are both potentially
782 /// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
783 /// potentially joined with r1 on the output side. It's worthwhile to commute
784 /// 'add' to eliminate a copy.
785 void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
786                                      MachineBasicBlock *MBB,
787                                      SmallPtrSet<MachineInstr*, 8> &Processed) {
788   if (Processed.count(MI))
789     return;
790
791   bool IsSrcPhys, IsDstPhys;
792   unsigned SrcReg, DstReg;
793   if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
794     return;
795
796   if (IsDstPhys && !IsSrcPhys)
797     DstRegMap.insert(std::make_pair(SrcReg, DstReg));
798   else if (!IsDstPhys && IsSrcPhys) {
799     bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
800     if (!isNew)
801       assert(SrcRegMap[DstReg] == SrcReg &&
802              "Can't map to two src physical registers!");
803
804     ScanUses(DstReg, MBB, Processed);
805   }
806
807   Processed.insert(MI);
808   return;
809 }
810
811 /// isSafeToDelete - If the specified instruction does not produce any side
812 /// effects and all of its defs are dead, then it's safe to delete.
813 static bool isSafeToDelete(MachineInstr *MI,
814                            const TargetInstrInfo *TII,
815                            SmallVector<unsigned, 4> &Kills) {
816   const MCInstrDesc &MCID = MI->getDesc();
817   if (MCID.mayStore() || MCID.isCall())
818     return false;
819   if (MCID.isTerminator() || MI->hasUnmodeledSideEffects())
820     return false;
821
822   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
823     MachineOperand &MO = MI->getOperand(i);
824     if (!MO.isReg())
825       continue;
826     if (MO.isDef() && !MO.isDead())
827       return false;
828     if (MO.isUse() && MO.isKill())
829       Kills.push_back(MO.getReg());
830   }
831   return true;
832 }
833
834 /// canUpdateDeletedKills - Check if all the registers listed in Kills are
835 /// killed by instructions in MBB preceding the current instruction at
836 /// position Dist.  If so, return true and record information about the
837 /// preceding kills in NewKills.
838 bool TwoAddressInstructionPass::
839 canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
840                       SmallVector<NewKill, 4> &NewKills,
841                       MachineBasicBlock *MBB, unsigned Dist) {
842   while (!Kills.empty()) {
843     unsigned Kill = Kills.back();
844     Kills.pop_back();
845     if (TargetRegisterInfo::isPhysicalRegister(Kill))
846       return false;
847
848     MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
849     if (!LastKill)
850       return false;
851
852     bool isModRef = LastKill->definesRegister(Kill);
853     NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
854                                       LastKill));
855   }
856   return true;
857 }
858
859 /// DeleteUnusedInstr - If an instruction with a tied register operand can
860 /// be safely deleted, just delete it.
861 bool
862 TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
863                                              MachineBasicBlock::iterator &nmi,
864                                              MachineFunction::iterator &mbbi,
865                                              unsigned Dist) {
866   // Check if the instruction has no side effects and if all its defs are dead.
867   SmallVector<unsigned, 4> Kills;
868   if (!isSafeToDelete(mi, TII, Kills))
869     return false;
870
871   // If this instruction kills some virtual registers, we need to
872   // update the kill information. If it's not possible to do so,
873   // then bail out.
874   SmallVector<NewKill, 4> NewKills;
875   if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
876     return false;
877
878   if (LV) {
879     while (!NewKills.empty()) {
880       MachineInstr *NewKill = NewKills.back().second;
881       unsigned Kill = NewKills.back().first.first;
882       bool isDead = NewKills.back().first.second;
883       NewKills.pop_back();
884       if (LV->removeVirtualRegisterKilled(Kill, mi)) {
885         if (isDead)
886           LV->addVirtualRegisterDead(Kill, NewKill);
887         else
888           LV->addVirtualRegisterKilled(Kill, NewKill);
889       }
890     }
891   }
892
893   mbbi->erase(mi); // Nuke the old inst.
894   mi = nmi;
895   return true;
896 }
897
898 /// RescheduleMIBelowKill - If there is one more local instruction that reads
899 /// 'Reg' and it kills 'Reg, consider moving the instruction below the kill
900 /// instruction in order to eliminate the need for the copy.
901 bool
902 TwoAddressInstructionPass::RescheduleMIBelowKill(MachineBasicBlock *MBB,
903                                      MachineBasicBlock::iterator &mi,
904                                      MachineBasicBlock::iterator &nmi,
905                                      unsigned Reg) {
906   MachineInstr *MI = &*mi;
907   DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI); 
908   if (DI == DistanceMap.end())
909     // Must be created from unfolded load. Don't waste time trying this.
910     return false;
911
912   MachineInstr *KillMI = findLocalKill(Reg, MBB, mi, MRI, DistanceMap);
913   if (!KillMI || KillMI->isCopy() || KillMI->isCopyLike())
914     // Don't mess with copies, they may be coalesced later.
915     return false;
916
917   const MCInstrDesc &MCID = KillMI->getDesc();
918   if (MCID.hasUnmodeledSideEffects() || MCID.isCall() || MCID.isBranch() ||
919       MCID.isTerminator())
920     // Don't move pass calls, etc.
921     return false;
922
923   unsigned DstReg;
924   if (isTwoAddrUse(*KillMI, Reg, DstReg))
925     return false;
926
927   bool SeenStore;
928   if (!MI->isSafeToMove(TII, AA, SeenStore))
929     return false;
930
931   if (TII->getInstrLatency(InstrItins, MI) > 1)
932     // FIXME: Needs more sophisticated heuristics.
933     return false;
934
935   SmallSet<unsigned, 2> Uses;
936   SmallSet<unsigned, 2> Defs;
937   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
938     const MachineOperand &MO = MI->getOperand(i);
939     if (!MO.isReg())
940       continue;
941     unsigned MOReg = MO.getReg();
942     if (!MOReg)
943       continue;
944     if (MO.isDef())
945       Defs.insert(MOReg);
946     else
947       Uses.insert(MOReg);
948   }
949
950   // Move the copies connected to MI down as well.
951   MachineBasicBlock::iterator From = MI;
952   MachineBasicBlock::iterator To = llvm::next(From);
953   while (To->isCopy() && Defs.count(To->getOperand(1).getReg())) {
954     Defs.insert(To->getOperand(0).getReg());
955     ++To;
956   }
957
958   // Check if the reschedule will not break depedencies.
959   unsigned NumVisited = 0;
960   MachineBasicBlock::iterator KillPos = KillMI;
961   ++KillPos;
962   for (MachineBasicBlock::iterator I = To; I != KillPos; ++I) {
963     MachineInstr *OtherMI = I;
964     // DBG_VALUE cannot be counted against the limit.
965     if (OtherMI->isDebugValue())
966       continue;
967     if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
968       return false;
969     ++NumVisited;
970     const MCInstrDesc &OMCID = OtherMI->getDesc();
971     if (OMCID.hasUnmodeledSideEffects() || OMCID.isCall() || OMCID.isBranch() ||
972         OMCID.isTerminator())
973       // Don't move pass calls, etc.
974       return false;
975     for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
976       const MachineOperand &MO = OtherMI->getOperand(i);
977       if (!MO.isReg())
978         continue;
979       unsigned MOReg = MO.getReg();
980       if (!MOReg)
981         continue;
982       if (MO.isDef()) {
983         if (Uses.count(MOReg))
984           // Physical register use would be clobbered.
985           return false;
986         if (!MO.isDead() && Defs.count(MOReg))
987           // May clobber a physical register def.
988           // FIXME: This may be too conservative. It's ok if the instruction
989           // is sunken completely below the use.
990           return false;
991       } else {
992         if (Defs.count(MOReg))
993           return false;
994         if (MOReg != Reg && MO.isKill() && Uses.count(MOReg))
995           // Don't want to extend other live ranges and update kills.
996           return false;
997       }
998     }
999   }
1000
1001   // Move debug info as well.
1002   if (From != MBB->begin()) {
1003     while (llvm::prior(From)->isDebugValue())
1004       --From;
1005   }
1006
1007   // Copies following MI may have been moved as well.
1008   nmi = To;
1009   MBB->splice(KillPos, MBB, From, To);
1010   DistanceMap.erase(DI);
1011
1012   if (LV) {
1013     // Update live variables
1014     LV->removeVirtualRegisterKilled(Reg, KillMI);
1015     LV->addVirtualRegisterKilled(Reg, MI);
1016   } else {
1017     for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1018       MachineOperand &MO = KillMI->getOperand(i);
1019       if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
1020         continue;
1021       MO.setIsKill(false);
1022     }
1023     MI->addRegisterKilled(Reg, 0);
1024   }
1025
1026   return true;
1027 }
1028
1029 /// isDefTooClose - Return true if the re-scheduling will put the given
1030 /// instruction too close to the defs of its register dependencies.
1031 bool TwoAddressInstructionPass::isDefTooClose(unsigned Reg, unsigned Dist,
1032                                               MachineInstr *MI,
1033                                               MachineBasicBlock *MBB) {
1034   for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(Reg),
1035          DE = MRI->def_end(); DI != DE; ++DI) {
1036     MachineInstr *DefMI = &*DI;
1037     if (DefMI->getParent() != MBB || DefMI->isCopy() || DefMI->isCopyLike())
1038       continue;
1039     if (DefMI == MI)
1040       return true; // MI is defining something KillMI uses
1041     DenseMap<MachineInstr*, unsigned>::iterator DDI = DistanceMap.find(DefMI);
1042     if (DDI == DistanceMap.end())
1043       return true;  // Below MI
1044     unsigned DefDist = DDI->second;
1045     assert(Dist > DefDist && "Visited def already?");
1046     if (TII->getInstrLatency(InstrItins, DefMI) > (int)(Dist - DefDist))
1047       return true;
1048   }
1049   return false;
1050 }
1051
1052 /// RescheduleKillAboveMI - If there is one more local instruction that reads
1053 /// 'Reg' and it kills 'Reg, consider moving the kill instruction above the
1054 /// current two-address instruction in order to eliminate the need for the
1055 /// copy.
1056 bool
1057 TwoAddressInstructionPass::RescheduleKillAboveMI(MachineBasicBlock *MBB,
1058                                      MachineBasicBlock::iterator &mi,
1059                                      MachineBasicBlock::iterator &nmi,
1060                                      unsigned Reg) {
1061   MachineInstr *MI = &*mi;
1062   DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
1063   if (DI == DistanceMap.end())
1064     // Must be created from unfolded load. Don't waste time trying this.
1065     return false;
1066
1067   MachineInstr *KillMI = findLocalKill(Reg, MBB, mi, MRI, DistanceMap);
1068   if (!KillMI || KillMI->isCopy() || KillMI->isCopyLike())
1069     // Don't mess with copies, they may be coalesced later.
1070     return false;
1071
1072   unsigned DstReg;
1073   if (isTwoAddrUse(*KillMI, Reg, DstReg))
1074     return false;
1075
1076   bool SeenStore;
1077   if (!KillMI->isSafeToMove(TII, AA, SeenStore))
1078     return false;
1079
1080   SmallSet<unsigned, 2> Uses;
1081   SmallSet<unsigned, 2> Kills;
1082   SmallSet<unsigned, 2> Defs;
1083   SmallSet<unsigned, 2> LiveDefs;
1084   for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1085     const MachineOperand &MO = KillMI->getOperand(i);
1086     if (!MO.isReg())
1087       continue;
1088     unsigned MOReg = MO.getReg();
1089     if (MO.isUse()) {
1090       if (!MOReg)
1091         continue;
1092       if (isDefTooClose(MOReg, DI->second, MI, MBB))
1093         return false;
1094       Uses.insert(MOReg);
1095       if (MO.isKill() && MOReg != Reg)
1096         Kills.insert(MOReg);
1097     } else if (TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1098       Defs.insert(MOReg);
1099       if (!MO.isDead())
1100         LiveDefs.insert(MOReg);
1101     }
1102   }
1103
1104   // Check if the reschedule will not break depedencies.
1105   unsigned NumVisited = 0;
1106   MachineBasicBlock::iterator KillPos = KillMI;
1107   for (MachineBasicBlock::iterator I = mi; I != KillPos; ++I) {
1108     MachineInstr *OtherMI = I;
1109     // DBG_VALUE cannot be counted against the limit.
1110     if (OtherMI->isDebugValue())
1111       continue;
1112     if (NumVisited > 10)  // FIXME: Arbitrary limit to reduce compile time cost.
1113       return false;
1114     ++NumVisited;
1115     const MCInstrDesc &MCID = OtherMI->getDesc();
1116     if (MCID.hasUnmodeledSideEffects() || MCID.isCall() || MCID.isBranch() ||
1117         MCID.isTerminator())
1118       // Don't move pass calls, etc.
1119       return false;
1120     for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
1121       const MachineOperand &MO = OtherMI->getOperand(i);
1122       if (!MO.isReg())
1123         continue;
1124       unsigned MOReg = MO.getReg();
1125       if (!MOReg)
1126         continue;
1127       if (MO.isUse()) {
1128         if (Defs.count(MOReg))
1129           // Moving KillMI can clobber the physical register if the def has
1130           // not been seen.
1131           return false;
1132         if (Kills.count(MOReg))
1133           // Don't want to extend other live ranges and update kills.
1134           return false;
1135       } else {
1136         if (Uses.count(MOReg))
1137           return false;
1138         if (TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1139             LiveDefs.count(MOReg))
1140           return false;
1141         // Physical register def is seen.
1142         Defs.erase(MOReg);
1143       }
1144     }
1145   }
1146
1147   // Move the old kill above MI, don't forget to move debug info as well.
1148   MachineBasicBlock::iterator InsertPos = mi;
1149   if (InsertPos != MBB->begin())
1150     while (llvm::prior(InsertPos)->isDebugValue())
1151       --InsertPos;
1152   MachineBasicBlock::iterator From = KillMI;
1153   MachineBasicBlock::iterator To = llvm::next(From);
1154   while (llvm::prior(From)->isDebugValue())
1155     --From;
1156   MBB->splice(InsertPos, MBB, From, To);
1157
1158   nmi = llvm::prior(mi); // Backtrack so we process the moved instruction.
1159   DistanceMap.erase(DI);
1160
1161   if (LV) {
1162     // Update live variables
1163     LV->removeVirtualRegisterKilled(Reg, KillMI);
1164     LV->addVirtualRegisterKilled(Reg, MI);
1165   } else {
1166     for (unsigned i = 0, e = KillMI->getNumOperands(); i != e; ++i) {
1167       MachineOperand &MO = KillMI->getOperand(i);
1168       if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
1169         continue;
1170       MO.setIsKill(false);
1171     }
1172     MI->addRegisterKilled(Reg, 0);
1173   }
1174   return true;
1175 }
1176
1177 /// TryInstructionTransform - For the case where an instruction has a single
1178 /// pair of tied register operands, attempt some transformations that may
1179 /// either eliminate the tied operands or improve the opportunities for
1180 /// coalescing away the register copy.  Returns true if the tied operands
1181 /// are eliminated altogether.
1182 bool TwoAddressInstructionPass::
1183 TryInstructionTransform(MachineBasicBlock::iterator &mi,
1184                         MachineBasicBlock::iterator &nmi,
1185                         MachineFunction::iterator &mbbi,
1186                         unsigned SrcIdx, unsigned DstIdx, unsigned Dist,
1187                         SmallPtrSet<MachineInstr*, 8> &Processed) {
1188   MachineInstr &MI = *mi;
1189   const MCInstrDesc &MCID = MI.getDesc();
1190   unsigned regA = MI.getOperand(DstIdx).getReg();
1191   unsigned regB = MI.getOperand(SrcIdx).getReg();
1192
1193   assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1194          "cannot make instruction into two-address form");
1195
1196   // If regA is dead and the instruction can be deleted, just delete
1197   // it so it doesn't clobber regB.
1198   bool regBKilled = isKilled(MI, regB, MRI, TII);
1199   if (!regBKilled && MI.getOperand(DstIdx).isDead() &&
1200       DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
1201     ++NumDeletes;
1202     return true; // Done with this instruction.
1203   }
1204
1205   // Check if it is profitable to commute the operands.
1206   unsigned SrcOp1, SrcOp2;
1207   unsigned regC = 0;
1208   unsigned regCIdx = ~0U;
1209   bool TryCommute = false;
1210   bool AggressiveCommute = false;
1211   if (MCID.isCommutable() && MI.getNumOperands() >= 3 &&
1212       TII->findCommutedOpIndices(&MI, SrcOp1, SrcOp2)) {
1213     if (SrcIdx == SrcOp1)
1214       regCIdx = SrcOp2;
1215     else if (SrcIdx == SrcOp2)
1216       regCIdx = SrcOp1;
1217
1218     if (regCIdx != ~0U) {
1219       regC = MI.getOperand(regCIdx).getReg();
1220       if (!regBKilled && isKilled(MI, regC, MRI, TII))
1221         // If C dies but B does not, swap the B and C operands.
1222         // This makes the live ranges of A and C joinable.
1223         TryCommute = true;
1224       else if (isProfitableToCommute(regB, regC, &MI, mbbi, Dist)) {
1225         TryCommute = true;
1226         AggressiveCommute = true;
1227       }
1228     }
1229   }
1230
1231   // If it's profitable to commute, try to do so.
1232   if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
1233     ++NumCommuted;
1234     if (AggressiveCommute)
1235       ++NumAggrCommuted;
1236     return false;
1237   }
1238
1239   // If there is one more use of regB later in the same MBB, consider
1240   // re-schedule this MI below it.
1241   if (RescheduleMIBelowKill(mbbi, mi, nmi, regB)) {
1242     ++NumReSchedDowns;
1243     return true;
1244   }
1245
1246   if (TargetRegisterInfo::isVirtualRegister(regA))
1247     ScanUses(regA, &*mbbi, Processed);
1248
1249   if (MCID.isConvertibleTo3Addr()) {
1250     // This instruction is potentially convertible to a true
1251     // three-address instruction.  Check if it is profitable.
1252     if (!regBKilled || isProfitableToConv3Addr(regA, regB)) {
1253       // Try to convert it.
1254       if (ConvertInstTo3Addr(mi, nmi, mbbi, regA, regB, Dist)) {
1255         ++NumConvertedTo3Addr;
1256         return true; // Done with this instruction.
1257       }
1258     }
1259   }
1260
1261   // If there is one more use of regB later in the same MBB, consider
1262   // re-schedule it before this MI if it's legal.
1263   if (RescheduleKillAboveMI(mbbi, mi, nmi, regB)) {
1264     ++NumReSchedUps;
1265     return true;
1266   }
1267
1268   // If this is an instruction with a load folded into it, try unfolding
1269   // the load, e.g. avoid this:
1270   //   movq %rdx, %rcx
1271   //   addq (%rax), %rcx
1272   // in favor of this:
1273   //   movq (%rax), %rcx
1274   //   addq %rdx, %rcx
1275   // because it's preferable to schedule a load than a register copy.
1276   if (MCID.mayLoad() && !regBKilled) {
1277     // Determine if a load can be unfolded.
1278     unsigned LoadRegIndex;
1279     unsigned NewOpc =
1280       TII->getOpcodeAfterMemoryUnfold(MI.getOpcode(),
1281                                       /*UnfoldLoad=*/true,
1282                                       /*UnfoldStore=*/false,
1283                                       &LoadRegIndex);
1284     if (NewOpc != 0) {
1285       const MCInstrDesc &UnfoldMCID = TII->get(NewOpc);
1286       if (UnfoldMCID.getNumDefs() == 1) {
1287         MachineFunction &MF = *mbbi->getParent();
1288
1289         // Unfold the load.
1290         DEBUG(dbgs() << "2addr:   UNFOLDING: " << MI);
1291         const TargetRegisterClass *RC =
1292           TII->getRegClass(UnfoldMCID, LoadRegIndex, TRI);
1293         unsigned Reg = MRI->createVirtualRegister(RC);
1294         SmallVector<MachineInstr *, 2> NewMIs;
1295         if (!TII->unfoldMemoryOperand(MF, &MI, Reg,
1296                                       /*UnfoldLoad=*/true,/*UnfoldStore=*/false,
1297                                       NewMIs)) {
1298           DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1299           return false;
1300         }
1301         assert(NewMIs.size() == 2 &&
1302                "Unfolded a load into multiple instructions!");
1303         // The load was previously folded, so this is the only use.
1304         NewMIs[1]->addRegisterKilled(Reg, TRI);
1305
1306         // Tentatively insert the instructions into the block so that they
1307         // look "normal" to the transformation logic.
1308         mbbi->insert(mi, NewMIs[0]);
1309         mbbi->insert(mi, NewMIs[1]);
1310
1311         DEBUG(dbgs() << "2addr:    NEW LOAD: " << *NewMIs[0]
1312                      << "2addr:    NEW INST: " << *NewMIs[1]);
1313
1314         // Transform the instruction, now that it no longer has a load.
1315         unsigned NewDstIdx = NewMIs[1]->findRegisterDefOperandIdx(regA);
1316         unsigned NewSrcIdx = NewMIs[1]->findRegisterUseOperandIdx(regB);
1317         MachineBasicBlock::iterator NewMI = NewMIs[1];
1318         bool TransformSuccess =
1319           TryInstructionTransform(NewMI, mi, mbbi,
1320                                   NewSrcIdx, NewDstIdx, Dist, Processed);
1321         if (TransformSuccess ||
1322             NewMIs[1]->getOperand(NewSrcIdx).isKill()) {
1323           // Success, or at least we made an improvement. Keep the unfolded
1324           // instructions and discard the original.
1325           if (LV) {
1326             for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1327               MachineOperand &MO = MI.getOperand(i);
1328               if (MO.isReg() && 
1329                   TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
1330                 if (MO.isUse()) {
1331                   if (MO.isKill()) {
1332                     if (NewMIs[0]->killsRegister(MO.getReg()))
1333                       LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[0]);
1334                     else {
1335                       assert(NewMIs[1]->killsRegister(MO.getReg()) &&
1336                              "Kill missing after load unfold!");
1337                       LV->replaceKillInstruction(MO.getReg(), &MI, NewMIs[1]);
1338                     }
1339                   }
1340                 } else if (LV->removeVirtualRegisterDead(MO.getReg(), &MI)) {
1341                   if (NewMIs[1]->registerDefIsDead(MO.getReg()))
1342                     LV->addVirtualRegisterDead(MO.getReg(), NewMIs[1]);
1343                   else {
1344                     assert(NewMIs[0]->registerDefIsDead(MO.getReg()) &&
1345                            "Dead flag missing after load unfold!");
1346                     LV->addVirtualRegisterDead(MO.getReg(), NewMIs[0]);
1347                   }
1348                 }
1349               }
1350             }
1351             LV->addVirtualRegisterKilled(Reg, NewMIs[1]);
1352           }
1353           MI.eraseFromParent();
1354           mi = NewMIs[1];
1355           if (TransformSuccess)
1356             return true;
1357         } else {
1358           // Transforming didn't eliminate the tie and didn't lead to an
1359           // improvement. Clean up the unfolded instructions and keep the
1360           // original.
1361           DEBUG(dbgs() << "2addr: ABANDONING UNFOLD\n");
1362           NewMIs[0]->eraseFromParent();
1363           NewMIs[1]->eraseFromParent();
1364         }
1365       }
1366     }
1367   }
1368
1369   return false;
1370 }
1371
1372 /// runOnMachineFunction - Reduce two-address instructions to two operands.
1373 ///
1374 bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
1375   DEBUG(dbgs() << "Machine Function\n");
1376   const TargetMachine &TM = MF.getTarget();
1377   MRI = &MF.getRegInfo();
1378   TII = TM.getInstrInfo();
1379   TRI = TM.getRegisterInfo();
1380   InstrItins = TM.getInstrItineraryData();
1381   LV = getAnalysisIfAvailable<LiveVariables>();
1382   AA = &getAnalysis<AliasAnalysis>();
1383
1384   bool MadeChange = false;
1385
1386   DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
1387   DEBUG(dbgs() << "********** Function: " 
1388         << MF.getFunction()->getName() << '\n');
1389
1390   // This pass takes the function out of SSA form.
1391   MRI->leaveSSA();
1392
1393   // ReMatRegs - Keep track of the registers whose def's are remat'ed.
1394   BitVector ReMatRegs(MRI->getNumVirtRegs());
1395
1396   typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
1397     TiedOperandMap;
1398   TiedOperandMap TiedOperands(4);
1399
1400   SmallPtrSet<MachineInstr*, 8> Processed;
1401   for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
1402        mbbi != mbbe; ++mbbi) {
1403     unsigned Dist = 0;
1404     DistanceMap.clear();
1405     SrcRegMap.clear();
1406     DstRegMap.clear();
1407     Processed.clear();
1408     for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
1409          mi != me; ) {
1410       MachineBasicBlock::iterator nmi = llvm::next(mi);
1411       if (mi->isDebugValue()) {
1412         mi = nmi;
1413         continue;
1414       }
1415
1416       // Remember REG_SEQUENCE instructions, we'll deal with them later.
1417       if (mi->isRegSequence())
1418         RegSequences.push_back(&*mi);
1419
1420       const MCInstrDesc &MCID = mi->getDesc();
1421       bool FirstTied = true;
1422
1423       DistanceMap.insert(std::make_pair(mi, ++Dist));
1424
1425       ProcessCopy(&*mi, &*mbbi, Processed);
1426
1427       // First scan through all the tied register uses in this instruction
1428       // and record a list of pairs of tied operands for each register.
1429       unsigned NumOps = mi->isInlineAsm()
1430         ? mi->getNumOperands() : MCID.getNumOperands();
1431       for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
1432         unsigned DstIdx = 0;
1433         if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
1434           continue;
1435
1436         if (FirstTied) {
1437           FirstTied = false;
1438           ++NumTwoAddressInstrs;
1439           DEBUG(dbgs() << '\t' << *mi);
1440         }
1441
1442         assert(mi->getOperand(SrcIdx).isReg() &&
1443                mi->getOperand(SrcIdx).getReg() &&
1444                mi->getOperand(SrcIdx).isUse() &&
1445                "two address instruction invalid");
1446
1447         unsigned regB = mi->getOperand(SrcIdx).getReg();
1448         TiedOperands[regB].push_back(std::make_pair(SrcIdx, DstIdx));
1449       }
1450
1451       // Now iterate over the information collected above.
1452       for (TiedOperandMap::iterator OI = TiedOperands.begin(),
1453              OE = TiedOperands.end(); OI != OE; ++OI) {
1454         SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
1455
1456         // If the instruction has a single pair of tied operands, try some
1457         // transformations that may either eliminate the tied operands or
1458         // improve the opportunities for coalescing away the register copy.
1459         if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
1460           unsigned SrcIdx = TiedPairs[0].first;
1461           unsigned DstIdx = TiedPairs[0].second;
1462
1463           // If the registers are already equal, nothing needs to be done.
1464           if (mi->getOperand(SrcIdx).getReg() ==
1465               mi->getOperand(DstIdx).getReg())
1466             break; // Done with this instruction.
1467
1468           if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist,
1469                                       Processed))
1470             break; // The tied operands have been eliminated.
1471         }
1472
1473         bool IsEarlyClobber = false;
1474         bool RemovedKillFlag = false;
1475         bool AllUsesCopied = true;
1476         unsigned LastCopiedReg = 0;
1477         unsigned regB = OI->first;
1478         for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
1479           unsigned SrcIdx = TiedPairs[tpi].first;
1480           unsigned DstIdx = TiedPairs[tpi].second;
1481
1482           const MachineOperand &DstMO = mi->getOperand(DstIdx);
1483           unsigned regA = DstMO.getReg();
1484           IsEarlyClobber |= DstMO.isEarlyClobber();
1485
1486           // Grab regB from the instruction because it may have changed if the
1487           // instruction was commuted.
1488           regB = mi->getOperand(SrcIdx).getReg();
1489
1490           if (regA == regB) {
1491             // The register is tied to multiple destinations (or else we would
1492             // not have continued this far), but this use of the register
1493             // already matches the tied destination.  Leave it.
1494             AllUsesCopied = false;
1495             continue;
1496           }
1497           LastCopiedReg = regA;
1498
1499           assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1500                  "cannot make instruction into two-address form");
1501
1502 #ifndef NDEBUG
1503           // First, verify that we don't have a use of "a" in the instruction
1504           // (a = b + a for example) because our transformation will not
1505           // work. This should never occur because we are in SSA form.
1506           for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1507             assert(i == DstIdx ||
1508                    !mi->getOperand(i).isReg() ||
1509                    mi->getOperand(i).getReg() != regA);
1510 #endif
1511
1512           // Emit a copy or rematerialize the definition.
1513           const TargetRegisterClass *rc = MRI->getRegClass(regB);
1514           MachineInstr *DefMI = MRI->getVRegDef(regB);
1515           // If it's safe and profitable, remat the definition instead of
1516           // copying it.
1517           if (DefMI &&
1518               DefMI->getDesc().isAsCheapAsAMove() &&
1519               DefMI->isSafeToReMat(TII, AA, regB) &&
1520               isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
1521             DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
1522             unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
1523             TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, *TRI);
1524             ReMatRegs.set(TargetRegisterInfo::virtReg2Index(regB));
1525             ++NumReMats;
1526           } else {
1527             BuildMI(*mbbi, mi, mi->getDebugLoc(), TII->get(TargetOpcode::COPY),
1528                     regA).addReg(regB);
1529           }
1530
1531           MachineBasicBlock::iterator prevMI = prior(mi);
1532           // Update DistanceMap.
1533           DistanceMap.insert(std::make_pair(prevMI, Dist));
1534           DistanceMap[mi] = ++Dist;
1535
1536           DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
1537
1538           MachineOperand &MO = mi->getOperand(SrcIdx);
1539           assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1540                  "inconsistent operand info for 2-reg pass");
1541           if (MO.isKill()) {
1542             MO.setIsKill(false);
1543             RemovedKillFlag = true;
1544           }
1545           MO.setReg(regA);
1546         }
1547
1548         if (AllUsesCopied) {
1549           if (!IsEarlyClobber) {
1550             // Replace other (un-tied) uses of regB with LastCopiedReg.
1551             for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1552               MachineOperand &MO = mi->getOperand(i);
1553               if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1554                 if (MO.isKill()) {
1555                   MO.setIsKill(false);
1556                   RemovedKillFlag = true;
1557                 }
1558                 MO.setReg(LastCopiedReg);
1559               }
1560             }
1561           }
1562
1563           // Update live variables for regB.
1564           if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1565             LV->addVirtualRegisterKilled(regB, prior(mi));
1566
1567         } else if (RemovedKillFlag) {
1568           // Some tied uses of regB matched their destination registers, so
1569           // regB is still used in this instruction, but a kill flag was
1570           // removed from a different tied use of regB, so now we need to add
1571           // a kill flag to one of the remaining uses of regB.
1572           for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1573             MachineOperand &MO = mi->getOperand(i);
1574             if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1575               MO.setIsKill(true);
1576               break;
1577             }
1578           }
1579         }
1580
1581         // Schedule the source copy / remat inserted to form two-address
1582         // instruction. FIXME: Does it matter the distance map may not be
1583         // accurate after it's scheduled?
1584         TII->scheduleTwoAddrSource(prior(mi), mi, *TRI);
1585
1586         MadeChange = true;
1587
1588         DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1589       }
1590
1591       // Rewrite INSERT_SUBREG as COPY now that we no longer need SSA form.
1592       if (mi->isInsertSubreg()) {
1593         // From %reg = INSERT_SUBREG %reg, %subreg, subidx
1594         // To   %reg:subidx = COPY %subreg
1595         unsigned SubIdx = mi->getOperand(3).getImm();
1596         mi->RemoveOperand(3);
1597         assert(mi->getOperand(0).getSubReg() == 0 && "Unexpected subreg idx");
1598         mi->getOperand(0).setSubReg(SubIdx);
1599         mi->RemoveOperand(1);
1600         mi->setDesc(TII->get(TargetOpcode::COPY));
1601         DEBUG(dbgs() << "\t\tconvert to:\t" << *mi);
1602       }
1603
1604       // Clear TiedOperands here instead of at the top of the loop
1605       // since most instructions do not have tied operands.
1606       TiedOperands.clear();
1607       mi = nmi;
1608     }
1609   }
1610
1611   // Some remat'ed instructions are dead.
1612   for (int i = ReMatRegs.find_first(); i != -1; i = ReMatRegs.find_next(i)) {
1613     unsigned VReg = TargetRegisterInfo::index2VirtReg(i);
1614     if (MRI->use_nodbg_empty(VReg)) {
1615       MachineInstr *DefMI = MRI->getVRegDef(VReg);
1616       DefMI->eraseFromParent();
1617     }
1618   }
1619
1620   // Eliminate REG_SEQUENCE instructions. Their whole purpose was to preseve
1621   // SSA form. It's now safe to de-SSA.
1622   MadeChange |= EliminateRegSequences();
1623
1624   return MadeChange;
1625 }
1626
1627 static void UpdateRegSequenceSrcs(unsigned SrcReg,
1628                                   unsigned DstReg, unsigned SubIdx,
1629                                   MachineRegisterInfo *MRI,
1630                                   const TargetRegisterInfo &TRI) {
1631   for (MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(SrcReg),
1632          RE = MRI->reg_end(); RI != RE; ) {
1633     MachineOperand &MO = RI.getOperand();
1634     ++RI;
1635     MO.substVirtReg(DstReg, SubIdx, TRI);
1636   }
1637 }
1638
1639 /// CoalesceExtSubRegs - If a number of sources of the REG_SEQUENCE are
1640 /// EXTRACT_SUBREG from the same register and to the same virtual register
1641 /// with different sub-register indices, attempt to combine the
1642 /// EXTRACT_SUBREGs and pre-coalesce them. e.g.
1643 /// %reg1026<def> = VLDMQ %reg1025<kill>, 260, pred:14, pred:%reg0
1644 /// %reg1029:6<def> = EXTRACT_SUBREG %reg1026, 6
1645 /// %reg1029:5<def> = EXTRACT_SUBREG %reg1026<kill>, 5
1646 /// Since D subregs 5, 6 can combine to a Q register, we can coalesce
1647 /// reg1026 to reg1029.
1648 void
1649 TwoAddressInstructionPass::CoalesceExtSubRegs(SmallVector<unsigned,4> &Srcs,
1650                                               unsigned DstReg) {
1651   SmallSet<unsigned, 4> Seen;
1652   for (unsigned i = 0, e = Srcs.size(); i != e; ++i) {
1653     unsigned SrcReg = Srcs[i];
1654     if (!Seen.insert(SrcReg))
1655       continue;
1656
1657     // Check that the instructions are all in the same basic block.
1658     MachineInstr *SrcDefMI = MRI->getVRegDef(SrcReg);
1659     MachineInstr *DstDefMI = MRI->getVRegDef(DstReg);
1660     if (SrcDefMI->getParent() != DstDefMI->getParent())
1661       continue;
1662
1663     // If there are no other uses than copies which feed into
1664     // the reg_sequence, then we might be able to coalesce them.
1665     bool CanCoalesce = true;
1666     SmallVector<unsigned, 4> SrcSubIndices, DstSubIndices;
1667     for (MachineRegisterInfo::use_nodbg_iterator
1668            UI = MRI->use_nodbg_begin(SrcReg),
1669            UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1670       MachineInstr *UseMI = &*UI;
1671       if (!UseMI->isCopy() || UseMI->getOperand(0).getReg() != DstReg) {
1672         CanCoalesce = false;
1673         break;
1674       }
1675       SrcSubIndices.push_back(UseMI->getOperand(1).getSubReg());
1676       DstSubIndices.push_back(UseMI->getOperand(0).getSubReg());
1677     }
1678
1679     if (!CanCoalesce || SrcSubIndices.size() < 2)
1680       continue;
1681
1682     // Check that the source subregisters can be combined.
1683     std::sort(SrcSubIndices.begin(), SrcSubIndices.end());
1684     unsigned NewSrcSubIdx = 0;
1685     if (!TRI->canCombineSubRegIndices(MRI->getRegClass(SrcReg), SrcSubIndices,
1686                                       NewSrcSubIdx))
1687       continue;
1688
1689     // Check that the destination subregisters can also be combined.
1690     std::sort(DstSubIndices.begin(), DstSubIndices.end());
1691     unsigned NewDstSubIdx = 0;
1692     if (!TRI->canCombineSubRegIndices(MRI->getRegClass(DstReg), DstSubIndices,
1693                                       NewDstSubIdx))
1694       continue;
1695
1696     // If neither source nor destination can be combined to the full register,
1697     // just give up.  This could be improved if it ever matters.
1698     if (NewSrcSubIdx != 0 && NewDstSubIdx != 0)
1699       continue;
1700
1701     // Now that we know that all the uses are extract_subregs and that those
1702     // subregs can somehow be combined, scan all the extract_subregs again to
1703     // make sure the subregs are in the right order and can be composed.
1704     MachineInstr *SomeMI = 0;
1705     CanCoalesce = true;
1706     for (MachineRegisterInfo::use_nodbg_iterator
1707            UI = MRI->use_nodbg_begin(SrcReg),
1708            UE = MRI->use_nodbg_end(); UI != UE; ++UI) {
1709       MachineInstr *UseMI = &*UI;
1710       assert(UseMI->isCopy());
1711       unsigned DstSubIdx = UseMI->getOperand(0).getSubReg();
1712       unsigned SrcSubIdx = UseMI->getOperand(1).getSubReg();
1713       assert(DstSubIdx != 0 && "missing subreg from RegSequence elimination");
1714       if ((NewDstSubIdx == 0 &&
1715            TRI->composeSubRegIndices(NewSrcSubIdx, DstSubIdx) != SrcSubIdx) ||
1716           (NewSrcSubIdx == 0 &&
1717            TRI->composeSubRegIndices(NewDstSubIdx, SrcSubIdx) != DstSubIdx)) {
1718         CanCoalesce = false;
1719         break;
1720       }
1721       // Keep track of one of the uses.
1722       SomeMI = UseMI;
1723     }
1724     if (!CanCoalesce)
1725       continue;
1726
1727     // Insert a copy to replace the original.
1728     MachineInstr *CopyMI = BuildMI(*SomeMI->getParent(), SomeMI,
1729                                    SomeMI->getDebugLoc(),
1730                                    TII->get(TargetOpcode::COPY))
1731       .addReg(DstReg, RegState::Define, NewDstSubIdx)
1732       .addReg(SrcReg, 0, NewSrcSubIdx);
1733
1734     // Remove all the old extract instructions.
1735     for (MachineRegisterInfo::use_nodbg_iterator
1736            UI = MRI->use_nodbg_begin(SrcReg),
1737            UE = MRI->use_nodbg_end(); UI != UE; ) {
1738       MachineInstr *UseMI = &*UI;
1739       ++UI;
1740       if (UseMI == CopyMI)
1741         continue;
1742       assert(UseMI->isCopy());
1743       // Move any kills to the new copy or extract instruction.
1744       if (UseMI->getOperand(1).isKill()) {
1745         CopyMI->getOperand(1).setIsKill();
1746         if (LV)
1747           // Update live variables
1748           LV->replaceKillInstruction(SrcReg, UseMI, &*CopyMI);
1749       }
1750       UseMI->eraseFromParent();
1751     }
1752   }
1753 }
1754
1755 static bool HasOtherRegSequenceUses(unsigned Reg, MachineInstr *RegSeq,
1756                                     MachineRegisterInfo *MRI) {
1757   for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
1758          UE = MRI->use_end(); UI != UE; ++UI) {
1759     MachineInstr *UseMI = &*UI;
1760     if (UseMI != RegSeq && UseMI->isRegSequence())
1761       return true;
1762   }
1763   return false;
1764 }
1765
1766 /// EliminateRegSequences - Eliminate REG_SEQUENCE instructions as part
1767 /// of the de-ssa process. This replaces sources of REG_SEQUENCE as
1768 /// sub-register references of the register defined by REG_SEQUENCE. e.g.
1769 ///
1770 /// %reg1029<def>, %reg1030<def> = VLD1q16 %reg1024<kill>, ...
1771 /// %reg1031<def> = REG_SEQUENCE %reg1029<kill>, 5, %reg1030<kill>, 6
1772 /// =>
1773 /// %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
1774 bool TwoAddressInstructionPass::EliminateRegSequences() {
1775   if (RegSequences.empty())
1776     return false;
1777
1778   for (unsigned i = 0, e = RegSequences.size(); i != e; ++i) {
1779     MachineInstr *MI = RegSequences[i];
1780     unsigned DstReg = MI->getOperand(0).getReg();
1781     if (MI->getOperand(0).getSubReg() ||
1782         TargetRegisterInfo::isPhysicalRegister(DstReg) ||
1783         !(MI->getNumOperands() & 1)) {
1784       DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1785       llvm_unreachable(0);
1786     }
1787
1788     bool IsImpDef = true;
1789     SmallVector<unsigned, 4> RealSrcs;
1790     SmallSet<unsigned, 4> Seen;
1791     for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1792       unsigned SrcReg = MI->getOperand(i).getReg();
1793       unsigned SubIdx = MI->getOperand(i+1).getImm();
1794       if (MI->getOperand(i).getSubReg() ||
1795           TargetRegisterInfo::isPhysicalRegister(SrcReg)) {
1796         DEBUG(dbgs() << "Illegal REG_SEQUENCE instruction:" << *MI);
1797         llvm_unreachable(0);
1798       }
1799
1800       MachineInstr *DefMI = MRI->getVRegDef(SrcReg);
1801       if (DefMI->isImplicitDef()) {
1802         DefMI->eraseFromParent();
1803         continue;
1804       }
1805       IsImpDef = false;
1806
1807       // Remember COPY sources. These might be candidate for coalescing.
1808       if (DefMI->isCopy() && DefMI->getOperand(1).getSubReg())
1809         RealSrcs.push_back(DefMI->getOperand(1).getReg());
1810
1811       bool isKill = MI->getOperand(i).isKill();
1812       if (!Seen.insert(SrcReg) || MI->getParent() != DefMI->getParent() ||
1813           !isKill || HasOtherRegSequenceUses(SrcReg, MI, MRI) ||
1814           !TRI->getMatchingSuperRegClass(MRI->getRegClass(DstReg),
1815                                          MRI->getRegClass(SrcReg), SubIdx)) {
1816         // REG_SEQUENCE cannot have duplicated operands, add a copy.
1817         // Also add an copy if the source is live-in the block. We don't want
1818         // to end up with a partial-redef of a livein, e.g.
1819         // BB0:
1820         // reg1051:10<def> =
1821         // ...
1822         // BB1:
1823         // ... = reg1051:10
1824         // BB2:
1825         // reg1051:9<def> =
1826         // LiveIntervalAnalysis won't like it.
1827         //
1828         // If the REG_SEQUENCE doesn't kill its source, keeping live variables
1829         // correctly up to date becomes very difficult. Insert a copy.
1830
1831         // Defer any kill flag to the last operand using SrcReg. Otherwise, we
1832         // might insert a COPY that uses SrcReg after is was killed.
1833         if (isKill)
1834           for (unsigned j = i + 2; j < e; j += 2)
1835             if (MI->getOperand(j).getReg() == SrcReg) {
1836               MI->getOperand(j).setIsKill();
1837               isKill = false;
1838               break;
1839             }
1840
1841         MachineBasicBlock::iterator InsertLoc = MI;
1842         MachineInstr *CopyMI = BuildMI(*MI->getParent(), InsertLoc,
1843                                 MI->getDebugLoc(), TII->get(TargetOpcode::COPY))
1844             .addReg(DstReg, RegState::Define, SubIdx)
1845             .addReg(SrcReg, getKillRegState(isKill));
1846         MI->getOperand(i).setReg(0);
1847         if (LV && isKill)
1848           LV->replaceKillInstruction(SrcReg, MI, CopyMI);
1849         DEBUG(dbgs() << "Inserted: " << *CopyMI);
1850       }
1851     }
1852
1853     for (unsigned i = 1, e = MI->getNumOperands(); i < e; i += 2) {
1854       unsigned SrcReg = MI->getOperand(i).getReg();
1855       if (!SrcReg) continue;
1856       unsigned SubIdx = MI->getOperand(i+1).getImm();
1857       UpdateRegSequenceSrcs(SrcReg, DstReg, SubIdx, MRI, *TRI);
1858     }
1859
1860     if (IsImpDef) {
1861       DEBUG(dbgs() << "Turned: " << *MI << " into an IMPLICIT_DEF");
1862       MI->setDesc(TII->get(TargetOpcode::IMPLICIT_DEF));
1863       for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
1864         MI->RemoveOperand(j);      
1865     } else {
1866       DEBUG(dbgs() << "Eliminated: " << *MI);
1867       MI->eraseFromParent();
1868     }
1869
1870     // Try coalescing some EXTRACT_SUBREG instructions. This can create
1871     // INSERT_SUBREG instructions that must have <undef> flags added by
1872     // LiveIntervalAnalysis, so only run it when LiveVariables is available.
1873     if (LV)
1874       CoalesceExtSubRegs(RealSrcs, DstReg);
1875   }
1876
1877   RegSequences.clear();
1878   return true;
1879 }