TwoAddressInstructionPass.cpp revision fe5c38072a6c6bd89361670523e57838140a2e2c
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/MachineRegisterInfo.h"
37#include "llvm/Analysis/AliasAnalysis.h"
38#include "llvm/Target/TargetRegisterInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetMachine.h"
41#include "llvm/Target/TargetOptions.h"
42#include "llvm/Support/Debug.h"
43#include "llvm/ADT/BitVector.h"
44#include "llvm/ADT/DenseMap.h"
45#include "llvm/ADT/SmallSet.h"
46#include "llvm/ADT/Statistic.h"
47#include "llvm/ADT/STLExtras.h"
48using namespace llvm;
49
50STATISTIC(NumTwoAddressInstrs, "Number of two-address instructions");
51STATISTIC(NumCommuted        , "Number of instructions commuted to coalesce");
52STATISTIC(NumAggrCommuted    , "Number of instructions aggressively commuted");
53STATISTIC(NumConvertedTo3Addr, "Number of instructions promoted to 3-address");
54STATISTIC(Num3AddrSunk,        "Number of 3-address instructions sunk");
55STATISTIC(NumReMats,           "Number of instructions re-materialized");
56STATISTIC(NumDeletes,          "Number of dead instructions deleted");
57
58namespace {
59  class TwoAddressInstructionPass : public MachineFunctionPass {
60    const TargetInstrInfo *TII;
61    const TargetRegisterInfo *TRI;
62    MachineRegisterInfo *MRI;
63    LiveVariables *LV;
64    AliasAnalysis *AA;
65
66    // DistanceMap - Keep track the distance of a MI from the start of the
67    // current basic block.
68    DenseMap<MachineInstr*, unsigned> DistanceMap;
69
70    // SrcRegMap - A map from virtual registers to physical registers which
71    // are likely targets to be coalesced to due to copies from physical
72    // registers to virtual registers. e.g. v1024 = move r0.
73    DenseMap<unsigned, unsigned> SrcRegMap;
74
75    // DstRegMap - A map from virtual registers to physical registers which
76    // are likely targets to be coalesced to due to copies to physical
77    // registers from virtual registers. e.g. r1 = move v1024.
78    DenseMap<unsigned, unsigned> DstRegMap;
79
80    bool Sink3AddrInstruction(MachineBasicBlock *MBB, MachineInstr *MI,
81                              unsigned Reg,
82                              MachineBasicBlock::iterator OldPos);
83
84    bool isProfitableToReMat(unsigned Reg, const TargetRegisterClass *RC,
85                             MachineInstr *MI, MachineInstr *DefMI,
86                             MachineBasicBlock *MBB, unsigned Loc);
87
88    bool NoUseAfterLastDef(unsigned Reg, MachineBasicBlock *MBB, unsigned Dist,
89                           unsigned &LastDef);
90
91    MachineInstr *FindLastUseInMBB(unsigned Reg, MachineBasicBlock *MBB,
92                                   unsigned Dist);
93
94    bool isProfitableToCommute(unsigned regB, unsigned regC,
95                               MachineInstr *MI, MachineBasicBlock *MBB,
96                               unsigned Dist);
97
98    bool CommuteInstruction(MachineBasicBlock::iterator &mi,
99                            MachineFunction::iterator &mbbi,
100                            unsigned RegB, unsigned RegC, unsigned Dist);
101
102    bool isProfitableToConv3Addr(unsigned RegA);
103
104    bool ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
105                            MachineBasicBlock::iterator &nmi,
106                            MachineFunction::iterator &mbbi,
107                            unsigned RegB, unsigned Dist);
108
109    typedef std::pair<std::pair<unsigned, bool>, MachineInstr*> NewKill;
110    bool canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
111                               SmallVector<NewKill, 4> &NewKills,
112                               MachineBasicBlock *MBB, unsigned Dist);
113    bool DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
114                           MachineBasicBlock::iterator &nmi,
115                           MachineFunction::iterator &mbbi, unsigned Dist);
116
117    bool TryInstructionTransform(MachineBasicBlock::iterator &mi,
118                                 MachineBasicBlock::iterator &nmi,
119                                 MachineFunction::iterator &mbbi,
120                                 unsigned SrcIdx, unsigned DstIdx,
121                                 unsigned Dist);
122
123    void ProcessCopy(MachineInstr *MI, MachineBasicBlock *MBB,
124                     SmallPtrSet<MachineInstr*, 8> &Processed);
125
126  public:
127    static char ID; // Pass identification, replacement for typeid
128    TwoAddressInstructionPass() : MachineFunctionPass(&ID) {}
129
130    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
131      AU.setPreservesCFG();
132      AU.addRequired<AliasAnalysis>();
133      AU.addPreserved<LiveVariables>();
134      AU.addPreservedID(MachineLoopInfoID);
135      AU.addPreservedID(MachineDominatorsID);
136      if (StrongPHIElim)
137        AU.addPreservedID(StrongPHIEliminationID);
138      else
139        AU.addPreservedID(PHIEliminationID);
140      MachineFunctionPass::getAnalysisUsage(AU);
141    }
142
143    /// runOnMachineFunction - Pass entry point.
144    bool runOnMachineFunction(MachineFunction&);
145  };
146}
147
148char TwoAddressInstructionPass::ID = 0;
149static RegisterPass<TwoAddressInstructionPass>
150X("twoaddressinstruction", "Two-Address instruction pass");
151
152const PassInfo *const llvm::TwoAddressInstructionPassID = &X;
153
154/// Sink3AddrInstruction - A two-address instruction has been converted to a
155/// three-address instruction to avoid clobbering a register. Try to sink it
156/// past the instruction that would kill the above mentioned register to reduce
157/// register pressure.
158bool TwoAddressInstructionPass::Sink3AddrInstruction(MachineBasicBlock *MBB,
159                                           MachineInstr *MI, unsigned SavedReg,
160                                           MachineBasicBlock::iterator OldPos) {
161  // Check if it's safe to move this instruction.
162  bool SeenStore = true; // Be conservative.
163  if (!MI->isSafeToMove(TII, SeenStore, AA))
164    return false;
165
166  unsigned DefReg = 0;
167  SmallSet<unsigned, 4> UseRegs;
168
169  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
170    const MachineOperand &MO = MI->getOperand(i);
171    if (!MO.isReg())
172      continue;
173    unsigned MOReg = MO.getReg();
174    if (!MOReg)
175      continue;
176    if (MO.isUse() && MOReg != SavedReg)
177      UseRegs.insert(MO.getReg());
178    if (!MO.isDef())
179      continue;
180    if (MO.isImplicit())
181      // Don't try to move it if it implicitly defines a register.
182      return false;
183    if (DefReg)
184      // For now, don't move any instructions that define multiple registers.
185      return false;
186    DefReg = MO.getReg();
187  }
188
189  // Find the instruction that kills SavedReg.
190  MachineInstr *KillMI = NULL;
191  for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SavedReg),
192         UE = MRI->use_end(); UI != UE; ++UI) {
193    MachineOperand &UseMO = UI.getOperand();
194    if (!UseMO.isKill())
195      continue;
196    KillMI = UseMO.getParent();
197    break;
198  }
199
200  if (!KillMI || KillMI->getParent() != MBB || KillMI == MI)
201    return false;
202
203  // If any of the definitions are used by another instruction between the
204  // position and the kill use, then it's not safe to sink it.
205  //
206  // FIXME: This can be sped up if there is an easy way to query whether an
207  // instruction is before or after another instruction. Then we can use
208  // MachineRegisterInfo def / use instead.
209  MachineOperand *KillMO = NULL;
210  MachineBasicBlock::iterator KillPos = KillMI;
211  ++KillPos;
212
213  unsigned NumVisited = 0;
214  for (MachineBasicBlock::iterator I = llvm::next(OldPos); I != KillPos; ++I) {
215    MachineInstr *OtherMI = I;
216    if (NumVisited > 30)  // FIXME: Arbitrary limit to reduce compile time cost.
217      return false;
218    ++NumVisited;
219    for (unsigned i = 0, e = OtherMI->getNumOperands(); i != e; ++i) {
220      MachineOperand &MO = OtherMI->getOperand(i);
221      if (!MO.isReg())
222        continue;
223      unsigned MOReg = MO.getReg();
224      if (!MOReg)
225        continue;
226      if (DefReg == MOReg)
227        return false;
228
229      if (MO.isKill()) {
230        if (OtherMI == KillMI && MOReg == SavedReg)
231          // Save the operand that kills the register. We want to unset the kill
232          // marker if we can sink MI past it.
233          KillMO = &MO;
234        else if (UseRegs.count(MOReg))
235          // One of the uses is killed before the destination.
236          return false;
237      }
238    }
239  }
240
241  // Update kill and LV information.
242  KillMO->setIsKill(false);
243  KillMO = MI->findRegisterUseOperand(SavedReg, false, TRI);
244  KillMO->setIsKill(true);
245
246  if (LV)
247    LV->replaceKillInstruction(SavedReg, KillMI, MI);
248
249  // Move instruction to its destination.
250  MBB->remove(MI);
251  MBB->insert(KillPos, MI);
252
253  ++Num3AddrSunk;
254  return true;
255}
256
257/// isTwoAddrUse - Return true if the specified MI is using the specified
258/// register as a two-address operand.
259static bool isTwoAddrUse(MachineInstr *UseMI, unsigned Reg) {
260  const TargetInstrDesc &TID = UseMI->getDesc();
261  for (unsigned i = 0, e = TID.getNumOperands(); i != e; ++i) {
262    MachineOperand &MO = UseMI->getOperand(i);
263    if (MO.isReg() && MO.getReg() == Reg &&
264        (MO.isDef() || UseMI->isRegTiedToDefOperand(i)))
265      // Earlier use is a two-address one.
266      return true;
267  }
268  return false;
269}
270
271/// isProfitableToReMat - Return true if the heuristics determines it is likely
272/// to be profitable to re-materialize the definition of Reg rather than copy
273/// the register.
274bool
275TwoAddressInstructionPass::isProfitableToReMat(unsigned Reg,
276                                         const TargetRegisterClass *RC,
277                                         MachineInstr *MI, MachineInstr *DefMI,
278                                         MachineBasicBlock *MBB, unsigned Loc) {
279  bool OtherUse = false;
280  for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
281         UE = MRI->use_end(); UI != UE; ++UI) {
282    MachineOperand &UseMO = UI.getOperand();
283    MachineInstr *UseMI = UseMO.getParent();
284    MachineBasicBlock *UseMBB = UseMI->getParent();
285    if (UseMBB == MBB) {
286      DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
287      if (DI != DistanceMap.end() && DI->second == Loc)
288        continue;  // Current use.
289      OtherUse = true;
290      // There is at least one other use in the MBB that will clobber the
291      // register.
292      if (isTwoAddrUse(UseMI, Reg))
293        return true;
294    }
295  }
296
297  // If other uses in MBB are not two-address uses, then don't remat.
298  if (OtherUse)
299    return false;
300
301  // No other uses in the same block, remat if it's defined in the same
302  // block so it does not unnecessarily extend the live range.
303  return MBB == DefMI->getParent();
304}
305
306/// NoUseAfterLastDef - Return true if there are no intervening uses between the
307/// last instruction in the MBB that defines the specified register and the
308/// two-address instruction which is being processed. It also returns the last
309/// def location by reference
310bool TwoAddressInstructionPass::NoUseAfterLastDef(unsigned Reg,
311                                           MachineBasicBlock *MBB, unsigned Dist,
312                                           unsigned &LastDef) {
313  LastDef = 0;
314  unsigned LastUse = Dist;
315  for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
316         E = MRI->reg_end(); I != E; ++I) {
317    MachineOperand &MO = I.getOperand();
318    MachineInstr *MI = MO.getParent();
319    if (MI->getParent() != MBB)
320      continue;
321    if (MI->getOpcode() == TargetInstrInfo::DEBUG_VALUE)
322      continue;
323    DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
324    if (DI == DistanceMap.end())
325      continue;
326    if (MO.isUse() && DI->second < LastUse)
327      LastUse = DI->second;
328    if (MO.isDef() && DI->second > LastDef)
329      LastDef = DI->second;
330  }
331
332  return !(LastUse > LastDef && LastUse < Dist);
333}
334
335MachineInstr *TwoAddressInstructionPass::FindLastUseInMBB(unsigned Reg,
336                                                         MachineBasicBlock *MBB,
337                                                         unsigned Dist) {
338  unsigned LastUseDist = 0;
339  MachineInstr *LastUse = 0;
340  for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(Reg),
341         E = MRI->reg_end(); I != E; ++I) {
342    MachineOperand &MO = I.getOperand();
343    MachineInstr *MI = MO.getParent();
344    if (MI->getParent() != MBB)
345      continue;
346    if (MI->getOpcode() == TargetInstrInfo::DEBUG_VALUE)
347      continue;
348    DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(MI);
349    if (DI == DistanceMap.end())
350      continue;
351    if (DI->second >= Dist)
352      continue;
353
354    if (MO.isUse() && DI->second > LastUseDist) {
355      LastUse = DI->first;
356      LastUseDist = DI->second;
357    }
358  }
359  return LastUse;
360}
361
362/// isCopyToReg - Return true if the specified MI is a copy instruction or
363/// a extract_subreg instruction. It also returns the source and destination
364/// registers and whether they are physical registers by reference.
365static bool isCopyToReg(MachineInstr &MI, const TargetInstrInfo *TII,
366                        unsigned &SrcReg, unsigned &DstReg,
367                        bool &IsSrcPhys, bool &IsDstPhys) {
368  SrcReg = 0;
369  DstReg = 0;
370  unsigned SrcSubIdx, DstSubIdx;
371  if (!TII->isMoveInstr(MI, SrcReg, DstReg, SrcSubIdx, DstSubIdx)) {
372    if (MI.getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
373      DstReg = MI.getOperand(0).getReg();
374      SrcReg = MI.getOperand(1).getReg();
375    } else if (MI.getOpcode() == TargetInstrInfo::INSERT_SUBREG) {
376      DstReg = MI.getOperand(0).getReg();
377      SrcReg = MI.getOperand(2).getReg();
378    } else if (MI.getOpcode() == TargetInstrInfo::SUBREG_TO_REG) {
379      DstReg = MI.getOperand(0).getReg();
380      SrcReg = MI.getOperand(2).getReg();
381    }
382  }
383
384  if (DstReg) {
385    IsSrcPhys = TargetRegisterInfo::isPhysicalRegister(SrcReg);
386    IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
387    return true;
388  }
389  return false;
390}
391
392/// isKilled - Test if the given register value, which is used by the given
393/// instruction, is killed by the given instruction. This looks through
394/// coalescable copies to see if the original value is potentially not killed.
395///
396/// For example, in this code:
397///
398///   %reg1034 = copy %reg1024
399///   %reg1035 = copy %reg1025<kill>
400///   %reg1036 = add %reg1034<kill>, %reg1035<kill>
401///
402/// %reg1034 is not considered to be killed, since it is copied from a
403/// register which is not killed. Treating it as not killed lets the
404/// normal heuristics commute the (two-address) add, which lets
405/// coalescing eliminate the extra copy.
406///
407static bool isKilled(MachineInstr &MI, unsigned Reg,
408                     const MachineRegisterInfo *MRI,
409                     const TargetInstrInfo *TII) {
410  MachineInstr *DefMI = &MI;
411  for (;;) {
412    if (!DefMI->killsRegister(Reg))
413      return false;
414    if (TargetRegisterInfo::isPhysicalRegister(Reg))
415      return true;
416    MachineRegisterInfo::def_iterator Begin = MRI->def_begin(Reg);
417    // If there are multiple defs, we can't do a simple analysis, so just
418    // go with what the kill flag says.
419    if (llvm::next(Begin) != MRI->def_end())
420      return true;
421    DefMI = &*Begin;
422    bool IsSrcPhys, IsDstPhys;
423    unsigned SrcReg,  DstReg;
424    // If the def is something other than a copy, then it isn't going to
425    // be coalesced, so follow the kill flag.
426    if (!isCopyToReg(*DefMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
427      return true;
428    Reg = SrcReg;
429  }
430}
431
432/// isTwoAddrUse - Return true if the specified MI uses the specified register
433/// as a two-address use. If so, return the destination register by reference.
434static bool isTwoAddrUse(MachineInstr &MI, unsigned Reg, unsigned &DstReg) {
435  const TargetInstrDesc &TID = MI.getDesc();
436  unsigned NumOps = (MI.getOpcode() == TargetInstrInfo::INLINEASM)
437    ? MI.getNumOperands() : TID.getNumOperands();
438  for (unsigned i = 0; i != NumOps; ++i) {
439    const MachineOperand &MO = MI.getOperand(i);
440    if (!MO.isReg() || !MO.isUse() || MO.getReg() != Reg)
441      continue;
442    unsigned ti;
443    if (MI.isRegTiedToDefOperand(i, &ti)) {
444      DstReg = MI.getOperand(ti).getReg();
445      return true;
446    }
447  }
448  return false;
449}
450
451/// findOnlyInterestingUse - Given a register, if has a single in-basic block
452/// use, return the use instruction if it's a copy or a two-address use.
453static
454MachineInstr *findOnlyInterestingUse(unsigned Reg, MachineBasicBlock *MBB,
455                                     MachineRegisterInfo *MRI,
456                                     const TargetInstrInfo *TII,
457                                     bool &IsCopy,
458                                     unsigned &DstReg, bool &IsDstPhys) {
459  MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg);
460  if (UI == MRI->use_end())
461    return 0;
462  MachineInstr &UseMI = *UI;
463  if (++UI != MRI->use_end())
464    // More than one use.
465    return 0;
466  if (UseMI.getParent() != MBB)
467    return 0;
468  unsigned SrcReg;
469  bool IsSrcPhys;
470  if (isCopyToReg(UseMI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys)) {
471    IsCopy = true;
472    return &UseMI;
473  }
474  IsDstPhys = false;
475  if (isTwoAddrUse(UseMI, Reg, DstReg)) {
476    IsDstPhys = TargetRegisterInfo::isPhysicalRegister(DstReg);
477    return &UseMI;
478  }
479  return 0;
480}
481
482/// getMappedReg - Return the physical register the specified virtual register
483/// might be mapped to.
484static unsigned
485getMappedReg(unsigned Reg, DenseMap<unsigned, unsigned> &RegMap) {
486  while (TargetRegisterInfo::isVirtualRegister(Reg))  {
487    DenseMap<unsigned, unsigned>::iterator SI = RegMap.find(Reg);
488    if (SI == RegMap.end())
489      return 0;
490    Reg = SI->second;
491  }
492  if (TargetRegisterInfo::isPhysicalRegister(Reg))
493    return Reg;
494  return 0;
495}
496
497/// regsAreCompatible - Return true if the two registers are equal or aliased.
498///
499static bool
500regsAreCompatible(unsigned RegA, unsigned RegB, const TargetRegisterInfo *TRI) {
501  if (RegA == RegB)
502    return true;
503  if (!RegA || !RegB)
504    return false;
505  return TRI->regsOverlap(RegA, RegB);
506}
507
508
509/// isProfitableToReMat - Return true if it's potentially profitable to commute
510/// the two-address instruction that's being processed.
511bool
512TwoAddressInstructionPass::isProfitableToCommute(unsigned regB, unsigned regC,
513                                       MachineInstr *MI, MachineBasicBlock *MBB,
514                                       unsigned Dist) {
515  // Determine if it's profitable to commute this two address instruction. In
516  // general, we want no uses between this instruction and the definition of
517  // the two-address register.
518  // e.g.
519  // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
520  // %reg1029<def> = MOV8rr %reg1028
521  // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
522  // insert => %reg1030<def> = MOV8rr %reg1028
523  // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
524  // In this case, it might not be possible to coalesce the second MOV8rr
525  // instruction if the first one is coalesced. So it would be profitable to
526  // commute it:
527  // %reg1028<def> = EXTRACT_SUBREG %reg1027<kill>, 1
528  // %reg1029<def> = MOV8rr %reg1028
529  // %reg1029<def> = SHR8ri %reg1029, 7, %EFLAGS<imp-def,dead>
530  // insert => %reg1030<def> = MOV8rr %reg1029
531  // %reg1030<def> = ADD8rr %reg1029<kill>, %reg1028<kill>, %EFLAGS<imp-def,dead>
532
533  if (!MI->killsRegister(regC))
534    return false;
535
536  // Ok, we have something like:
537  // %reg1030<def> = ADD8rr %reg1028<kill>, %reg1029<kill>, %EFLAGS<imp-def,dead>
538  // let's see if it's worth commuting it.
539
540  // Look for situations like this:
541  // %reg1024<def> = MOV r1
542  // %reg1025<def> = MOV r0
543  // %reg1026<def> = ADD %reg1024, %reg1025
544  // r0            = MOV %reg1026
545  // Commute the ADD to hopefully eliminate an otherwise unavoidable copy.
546  unsigned FromRegB = getMappedReg(regB, SrcRegMap);
547  unsigned FromRegC = getMappedReg(regC, SrcRegMap);
548  unsigned ToRegB = getMappedReg(regB, DstRegMap);
549  unsigned ToRegC = getMappedReg(regC, DstRegMap);
550  if (!regsAreCompatible(FromRegB, ToRegB, TRI) &&
551      (regsAreCompatible(FromRegB, ToRegC, TRI) ||
552       regsAreCompatible(FromRegC, ToRegB, TRI)))
553    return true;
554
555  // If there is a use of regC between its last def (could be livein) and this
556  // instruction, then bail.
557  unsigned LastDefC = 0;
558  if (!NoUseAfterLastDef(regC, MBB, Dist, LastDefC))
559    return false;
560
561  // If there is a use of regB between its last def (could be livein) and this
562  // instruction, then go ahead and make this transformation.
563  unsigned LastDefB = 0;
564  if (!NoUseAfterLastDef(regB, MBB, Dist, LastDefB))
565    return true;
566
567  // Since there are no intervening uses for both registers, then commute
568  // if the def of regC is closer. Its live interval is shorter.
569  return LastDefB && LastDefC && LastDefC > LastDefB;
570}
571
572/// CommuteInstruction - Commute a two-address instruction and update the basic
573/// block, distance map, and live variables if needed. Return true if it is
574/// successful.
575bool
576TwoAddressInstructionPass::CommuteInstruction(MachineBasicBlock::iterator &mi,
577                               MachineFunction::iterator &mbbi,
578                               unsigned RegB, unsigned RegC, unsigned Dist) {
579  MachineInstr *MI = mi;
580  DEBUG(dbgs() << "2addr: COMMUTING  : " << *MI);
581  MachineInstr *NewMI = TII->commuteInstruction(MI);
582
583  if (NewMI == 0) {
584    DEBUG(dbgs() << "2addr: COMMUTING FAILED!\n");
585    return false;
586  }
587
588  DEBUG(dbgs() << "2addr: COMMUTED TO: " << *NewMI);
589  // If the instruction changed to commute it, update livevar.
590  if (NewMI != MI) {
591    if (LV)
592      // Update live variables
593      LV->replaceKillInstruction(RegC, MI, NewMI);
594
595    mbbi->insert(mi, NewMI);           // Insert the new inst
596    mbbi->erase(mi);                   // Nuke the old inst.
597    mi = NewMI;
598    DistanceMap.insert(std::make_pair(NewMI, Dist));
599  }
600
601  // Update source register map.
602  unsigned FromRegC = getMappedReg(RegC, SrcRegMap);
603  if (FromRegC) {
604    unsigned RegA = MI->getOperand(0).getReg();
605    SrcRegMap[RegA] = FromRegC;
606  }
607
608  return true;
609}
610
611/// isProfitableToConv3Addr - Return true if it is profitable to convert the
612/// given 2-address instruction to a 3-address one.
613bool
614TwoAddressInstructionPass::isProfitableToConv3Addr(unsigned RegA) {
615  // Look for situations like this:
616  // %reg1024<def> = MOV r1
617  // %reg1025<def> = MOV r0
618  // %reg1026<def> = ADD %reg1024, %reg1025
619  // r2            = MOV %reg1026
620  // Turn ADD into a 3-address instruction to avoid a copy.
621  unsigned FromRegA = getMappedReg(RegA, SrcRegMap);
622  unsigned ToRegA = getMappedReg(RegA, DstRegMap);
623  return (FromRegA && ToRegA && !regsAreCompatible(FromRegA, ToRegA, TRI));
624}
625
626/// ConvertInstTo3Addr - Convert the specified two-address instruction into a
627/// three address one. Return true if this transformation was successful.
628bool
629TwoAddressInstructionPass::ConvertInstTo3Addr(MachineBasicBlock::iterator &mi,
630                                              MachineBasicBlock::iterator &nmi,
631                                              MachineFunction::iterator &mbbi,
632                                              unsigned RegB, unsigned Dist) {
633  MachineInstr *NewMI = TII->convertToThreeAddress(mbbi, mi, LV);
634  if (NewMI) {
635    DEBUG(dbgs() << "2addr: CONVERTING 2-ADDR: " << *mi);
636    DEBUG(dbgs() << "2addr:         TO 3-ADDR: " << *NewMI);
637    bool Sunk = false;
638
639    if (NewMI->findRegisterUseOperand(RegB, false, TRI))
640      // FIXME: Temporary workaround. If the new instruction doesn't
641      // uses RegB, convertToThreeAddress must have created more
642      // then one instruction.
643      Sunk = Sink3AddrInstruction(mbbi, NewMI, RegB, mi);
644
645    mbbi->erase(mi); // Nuke the old inst.
646
647    if (!Sunk) {
648      DistanceMap.insert(std::make_pair(NewMI, Dist));
649      mi = NewMI;
650      nmi = llvm::next(mi);
651    }
652    return true;
653  }
654
655  return false;
656}
657
658/// ProcessCopy - If the specified instruction is not yet processed, process it
659/// if it's a copy. For a copy instruction, we find the physical registers the
660/// source and destination registers might be mapped to. These are kept in
661/// point-to maps used to determine future optimizations. e.g.
662/// v1024 = mov r0
663/// v1025 = mov r1
664/// v1026 = add v1024, v1025
665/// r1    = mov r1026
666/// If 'add' is a two-address instruction, v1024, v1026 are both potentially
667/// coalesced to r0 (from the input side). v1025 is mapped to r1. v1026 is
668/// potentially joined with r1 on the output side. It's worthwhile to commute
669/// 'add' to eliminate a copy.
670void TwoAddressInstructionPass::ProcessCopy(MachineInstr *MI,
671                                     MachineBasicBlock *MBB,
672                                     SmallPtrSet<MachineInstr*, 8> &Processed) {
673  if (Processed.count(MI))
674    return;
675
676  bool IsSrcPhys, IsDstPhys;
677  unsigned SrcReg, DstReg;
678  if (!isCopyToReg(*MI, TII, SrcReg, DstReg, IsSrcPhys, IsDstPhys))
679    return;
680
681  if (IsDstPhys && !IsSrcPhys)
682    DstRegMap.insert(std::make_pair(SrcReg, DstReg));
683  else if (!IsDstPhys && IsSrcPhys) {
684    bool isNew = SrcRegMap.insert(std::make_pair(DstReg, SrcReg)).second;
685    if (!isNew)
686      assert(SrcRegMap[DstReg] == SrcReg &&
687             "Can't map to two src physical registers!");
688
689    SmallVector<unsigned, 4> VirtRegPairs;
690    bool IsCopy = false;
691    unsigned NewReg = 0;
692    while (MachineInstr *UseMI = findOnlyInterestingUse(DstReg, MBB, MRI,TII,
693                                                   IsCopy, NewReg, IsDstPhys)) {
694      if (IsCopy) {
695        if (!Processed.insert(UseMI))
696          break;
697      }
698
699      DenseMap<MachineInstr*, unsigned>::iterator DI = DistanceMap.find(UseMI);
700      if (DI != DistanceMap.end())
701        // Earlier in the same MBB.Reached via a back edge.
702        break;
703
704      if (IsDstPhys) {
705        VirtRegPairs.push_back(NewReg);
706        break;
707      }
708      bool isNew = SrcRegMap.insert(std::make_pair(NewReg, DstReg)).second;
709      if (!isNew)
710        assert(SrcRegMap[NewReg] == DstReg &&
711               "Can't map to two src physical registers!");
712      VirtRegPairs.push_back(NewReg);
713      DstReg = NewReg;
714    }
715
716    if (!VirtRegPairs.empty()) {
717      unsigned ToReg = VirtRegPairs.back();
718      VirtRegPairs.pop_back();
719      while (!VirtRegPairs.empty()) {
720        unsigned FromReg = VirtRegPairs.back();
721        VirtRegPairs.pop_back();
722        bool isNew = DstRegMap.insert(std::make_pair(FromReg, ToReg)).second;
723        if (!isNew)
724          assert(DstRegMap[FromReg] == ToReg &&
725                 "Can't map to two dst physical registers!");
726        ToReg = FromReg;
727      }
728    }
729  }
730
731  Processed.insert(MI);
732}
733
734/// isSafeToDelete - If the specified instruction does not produce any side
735/// effects and all of its defs are dead, then it's safe to delete.
736static bool isSafeToDelete(MachineInstr *MI,
737                           const TargetInstrInfo *TII,
738                           SmallVector<unsigned, 4> &Kills) {
739  const TargetInstrDesc &TID = MI->getDesc();
740  if (TID.mayStore() || TID.isCall())
741    return false;
742  if (TID.isTerminator() || TID.hasUnmodeledSideEffects())
743    return false;
744
745  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
746    MachineOperand &MO = MI->getOperand(i);
747    if (!MO.isReg())
748      continue;
749    if (MO.isDef() && !MO.isDead())
750      return false;
751    if (MO.isUse() && MO.isKill())
752      Kills.push_back(MO.getReg());
753  }
754  return true;
755}
756
757/// canUpdateDeletedKills - Check if all the registers listed in Kills are
758/// killed by instructions in MBB preceding the current instruction at
759/// position Dist.  If so, return true and record information about the
760/// preceding kills in NewKills.
761bool TwoAddressInstructionPass::
762canUpdateDeletedKills(SmallVector<unsigned, 4> &Kills,
763                      SmallVector<NewKill, 4> &NewKills,
764                      MachineBasicBlock *MBB, unsigned Dist) {
765  while (!Kills.empty()) {
766    unsigned Kill = Kills.back();
767    Kills.pop_back();
768    if (TargetRegisterInfo::isPhysicalRegister(Kill))
769      return false;
770
771    MachineInstr *LastKill = FindLastUseInMBB(Kill, MBB, Dist);
772    if (!LastKill)
773      return false;
774
775    bool isModRef = LastKill->modifiesRegister(Kill);
776    NewKills.push_back(std::make_pair(std::make_pair(Kill, isModRef),
777                                      LastKill));
778  }
779  return true;
780}
781
782/// DeleteUnusedInstr - If an instruction with a tied register operand can
783/// be safely deleted, just delete it.
784bool
785TwoAddressInstructionPass::DeleteUnusedInstr(MachineBasicBlock::iterator &mi,
786                                             MachineBasicBlock::iterator &nmi,
787                                             MachineFunction::iterator &mbbi,
788                                             unsigned Dist) {
789  // Check if the instruction has no side effects and if all its defs are dead.
790  SmallVector<unsigned, 4> Kills;
791  if (!isSafeToDelete(mi, TII, Kills))
792    return false;
793
794  // If this instruction kills some virtual registers, we need to
795  // update the kill information. If it's not possible to do so,
796  // then bail out.
797  SmallVector<NewKill, 4> NewKills;
798  if (!canUpdateDeletedKills(Kills, NewKills, &*mbbi, Dist))
799    return false;
800
801  if (LV) {
802    while (!NewKills.empty()) {
803      MachineInstr *NewKill = NewKills.back().second;
804      unsigned Kill = NewKills.back().first.first;
805      bool isDead = NewKills.back().first.second;
806      NewKills.pop_back();
807      if (LV->removeVirtualRegisterKilled(Kill, mi)) {
808        if (isDead)
809          LV->addVirtualRegisterDead(Kill, NewKill);
810        else
811          LV->addVirtualRegisterKilled(Kill, NewKill);
812      }
813    }
814  }
815
816  mbbi->erase(mi); // Nuke the old inst.
817  mi = nmi;
818  return true;
819}
820
821/// TryInstructionTransform - For the case where an instruction has a single
822/// pair of tied register operands, attempt some transformations that may
823/// either eliminate the tied operands or improve the opportunities for
824/// coalescing away the register copy.  Returns true if the tied operands
825/// are eliminated altogether.
826bool TwoAddressInstructionPass::
827TryInstructionTransform(MachineBasicBlock::iterator &mi,
828                        MachineBasicBlock::iterator &nmi,
829                        MachineFunction::iterator &mbbi,
830                        unsigned SrcIdx, unsigned DstIdx, unsigned Dist) {
831  const TargetInstrDesc &TID = mi->getDesc();
832  unsigned regA = mi->getOperand(DstIdx).getReg();
833  unsigned regB = mi->getOperand(SrcIdx).getReg();
834
835  assert(TargetRegisterInfo::isVirtualRegister(regB) &&
836         "cannot make instruction into two-address form");
837
838  // If regA is dead and the instruction can be deleted, just delete
839  // it so it doesn't clobber regB.
840  bool regBKilled = isKilled(*mi, regB, MRI, TII);
841  if (!regBKilled && mi->getOperand(DstIdx).isDead() &&
842      DeleteUnusedInstr(mi, nmi, mbbi, Dist)) {
843    ++NumDeletes;
844    return true; // Done with this instruction.
845  }
846
847  // Check if it is profitable to commute the operands.
848  unsigned SrcOp1, SrcOp2;
849  unsigned regC = 0;
850  unsigned regCIdx = ~0U;
851  bool TryCommute = false;
852  bool AggressiveCommute = false;
853  if (TID.isCommutable() && mi->getNumOperands() >= 3 &&
854      TII->findCommutedOpIndices(mi, SrcOp1, SrcOp2)) {
855    if (SrcIdx == SrcOp1)
856      regCIdx = SrcOp2;
857    else if (SrcIdx == SrcOp2)
858      regCIdx = SrcOp1;
859
860    if (regCIdx != ~0U) {
861      regC = mi->getOperand(regCIdx).getReg();
862      if (!regBKilled && isKilled(*mi, regC, MRI, TII))
863        // If C dies but B does not, swap the B and C operands.
864        // This makes the live ranges of A and C joinable.
865        TryCommute = true;
866      else if (isProfitableToCommute(regB, regC, mi, mbbi, Dist)) {
867        TryCommute = true;
868        AggressiveCommute = true;
869      }
870    }
871  }
872
873  // If it's profitable to commute, try to do so.
874  if (TryCommute && CommuteInstruction(mi, mbbi, regB, regC, Dist)) {
875    ++NumCommuted;
876    if (AggressiveCommute)
877      ++NumAggrCommuted;
878    return false;
879  }
880
881  if (TID.isConvertibleTo3Addr()) {
882    // This instruction is potentially convertible to a true
883    // three-address instruction.  Check if it is profitable.
884    if (!regBKilled || isProfitableToConv3Addr(regA)) {
885      // Try to convert it.
886      if (ConvertInstTo3Addr(mi, nmi, mbbi, regB, Dist)) {
887        ++NumConvertedTo3Addr;
888        return true; // Done with this instruction.
889      }
890    }
891  }
892  return false;
893}
894
895/// runOnMachineFunction - Reduce two-address instructions to two operands.
896///
897bool TwoAddressInstructionPass::runOnMachineFunction(MachineFunction &MF) {
898  DEBUG(dbgs() << "Machine Function\n");
899  const TargetMachine &TM = MF.getTarget();
900  MRI = &MF.getRegInfo();
901  TII = TM.getInstrInfo();
902  TRI = TM.getRegisterInfo();
903  LV = getAnalysisIfAvailable<LiveVariables>();
904  AA = &getAnalysis<AliasAnalysis>();
905
906  bool MadeChange = false;
907
908  DEBUG(dbgs() << "********** REWRITING TWO-ADDR INSTRS **********\n");
909  DEBUG(dbgs() << "********** Function: "
910        << MF.getFunction()->getName() << '\n');
911
912  // ReMatRegs - Keep track of the registers whose def's are remat'ed.
913  BitVector ReMatRegs;
914  ReMatRegs.resize(MRI->getLastVirtReg()+1);
915
916  typedef DenseMap<unsigned, SmallVector<std::pair<unsigned, unsigned>, 4> >
917    TiedOperandMap;
918  TiedOperandMap TiedOperands(4);
919
920  SmallPtrSet<MachineInstr*, 8> Processed;
921  for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
922       mbbi != mbbe; ++mbbi) {
923    unsigned Dist = 0;
924    DistanceMap.clear();
925    SrcRegMap.clear();
926    DstRegMap.clear();
927    Processed.clear();
928    for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
929         mi != me; ) {
930      MachineBasicBlock::iterator nmi = llvm::next(mi);
931      const TargetInstrDesc &TID = mi->getDesc();
932      bool FirstTied = true;
933
934      DistanceMap.insert(std::make_pair(mi, ++Dist));
935
936      ProcessCopy(&*mi, &*mbbi, Processed);
937
938      // First scan through all the tied register uses in this instruction
939      // and record a list of pairs of tied operands for each register.
940      unsigned NumOps = (mi->getOpcode() == TargetInstrInfo::INLINEASM)
941        ? mi->getNumOperands() : TID.getNumOperands();
942      for (unsigned SrcIdx = 0; SrcIdx < NumOps; ++SrcIdx) {
943        unsigned DstIdx = 0;
944        if (!mi->isRegTiedToDefOperand(SrcIdx, &DstIdx))
945          continue;
946
947        if (FirstTied) {
948          FirstTied = false;
949          ++NumTwoAddressInstrs;
950          DEBUG(dbgs() << '\t' << *mi);
951        }
952
953        assert(mi->getOperand(SrcIdx).isReg() &&
954               mi->getOperand(SrcIdx).getReg() &&
955               mi->getOperand(SrcIdx).isUse() &&
956               "two address instruction invalid");
957
958        unsigned regB = mi->getOperand(SrcIdx).getReg();
959        TiedOperandMap::iterator OI = TiedOperands.find(regB);
960        if (OI == TiedOperands.end()) {
961          SmallVector<std::pair<unsigned, unsigned>, 4> TiedPair;
962          OI = TiedOperands.insert(std::make_pair(regB, TiedPair)).first;
963        }
964        OI->second.push_back(std::make_pair(SrcIdx, DstIdx));
965      }
966
967      // Now iterate over the information collected above.
968      for (TiedOperandMap::iterator OI = TiedOperands.begin(),
969             OE = TiedOperands.end(); OI != OE; ++OI) {
970        SmallVector<std::pair<unsigned, unsigned>, 4> &TiedPairs = OI->second;
971
972        // If the instruction has a single pair of tied operands, try some
973        // transformations that may either eliminate the tied operands or
974        // improve the opportunities for coalescing away the register copy.
975        if (TiedOperands.size() == 1 && TiedPairs.size() == 1) {
976          unsigned SrcIdx = TiedPairs[0].first;
977          unsigned DstIdx = TiedPairs[0].second;
978
979          // If the registers are already equal, nothing needs to be done.
980          if (mi->getOperand(SrcIdx).getReg() ==
981              mi->getOperand(DstIdx).getReg())
982            break; // Done with this instruction.
983
984          if (TryInstructionTransform(mi, nmi, mbbi, SrcIdx, DstIdx, Dist))
985            break; // The tied operands have been eliminated.
986        }
987
988        bool RemovedKillFlag = false;
989        bool AllUsesCopied = true;
990        unsigned LastCopiedReg = 0;
991        unsigned regB = OI->first;
992        for (unsigned tpi = 0, tpe = TiedPairs.size(); tpi != tpe; ++tpi) {
993          unsigned SrcIdx = TiedPairs[tpi].first;
994          unsigned DstIdx = TiedPairs[tpi].second;
995          unsigned regA = mi->getOperand(DstIdx).getReg();
996          // Grab regB from the instruction because it may have changed if the
997          // instruction was commuted.
998          regB = mi->getOperand(SrcIdx).getReg();
999
1000          if (regA == regB) {
1001            // The register is tied to multiple destinations (or else we would
1002            // not have continued this far), but this use of the register
1003            // already matches the tied destination.  Leave it.
1004            AllUsesCopied = false;
1005            continue;
1006          }
1007          LastCopiedReg = regA;
1008
1009          assert(TargetRegisterInfo::isVirtualRegister(regB) &&
1010                 "cannot make instruction into two-address form");
1011
1012#ifndef NDEBUG
1013          // First, verify that we don't have a use of "a" in the instruction
1014          // (a = b + a for example) because our transformation will not
1015          // work. This should never occur because we are in SSA form.
1016          for (unsigned i = 0; i != mi->getNumOperands(); ++i)
1017            assert(i == DstIdx ||
1018                   !mi->getOperand(i).isReg() ||
1019                   mi->getOperand(i).getReg() != regA);
1020#endif
1021
1022          // Emit a copy or rematerialize the definition.
1023          const TargetRegisterClass *rc = MRI->getRegClass(regB);
1024          MachineInstr *DefMI = MRI->getVRegDef(regB);
1025          // If it's safe and profitable, remat the definition instead of
1026          // copying it.
1027          if (DefMI &&
1028              DefMI->getDesc().isAsCheapAsAMove() &&
1029              DefMI->isSafeToReMat(TII, regB, AA) &&
1030              isProfitableToReMat(regB, rc, mi, DefMI, mbbi, Dist)){
1031            DEBUG(dbgs() << "2addr: REMATTING : " << *DefMI << "\n");
1032            unsigned regASubIdx = mi->getOperand(DstIdx).getSubReg();
1033            TII->reMaterialize(*mbbi, mi, regA, regASubIdx, DefMI, TRI);
1034            ReMatRegs.set(regB);
1035            ++NumReMats;
1036          } else {
1037            bool Emitted = TII->copyRegToReg(*mbbi, mi, regA, regB, rc, rc);
1038            (void)Emitted;
1039            assert(Emitted && "Unable to issue a copy instruction!\n");
1040          }
1041
1042          MachineBasicBlock::iterator prevMI = prior(mi);
1043          // Update DistanceMap.
1044          DistanceMap.insert(std::make_pair(prevMI, Dist));
1045          DistanceMap[mi] = ++Dist;
1046
1047          DEBUG(dbgs() << "\t\tprepend:\t" << *prevMI);
1048
1049          MachineOperand &MO = mi->getOperand(SrcIdx);
1050          assert(MO.isReg() && MO.getReg() == regB && MO.isUse() &&
1051                 "inconsistent operand info for 2-reg pass");
1052          if (MO.isKill()) {
1053            MO.setIsKill(false);
1054            RemovedKillFlag = true;
1055          }
1056          MO.setReg(regA);
1057        }
1058
1059        if (AllUsesCopied) {
1060          // Replace other (un-tied) uses of regB with LastCopiedReg.
1061          for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1062            MachineOperand &MO = mi->getOperand(i);
1063            if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1064              if (MO.isKill()) {
1065                MO.setIsKill(false);
1066                RemovedKillFlag = true;
1067              }
1068              MO.setReg(LastCopiedReg);
1069            }
1070          }
1071
1072          // Update live variables for regB.
1073          if (RemovedKillFlag && LV && LV->getVarInfo(regB).removeKill(mi))
1074            LV->addVirtualRegisterKilled(regB, prior(mi));
1075
1076        } else if (RemovedKillFlag) {
1077          // Some tied uses of regB matched their destination registers, so
1078          // regB is still used in this instruction, but a kill flag was
1079          // removed from a different tied use of regB, so now we need to add
1080          // a kill flag to one of the remaining uses of regB.
1081          for (unsigned i = 0, e = mi->getNumOperands(); i != e; ++i) {
1082            MachineOperand &MO = mi->getOperand(i);
1083            if (MO.isReg() && MO.getReg() == regB && MO.isUse()) {
1084              MO.setIsKill(true);
1085              break;
1086            }
1087          }
1088        }
1089
1090        MadeChange = true;
1091
1092        DEBUG(dbgs() << "\t\trewrite to:\t" << *mi);
1093      }
1094
1095      // Clear TiedOperands here instead of at the top of the loop
1096      // since most instructions do not have tied operands.
1097      TiedOperands.clear();
1098      mi = nmi;
1099    }
1100  }
1101
1102  // Some remat'ed instructions are dead.
1103  int VReg = ReMatRegs.find_first();
1104  while (VReg != -1) {
1105    if (MRI->use_empty(VReg)) {
1106      MachineInstr *DefMI = MRI->getVRegDef(VReg);
1107      DefMI->eraseFromParent();
1108    }
1109    VReg = ReMatRegs.find_next(VReg);
1110  }
1111
1112  return MadeChange;
1113}
1114