Reapply r110396, with fixes to appease the Linux buildbot gods.
[oota-llvm.git] / lib / CodeGen / LowerSubregs.cpp
1 //===-- LowerSubregs.cpp - Subregister Lowering 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 defines a MachineFunction pass which runs after register
11 // allocation that turns subreg insert/extract instructions into register
12 // copies, as needed. This ensures correct codegen even if the coalescer
13 // isn't able to remove all subreg instructions.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #define DEBUG_TYPE "lowersubregs"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/Function.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/Target/TargetRegisterInfo.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm;
30
31 namespace {
32   struct LowerSubregsInstructionPass : public MachineFunctionPass {
33   private:
34     const TargetRegisterInfo *TRI;
35     const TargetInstrInfo *TII;
36
37   public:
38     static char ID; // Pass identification, replacement for typeid
39     LowerSubregsInstructionPass() : MachineFunctionPass(ID) {}
40     
41     const char *getPassName() const {
42       return "Subregister lowering instruction pass";
43     }
44
45     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46       AU.setPreservesCFG();
47       AU.addPreservedID(MachineLoopInfoID);
48       AU.addPreservedID(MachineDominatorsID);
49       MachineFunctionPass::getAnalysisUsage(AU);
50     }
51
52     /// runOnMachineFunction - pass entry point
53     bool runOnMachineFunction(MachineFunction&);
54
55   private:
56     bool LowerSubregToReg(MachineInstr *MI);
57     bool LowerCopy(MachineInstr *MI);
58
59     void TransferDeadFlag(MachineInstr *MI, unsigned DstReg,
60                           const TargetRegisterInfo *TRI);
61     void TransferKillFlag(MachineInstr *MI, unsigned SrcReg,
62                           const TargetRegisterInfo *TRI,
63                           bool AddIfNotFound = false);
64     void TransferImplicitDefs(MachineInstr *MI);
65   };
66
67   char LowerSubregsInstructionPass::ID = 0;
68 }
69
70 FunctionPass *llvm::createLowerSubregsPass() { 
71   return new LowerSubregsInstructionPass(); 
72 }
73
74 /// TransferDeadFlag - MI is a pseudo-instruction with DstReg dead,
75 /// and the lowered replacement instructions immediately precede it.
76 /// Mark the replacement instructions with the dead flag.
77 void
78 LowerSubregsInstructionPass::TransferDeadFlag(MachineInstr *MI,
79                                               unsigned DstReg,
80                                               const TargetRegisterInfo *TRI) {
81   for (MachineBasicBlock::iterator MII =
82         prior(MachineBasicBlock::iterator(MI)); ; --MII) {
83     if (MII->addRegisterDead(DstReg, TRI))
84       break;
85     assert(MII != MI->getParent()->begin() &&
86            "copyPhysReg output doesn't reference destination register!");
87   }
88 }
89
90 /// TransferKillFlag - MI is a pseudo-instruction with SrcReg killed,
91 /// and the lowered replacement instructions immediately precede it.
92 /// Mark the replacement instructions with the kill flag.
93 void
94 LowerSubregsInstructionPass::TransferKillFlag(MachineInstr *MI,
95                                               unsigned SrcReg,
96                                               const TargetRegisterInfo *TRI,
97                                               bool AddIfNotFound) {
98   for (MachineBasicBlock::iterator MII =
99         prior(MachineBasicBlock::iterator(MI)); ; --MII) {
100     if (MII->addRegisterKilled(SrcReg, TRI, AddIfNotFound))
101       break;
102     assert(MII != MI->getParent()->begin() &&
103            "copyPhysReg output doesn't reference source register!");
104   }
105 }
106
107 /// TransferImplicitDefs - MI is a pseudo-instruction, and the lowered
108 /// replacement instructions immediately precede it.  Copy any implicit-def
109 /// operands from MI to the replacement instruction.
110 void
111 LowerSubregsInstructionPass::TransferImplicitDefs(MachineInstr *MI) {
112   MachineBasicBlock::iterator CopyMI = MI;
113   --CopyMI;
114
115   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
116     MachineOperand &MO = MI->getOperand(i);
117     if (!MO.isReg() || !MO.isImplicit() || MO.isUse())
118       continue;
119     CopyMI->addOperand(MachineOperand::CreateReg(MO.getReg(), true, true));
120   }
121 }
122
123 bool LowerSubregsInstructionPass::LowerSubregToReg(MachineInstr *MI) {
124   MachineBasicBlock *MBB = MI->getParent();
125   assert((MI->getOperand(0).isReg() && MI->getOperand(0).isDef()) &&
126          MI->getOperand(1).isImm() &&
127          (MI->getOperand(2).isReg() && MI->getOperand(2).isUse()) &&
128           MI->getOperand(3).isImm() && "Invalid subreg_to_reg");
129
130   unsigned DstReg  = MI->getOperand(0).getReg();
131   unsigned InsReg  = MI->getOperand(2).getReg();
132   assert(!MI->getOperand(2).getSubReg() && "SubIdx on physreg?");
133   unsigned SubIdx  = MI->getOperand(3).getImm();
134
135   assert(SubIdx != 0 && "Invalid index for insert_subreg");
136   unsigned DstSubReg = TRI->getSubReg(DstReg, SubIdx);
137
138   assert(TargetRegisterInfo::isPhysicalRegister(DstReg) &&
139          "Insert destination must be in a physical register");
140   assert(TargetRegisterInfo::isPhysicalRegister(InsReg) &&
141          "Inserted value must be in a physical register");
142
143   DEBUG(dbgs() << "subreg: CONVERTING: " << *MI);
144
145   if (DstSubReg == InsReg) {
146     // No need to insert an identify copy instruction.
147     // Watch out for case like this:
148     // %RAX<def> = SUBREG_TO_REG 0, %EAX<kill>, 3
149     // We must leave %RAX live.
150     if (DstReg != InsReg) {
151       MI->setDesc(TII->get(TargetOpcode::KILL));
152       MI->RemoveOperand(3);     // SubIdx
153       MI->RemoveOperand(1);     // Imm
154       DEBUG(dbgs() << "subreg: replace by: " << *MI);
155       return true;
156     }
157     DEBUG(dbgs() << "subreg: eliminated!");
158   } else {
159     TII->copyPhysReg(*MBB, MI, MI->getDebugLoc(), DstSubReg, InsReg,
160                      MI->getOperand(2).isKill());
161     // Transfer the kill/dead flags, if needed.
162     if (MI->getOperand(0).isDead())
163       TransferDeadFlag(MI, DstSubReg, TRI);
164     DEBUG({
165         MachineBasicBlock::iterator dMI = MI;
166         dbgs() << "subreg: " << *(--dMI);
167       });
168   }
169
170   DEBUG(dbgs() << '\n');
171   MBB->erase(MI);
172   return true;
173 }
174
175 bool LowerSubregsInstructionPass::LowerCopy(MachineInstr *MI) {
176   MachineOperand &DstMO = MI->getOperand(0);
177   MachineOperand &SrcMO = MI->getOperand(1);
178
179   if (SrcMO.getReg() == DstMO.getReg()) {
180     DEBUG(dbgs() << "identity copy: " << *MI);
181     // No need to insert an identity copy instruction, but replace with a KILL
182     // if liveness is changed.
183     if (DstMO.isDead() || SrcMO.isUndef() || MI->getNumOperands() > 2) {
184       // We must make sure the super-register gets killed. Replace the
185       // instruction with KILL.
186       MI->setDesc(TII->get(TargetOpcode::KILL));
187       DEBUG(dbgs() << "replaced by:   " << *MI);
188       return true;
189     }
190     // Vanilla identity copy.
191     MI->eraseFromParent();
192     return true;
193   }
194
195   DEBUG(dbgs() << "real copy:   " << *MI);
196   TII->copyPhysReg(*MI->getParent(), MI, MI->getDebugLoc(),
197                    DstMO.getReg(), SrcMO.getReg(), SrcMO.isKill());
198
199   if (DstMO.isDead())
200     TransferDeadFlag(MI, DstMO.getReg(), TRI);
201   if (MI->getNumOperands() > 2)
202     TransferImplicitDefs(MI);
203   DEBUG({
204     MachineBasicBlock::iterator dMI = MI;
205     dbgs() << "replaced by: " << *(--dMI);
206   });
207   MI->eraseFromParent();
208   return true;
209 }
210
211 /// runOnMachineFunction - Reduce subregister inserts and extracts to register
212 /// copies.
213 ///
214 bool LowerSubregsInstructionPass::runOnMachineFunction(MachineFunction &MF) {
215   DEBUG(dbgs() << "Machine Function\n"  
216                << "********** LOWERING SUBREG INSTRS **********\n"
217                << "********** Function: " 
218                << MF.getFunction()->getName() << '\n');
219   TRI = MF.getTarget().getRegisterInfo();
220   TII = MF.getTarget().getInstrInfo();
221
222   bool MadeChange = false;
223
224   for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end();
225        mbbi != mbbe; ++mbbi) {
226     for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end();
227          mi != me;) {
228       MachineBasicBlock::iterator nmi = llvm::next(mi);
229       MachineInstr *MI = mi;
230       assert(!MI->isInsertSubreg() && "INSERT_SUBREG should no longer appear");
231       assert(MI->getOpcode() != TargetOpcode::EXTRACT_SUBREG &&
232              "EXTRACT_SUBREG should no longer appear");
233       if (MI->isSubregToReg()) {
234         MadeChange |= LowerSubregToReg(MI);
235       } else if (MI->isCopy()) {
236         MadeChange |= LowerCopy(MI);
237       }
238       mi = nmi;
239     }
240   }
241
242   return MadeChange;
243 }