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