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