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