Deleted Added
full compact
MachineLICM.cpp (198090) MachineLICM.cpp (198892)
1//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion 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 pass performs loop invariant code motion on machine instructions. We
11// attempt to remove as much code from the body of a loop as possible.
12//
13// This pass does not attempt to throttle itself to limit register pressure.
14// The register allocation phases are expected to perform rematerialization
15// to recover when register pressure is high.
16//
17// This pass is not intended to be a replacement or a complete alternative
18// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
19// constructs that are not exposed before lowering and instruction selection.
20//
21//===----------------------------------------------------------------------===//
22
23#define DEBUG_TYPE "machine-licm"
24#include "llvm/CodeGen/Passes.h"
25#include "llvm/CodeGen/MachineDominators.h"
26#include "llvm/CodeGen/MachineLoopInfo.h"
1//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion 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 pass performs loop invariant code motion on machine instructions. We
11// attempt to remove as much code from the body of a loop as possible.
12//
13// This pass does not attempt to throttle itself to limit register pressure.
14// The register allocation phases are expected to perform rematerialization
15// to recover when register pressure is high.
16//
17// This pass is not intended to be a replacement or a complete alternative
18// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
19// constructs that are not exposed before lowering and instruction selection.
20//
21//===----------------------------------------------------------------------===//
22
23#define DEBUG_TYPE "machine-licm"
24#include "llvm/CodeGen/Passes.h"
25#include "llvm/CodeGen/MachineDominators.h"
26#include "llvm/CodeGen/MachineLoopInfo.h"
27#include "llvm/CodeGen/MachineMemOperand.h"
27#include "llvm/CodeGen/MachineRegisterInfo.h"
28#include "llvm/CodeGen/MachineRegisterInfo.h"
29#include "llvm/CodeGen/PseudoSourceValue.h"
28#include "llvm/Target/TargetRegisterInfo.h"
29#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
31#include "llvm/Analysis/AliasAnalysis.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/Statistic.h"
30#include "llvm/Target/TargetRegisterInfo.h"
31#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetMachine.h"
33#include "llvm/Analysis/AliasAnalysis.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/Statistic.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/raw_ostream.h"
37
38using namespace llvm;
39
40STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
41STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
42
43namespace {
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/raw_ostream.h"
38
39using namespace llvm;
40
41STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
42STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
43
44namespace {
44 class VISIBILITY_HIDDEN MachineLICM : public MachineFunctionPass {
45 class MachineLICM : public MachineFunctionPass {
45 const TargetMachine *TM;
46 const TargetInstrInfo *TII;
47 const TargetRegisterInfo *TRI;
48 BitVector AllocatableSet;
49
50 // Various analyses that we use...
51 AliasAnalysis *AA; // Alias analysis info.
52 MachineLoopInfo *LI; // Current MachineLoopInfo
53 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
54 MachineRegisterInfo *RegInfo; // Machine register information
55
56 // State that is updated as we process loops
57 bool Changed; // True if a loop is changed.
46 const TargetMachine *TM;
47 const TargetInstrInfo *TII;
48 const TargetRegisterInfo *TRI;
49 BitVector AllocatableSet;
50
51 // Various analyses that we use...
52 AliasAnalysis *AA; // Alias analysis info.
53 MachineLoopInfo *LI; // Current MachineLoopInfo
54 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
55 MachineRegisterInfo *RegInfo; // Machine register information
56
57 // State that is updated as we process loops
58 bool Changed; // True if a loop is changed.
59 bool FirstInLoop; // True if it's the first LICM in the loop.
58 MachineLoop *CurLoop; // The current loop we are working on.
59 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
60
60 MachineLoop *CurLoop; // The current loop we are working on.
61 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
62
61 // For each BB and opcode pair, keep a list of hoisted instructions.
62 DenseMap<std::pair<unsigned, unsigned>,
63 std::vector<const MachineInstr*> > CSEMap;
63 // For each opcode, keep a list of potentail CSE instructions.
64 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
64 public:
65 static char ID; // Pass identification, replacement for typeid
66 MachineLICM() : MachineFunctionPass(&ID) {}
67
68 virtual bool runOnMachineFunction(MachineFunction &MF);
69
70 const char *getPassName() const { return "Machine Instruction LICM"; }
71
72 // FIXME: Loop preheaders?
73 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
74 AU.setPreservesCFG();
75 AU.addRequired<MachineLoopInfo>();
76 AU.addRequired<MachineDominatorTree>();
77 AU.addRequired<AliasAnalysis>();
78 AU.addPreserved<MachineLoopInfo>();
79 AU.addPreserved<MachineDominatorTree>();
80 MachineFunctionPass::getAnalysisUsage(AU);
81 }
82
83 virtual void releaseMemory() {
84 CSEMap.clear();
85 }
86
87 private:
88 /// IsLoopInvariantInst - Returns true if the instruction is loop
89 /// invariant. I.e., all virtual register operands are defined outside of
90 /// the loop, physical registers aren't accessed (explicitly or implicitly),
91 /// and the instruction is hoistable.
92 ///
93 bool IsLoopInvariantInst(MachineInstr &I);
94
95 /// IsProfitableToHoist - Return true if it is potentially profitable to
96 /// hoist the given loop invariant.
97 bool IsProfitableToHoist(MachineInstr &MI);
98
99 /// HoistRegion - Walk the specified region of the CFG (defined by all
100 /// blocks dominated by the specified block, and that are in the current
101 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
102 /// visit definitions before uses, allowing us to hoist a loop body in one
103 /// pass without iteration.
104 ///
105 void HoistRegion(MachineDomTreeNode *N);
106
65 public:
66 static char ID; // Pass identification, replacement for typeid
67 MachineLICM() : MachineFunctionPass(&ID) {}
68
69 virtual bool runOnMachineFunction(MachineFunction &MF);
70
71 const char *getPassName() const { return "Machine Instruction LICM"; }
72
73 // FIXME: Loop preheaders?
74 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
75 AU.setPreservesCFG();
76 AU.addRequired<MachineLoopInfo>();
77 AU.addRequired<MachineDominatorTree>();
78 AU.addRequired<AliasAnalysis>();
79 AU.addPreserved<MachineLoopInfo>();
80 AU.addPreserved<MachineDominatorTree>();
81 MachineFunctionPass::getAnalysisUsage(AU);
82 }
83
84 virtual void releaseMemory() {
85 CSEMap.clear();
86 }
87
88 private:
89 /// IsLoopInvariantInst - Returns true if the instruction is loop
90 /// invariant. I.e., all virtual register operands are defined outside of
91 /// the loop, physical registers aren't accessed (explicitly or implicitly),
92 /// and the instruction is hoistable.
93 ///
94 bool IsLoopInvariantInst(MachineInstr &I);
95
96 /// IsProfitableToHoist - Return true if it is potentially profitable to
97 /// hoist the given loop invariant.
98 bool IsProfitableToHoist(MachineInstr &MI);
99
100 /// HoistRegion - Walk the specified region of the CFG (defined by all
101 /// blocks dominated by the specified block, and that are in the current
102 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
103 /// visit definitions before uses, allowing us to hoist a loop body in one
104 /// pass without iteration.
105 ///
106 void HoistRegion(MachineDomTreeNode *N);
107
108 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
109 /// the load itself could be hoisted. Return the unfolded and hoistable
110 /// load, or null if the load couldn't be unfolded or if it wouldn't
111 /// be hoistable.
112 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
113
107 /// Hoist - When an instruction is found to only use loop invariant operands
108 /// that is safe to hoist, this instruction is called to do the dirty work.
109 ///
114 /// Hoist - When an instruction is found to only use loop invariant operands
115 /// that is safe to hoist, this instruction is called to do the dirty work.
116 ///
110 void Hoist(MachineInstr &MI);
117 void Hoist(MachineInstr *MI);
118
119 /// InitCSEMap - Initialize the CSE map with instructions that are in the
120 /// current loop preheader that may become duplicates of instructions that
121 /// are hoisted out of the loop.
122 void InitCSEMap(MachineBasicBlock *BB);
111 };
112} // end anonymous namespace
113
114char MachineLICM::ID = 0;
115static RegisterPass<MachineLICM>
116X("machinelicm", "Machine Loop Invariant Code Motion");
117
118FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
119
120/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
121/// loop that has a preheader.
122static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
123 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
124 if (L->getLoopPreheader())
125 return false;
126 return true;
127}
128
129/// Hoist expressions out of the specified loop. Note, alias info for inner loop
130/// is not preserved so it is not a good idea to run LICM multiple times on one
131/// loop.
132///
133bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
134 DEBUG(errs() << "******** Machine LICM ********\n");
135
123 };
124} // end anonymous namespace
125
126char MachineLICM::ID = 0;
127static RegisterPass<MachineLICM>
128X("machinelicm", "Machine Loop Invariant Code Motion");
129
130FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
131
132/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
133/// loop that has a preheader.
134static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
135 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
136 if (L->getLoopPreheader())
137 return false;
138 return true;
139}
140
141/// Hoist expressions out of the specified loop. Note, alias info for inner loop
142/// is not preserved so it is not a good idea to run LICM multiple times on one
143/// loop.
144///
145bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
146 DEBUG(errs() << "******** Machine LICM ********\n");
147
136 Changed = false;
148 Changed = FirstInLoop = false;
137 TM = &MF.getTarget();
138 TII = TM->getInstrInfo();
139 TRI = TM->getRegisterInfo();
140 RegInfo = &MF.getRegInfo();
141 AllocatableSet = TRI->getAllocatableSet(MF);
142
143 // Get our Loop information...
144 LI = &getAnalysis<MachineLoopInfo>();
145 DT = &getAnalysis<MachineDominatorTree>();
146 AA = &getAnalysis<AliasAnalysis>();
147
149 TM = &MF.getTarget();
150 TII = TM->getInstrInfo();
151 TRI = TM->getRegisterInfo();
152 RegInfo = &MF.getRegInfo();
153 AllocatableSet = TRI->getAllocatableSet(MF);
154
155 // Get our Loop information...
156 LI = &getAnalysis<MachineLoopInfo>();
157 DT = &getAnalysis<MachineDominatorTree>();
158 AA = &getAnalysis<AliasAnalysis>();
159
148 for (MachineLoopInfo::iterator
149 I = LI->begin(), E = LI->end(); I != E; ++I) {
160 for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
150 CurLoop = *I;
151
152 // Only visit outer-most preheader-sporting loops.
153 if (!LoopIsOuterMostWithPreheader(CurLoop))
154 continue;
155
156 // Determine the block to which to hoist instructions. If we can't find a
157 // suitable loop preheader, we can't do any hoisting.
158 //
159 // FIXME: We are only hoisting if the basic block coming into this loop
160 // has only one successor. This isn't the case in general because we haven't
161 // broken critical edges or added preheaders.
162 CurPreheader = CurLoop->getLoopPreheader();
163 if (!CurPreheader)
164 continue;
165
161 CurLoop = *I;
162
163 // Only visit outer-most preheader-sporting loops.
164 if (!LoopIsOuterMostWithPreheader(CurLoop))
165 continue;
166
167 // Determine the block to which to hoist instructions. If we can't find a
168 // suitable loop preheader, we can't do any hoisting.
169 //
170 // FIXME: We are only hoisting if the basic block coming into this loop
171 // has only one successor. This isn't the case in general because we haven't
172 // broken critical edges or added preheaders.
173 CurPreheader = CurLoop->getLoopPreheader();
174 if (!CurPreheader)
175 continue;
176
177 // CSEMap is initialized for loop header when the first instruction is
178 // being hoisted.
179 FirstInLoop = true;
166 HoistRegion(DT->getNode(CurLoop->getHeader()));
180 HoistRegion(DT->getNode(CurLoop->getHeader()));
181 CSEMap.clear();
167 }
168
169 return Changed;
170}
171
172/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
173/// dominated by the specified block, and that are in the current loop) in depth
174/// first order w.r.t the DominatorTree. This allows us to visit definitions
175/// before uses, allowing us to hoist a loop body in one pass without iteration.
176///
177void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
178 assert(N != 0 && "Null dominator tree node?");
179 MachineBasicBlock *BB = N->getBlock();
180
181 // If this subregion is not in the top level loop at all, exit.
182 if (!CurLoop->contains(BB)) return;
183
184 for (MachineBasicBlock::iterator
185 MII = BB->begin(), E = BB->end(); MII != E; ) {
186 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
182 }
183
184 return Changed;
185}
186
187/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
188/// dominated by the specified block, and that are in the current loop) in depth
189/// first order w.r.t the DominatorTree. This allows us to visit definitions
190/// before uses, allowing us to hoist a loop body in one pass without iteration.
191///
192void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
193 assert(N != 0 && "Null dominator tree node?");
194 MachineBasicBlock *BB = N->getBlock();
195
196 // If this subregion is not in the top level loop at all, exit.
197 if (!CurLoop->contains(BB)) return;
198
199 for (MachineBasicBlock::iterator
200 MII = BB->begin(), E = BB->end(); MII != E; ) {
201 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
187 MachineInstr &MI = *MII;
188
189 Hoist(MI);
190
202 Hoist(&*MII);
191 MII = NextMII;
192 }
193
194 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
195
196 for (unsigned I = 0, E = Children.size(); I != E; ++I)
197 HoistRegion(Children[I]);
198}
199
200/// IsLoopInvariantInst - Returns true if the instruction is loop
201/// invariant. I.e., all virtual register operands are defined outside of the
202/// loop, physical registers aren't accessed explicitly, and there are no side
203/// effects that aren't captured by the operands or other flags.
204///
205bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
206 const TargetInstrDesc &TID = I.getDesc();
207
208 // Ignore stuff that we obviously can't hoist.
209 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
210 TID.hasUnmodeledSideEffects())
211 return false;
212
213 if (TID.mayLoad()) {
214 // Okay, this instruction does a load. As a refinement, we allow the target
215 // to decide whether the loaded value is actually a constant. If so, we can
216 // actually use it as a load.
217 if (!I.isInvariantLoad(AA))
218 // FIXME: we should be able to sink loads with no other side effects if
219 // there is nothing that can change memory from here until the end of
220 // block. This is a trivial form of alias analysis.
221 return false;
222 }
223
224 DEBUG({
225 errs() << "--- Checking if we can hoist " << I;
226 if (I.getDesc().getImplicitUses()) {
227 errs() << " * Instruction has implicit uses:\n";
228
229 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
230 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
231 *ImpUses; ++ImpUses)
232 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
233 }
234
235 if (I.getDesc().getImplicitDefs()) {
236 errs() << " * Instruction has implicit defines:\n";
237
238 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
239 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
240 *ImpDefs; ++ImpDefs)
241 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
242 }
243 });
244
245 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
246 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
247 return false;
248 }
249
250 // The instruction is loop invariant if all of its operands are.
251 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
252 const MachineOperand &MO = I.getOperand(i);
253
254 if (!MO.isReg())
255 continue;
256
257 unsigned Reg = MO.getReg();
258 if (Reg == 0) continue;
259
260 // Don't hoist an instruction that uses or defines a physical register.
261 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
262 if (MO.isUse()) {
263 // If the physreg has no defs anywhere, it's just an ambient register
264 // and we can freely move its uses. Alternatively, if it's allocatable,
265 // it could get allocated to something with a def during allocation.
266 if (!RegInfo->def_empty(Reg))
267 return false;
268 if (AllocatableSet.test(Reg))
269 return false;
270 // Check for a def among the register's aliases too.
271 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
272 unsigned AliasReg = *Alias;
273 if (!RegInfo->def_empty(AliasReg))
274 return false;
275 if (AllocatableSet.test(AliasReg))
276 return false;
277 }
278 // Otherwise it's safe to move.
279 continue;
280 } else if (!MO.isDead()) {
281 // A def that isn't dead. We can't move it.
282 return false;
283 }
284 }
285
286 if (!MO.isUse())
287 continue;
288
289 assert(RegInfo->getVRegDef(Reg) &&
290 "Machine instr not mapped for this vreg?!");
291
292 // If the loop contains the definition of an operand, then the instruction
293 // isn't loop invariant.
294 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
295 return false;
296 }
297
298 // If we got this far, the instruction is loop invariant!
299 return true;
300}
301
302
303/// HasPHIUses - Return true if the specified register has any PHI use.
304static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
305 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
306 UE = RegInfo->use_end(); UI != UE; ++UI) {
307 MachineInstr *UseMI = &*UI;
308 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
309 return true;
310 }
311 return false;
312}
313
314/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
315/// the given loop invariant.
316bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
317 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
318 return false;
319
320 // FIXME: For now, only hoist re-materilizable instructions. LICM will
321 // increase register pressure. We want to make sure it doesn't increase
322 // spilling.
323 if (!TII->isTriviallyReMaterializable(&MI, AA))
324 return false;
325
326 // If result(s) of this instruction is used by PHIs, then don't hoist it.
327 // The presence of joins makes it difficult for current register allocator
328 // implementation to perform remat.
329 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
330 const MachineOperand &MO = MI.getOperand(i);
331 if (!MO.isReg() || !MO.isDef())
332 continue;
333 if (HasPHIUses(MO.getReg(), RegInfo))
334 return false;
335 }
336
337 return true;
338}
339
340static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
341 std::vector<const MachineInstr*> &PrevMIs,
342 MachineRegisterInfo *RegInfo) {
343 unsigned NumOps = MI->getNumOperands();
344 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
345 const MachineInstr *PrevMI = PrevMIs[i];
346 unsigned NumOps2 = PrevMI->getNumOperands();
347 if (NumOps != NumOps2)
348 continue;
349 bool IsSame = true;
350 for (unsigned j = 0; j != NumOps; ++j) {
351 const MachineOperand &MO = MI->getOperand(j);
352 if (MO.isReg() && MO.isDef()) {
353 if (RegInfo->getRegClass(MO.getReg()) !=
354 RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
355 IsSame = false;
356 break;
357 }
358 continue;
359 }
360 if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
361 IsSame = false;
362 break;
363 }
364 }
365 if (IsSame)
366 return PrevMI;
367 }
368 return 0;
369}
370
203 MII = NextMII;
204 }
205
206 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
207
208 for (unsigned I = 0, E = Children.size(); I != E; ++I)
209 HoistRegion(Children[I]);
210}
211
212/// IsLoopInvariantInst - Returns true if the instruction is loop
213/// invariant. I.e., all virtual register operands are defined outside of the
214/// loop, physical registers aren't accessed explicitly, and there are no side
215/// effects that aren't captured by the operands or other flags.
216///
217bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
218 const TargetInstrDesc &TID = I.getDesc();
219
220 // Ignore stuff that we obviously can't hoist.
221 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
222 TID.hasUnmodeledSideEffects())
223 return false;
224
225 if (TID.mayLoad()) {
226 // Okay, this instruction does a load. As a refinement, we allow the target
227 // to decide whether the loaded value is actually a constant. If so, we can
228 // actually use it as a load.
229 if (!I.isInvariantLoad(AA))
230 // FIXME: we should be able to sink loads with no other side effects if
231 // there is nothing that can change memory from here until the end of
232 // block. This is a trivial form of alias analysis.
233 return false;
234 }
235
236 DEBUG({
237 errs() << "--- Checking if we can hoist " << I;
238 if (I.getDesc().getImplicitUses()) {
239 errs() << " * Instruction has implicit uses:\n";
240
241 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
242 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
243 *ImpUses; ++ImpUses)
244 errs() << " -> " << TRI->getName(*ImpUses) << "\n";
245 }
246
247 if (I.getDesc().getImplicitDefs()) {
248 errs() << " * Instruction has implicit defines:\n";
249
250 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
251 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
252 *ImpDefs; ++ImpDefs)
253 errs() << " -> " << TRI->getName(*ImpDefs) << "\n";
254 }
255 });
256
257 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
258 DEBUG(errs() << "Cannot hoist with implicit defines or uses\n");
259 return false;
260 }
261
262 // The instruction is loop invariant if all of its operands are.
263 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
264 const MachineOperand &MO = I.getOperand(i);
265
266 if (!MO.isReg())
267 continue;
268
269 unsigned Reg = MO.getReg();
270 if (Reg == 0) continue;
271
272 // Don't hoist an instruction that uses or defines a physical register.
273 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
274 if (MO.isUse()) {
275 // If the physreg has no defs anywhere, it's just an ambient register
276 // and we can freely move its uses. Alternatively, if it's allocatable,
277 // it could get allocated to something with a def during allocation.
278 if (!RegInfo->def_empty(Reg))
279 return false;
280 if (AllocatableSet.test(Reg))
281 return false;
282 // Check for a def among the register's aliases too.
283 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
284 unsigned AliasReg = *Alias;
285 if (!RegInfo->def_empty(AliasReg))
286 return false;
287 if (AllocatableSet.test(AliasReg))
288 return false;
289 }
290 // Otherwise it's safe to move.
291 continue;
292 } else if (!MO.isDead()) {
293 // A def that isn't dead. We can't move it.
294 return false;
295 }
296 }
297
298 if (!MO.isUse())
299 continue;
300
301 assert(RegInfo->getVRegDef(Reg) &&
302 "Machine instr not mapped for this vreg?!");
303
304 // If the loop contains the definition of an operand, then the instruction
305 // isn't loop invariant.
306 if (CurLoop->contains(RegInfo->getVRegDef(Reg)->getParent()))
307 return false;
308 }
309
310 // If we got this far, the instruction is loop invariant!
311 return true;
312}
313
314
315/// HasPHIUses - Return true if the specified register has any PHI use.
316static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
317 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
318 UE = RegInfo->use_end(); UI != UE; ++UI) {
319 MachineInstr *UseMI = &*UI;
320 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
321 return true;
322 }
323 return false;
324}
325
326/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
327/// the given loop invariant.
328bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
329 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
330 return false;
331
332 // FIXME: For now, only hoist re-materilizable instructions. LICM will
333 // increase register pressure. We want to make sure it doesn't increase
334 // spilling.
335 if (!TII->isTriviallyReMaterializable(&MI, AA))
336 return false;
337
338 // If result(s) of this instruction is used by PHIs, then don't hoist it.
339 // The presence of joins makes it difficult for current register allocator
340 // implementation to perform remat.
341 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
342 const MachineOperand &MO = MI.getOperand(i);
343 if (!MO.isReg() || !MO.isDef())
344 continue;
345 if (HasPHIUses(MO.getReg(), RegInfo))
346 return false;
347 }
348
349 return true;
350}
351
352static const MachineInstr *LookForDuplicate(const MachineInstr *MI,
353 std::vector<const MachineInstr*> &PrevMIs,
354 MachineRegisterInfo *RegInfo) {
355 unsigned NumOps = MI->getNumOperands();
356 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
357 const MachineInstr *PrevMI = PrevMIs[i];
358 unsigned NumOps2 = PrevMI->getNumOperands();
359 if (NumOps != NumOps2)
360 continue;
361 bool IsSame = true;
362 for (unsigned j = 0; j != NumOps; ++j) {
363 const MachineOperand &MO = MI->getOperand(j);
364 if (MO.isReg() && MO.isDef()) {
365 if (RegInfo->getRegClass(MO.getReg()) !=
366 RegInfo->getRegClass(PrevMI->getOperand(j).getReg())) {
367 IsSame = false;
368 break;
369 }
370 continue;
371 }
372 if (!MO.isIdenticalTo(PrevMI->getOperand(j))) {
373 IsSame = false;
374 break;
375 }
376 }
377 if (IsSame)
378 return PrevMI;
379 }
380 return 0;
381}
382
383MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
384 // If not, we may be able to unfold a load and hoist that.
385 // First test whether the instruction is loading from an amenable
386 // memory location.
387 if (!MI->getDesc().mayLoad()) return 0;
388 if (!MI->hasOneMemOperand()) return 0;
389 MachineMemOperand *MMO = *MI->memoperands_begin();
390 if (MMO->isVolatile()) return 0;
391 MachineFunction &MF = *MI->getParent()->getParent();
392 if (!MMO->getValue()) return 0;
393 if (const PseudoSourceValue *PSV =
394 dyn_cast<PseudoSourceValue>(MMO->getValue())) {
395 if (!PSV->isConstant(MF.getFrameInfo())) return 0;
396 } else {
397 if (!AA->pointsToConstantMemory(MMO->getValue())) return 0;
398 }
399 // Next determine the register class for a temporary register.
400 unsigned LoadRegIndex;
401 unsigned NewOpc =
402 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
403 /*UnfoldLoad=*/true,
404 /*UnfoldStore=*/false,
405 &LoadRegIndex);
406 if (NewOpc == 0) return 0;
407 const TargetInstrDesc &TID = TII->get(NewOpc);
408 if (TID.getNumDefs() != 1) return 0;
409 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
410 // Ok, we're unfolding. Create a temporary register and do the unfold.
411 unsigned Reg = RegInfo->createVirtualRegister(RC);
412 SmallVector<MachineInstr *, 2> NewMIs;
413 bool Success =
414 TII->unfoldMemoryOperand(MF, MI, Reg,
415 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
416 NewMIs);
417 (void)Success;
418 assert(Success &&
419 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
420 "succeeded!");
421 assert(NewMIs.size() == 2 &&
422 "Unfolded a load into multiple instructions!");
423 MachineBasicBlock *MBB = MI->getParent();
424 MBB->insert(MI, NewMIs[0]);
425 MBB->insert(MI, NewMIs[1]);
426 // If unfolding produced a load that wasn't loop-invariant or profitable to
427 // hoist, discard the new instructions and bail.
428 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
429 NewMIs[0]->eraseFromParent();
430 NewMIs[1]->eraseFromParent();
431 return 0;
432 }
433 // Otherwise we successfully unfolded a load that we can hoist.
434 MI->eraseFromParent();
435 return NewMIs[0];
436}
437
438void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
439 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
440 const MachineInstr *MI = &*I;
441 // FIXME: For now, only hoist re-materilizable instructions. LICM will
442 // increase register pressure. We want to make sure it doesn't increase
443 // spilling.
444 if (TII->isTriviallyReMaterializable(MI, AA)) {
445 unsigned Opcode = MI->getOpcode();
446 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
447 CI = CSEMap.find(Opcode);
448 if (CI != CSEMap.end())
449 CI->second.push_back(MI);
450 else {
451 std::vector<const MachineInstr*> CSEMIs;
452 CSEMIs.push_back(MI);
453 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
454 }
455 }
456 }
457}
458
371/// Hoist - When an instruction is found to use only loop invariant operands
372/// that are safe to hoist, this instruction is called to do the dirty work.
373///
459/// Hoist - When an instruction is found to use only loop invariant operands
460/// that are safe to hoist, this instruction is called to do the dirty work.
461///
374void MachineLICM::Hoist(MachineInstr &MI) {
375 if (!IsLoopInvariantInst(MI)) return;
376 if (!IsProfitableToHoist(MI)) return;
462void MachineLICM::Hoist(MachineInstr *MI) {
463 // First check whether we should hoist this instruction.
464 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
465 // If not, try unfolding a hoistable load.
466 MI = ExtractHoistableLoad(MI);
467 if (!MI) return;
468 }
377
378 // Now move the instructions to the predecessor, inserting it before any
379 // terminator instructions.
380 DEBUG({
469
470 // Now move the instructions to the predecessor, inserting it before any
471 // terminator instructions.
472 DEBUG({
381 errs() << "Hoisting " << MI;
473 errs() << "Hoisting " << *MI;
382 if (CurPreheader->getBasicBlock())
383 errs() << " to MachineBasicBlock "
384 << CurPreheader->getBasicBlock()->getName();
474 if (CurPreheader->getBasicBlock())
475 errs() << " to MachineBasicBlock "
476 << CurPreheader->getBasicBlock()->getName();
385 if (MI.getParent()->getBasicBlock())
477 if (MI->getParent()->getBasicBlock())
386 errs() << " from MachineBasicBlock "
478 errs() << " from MachineBasicBlock "
387 << MI.getParent()->getBasicBlock()->getName();
479 << MI->getParent()->getBasicBlock()->getName();
388 errs() << "\n";
389 });
390
480 errs() << "\n";
481 });
482
483 // If this is the first instruction being hoisted to the preheader,
484 // initialize the CSE map with potential common expressions.
485 InitCSEMap(CurPreheader);
486
391 // Look for opportunity to CSE the hoisted instruction.
487 // Look for opportunity to CSE the hoisted instruction.
392 std::pair<unsigned, unsigned> BBOpcPair =
393 std::make_pair(CurPreheader->getNumber(), MI.getOpcode());
394 DenseMap<std::pair<unsigned, unsigned>,
395 std::vector<const MachineInstr*> >::iterator CI = CSEMap.find(BBOpcPair);
488 unsigned Opcode = MI->getOpcode();
489 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
490 CI = CSEMap.find(Opcode);
396 bool DoneCSE = false;
397 if (CI != CSEMap.end()) {
491 bool DoneCSE = false;
492 if (CI != CSEMap.end()) {
398 const MachineInstr *Dup = LookForDuplicate(&MI, CI->second, RegInfo);
493 const MachineInstr *Dup = LookForDuplicate(MI, CI->second, RegInfo);
399 if (Dup) {
494 if (Dup) {
400 DEBUG(errs() << "CSEing " << MI << " with " << *Dup);
401 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
402 const MachineOperand &MO = MI.getOperand(i);
495 DEBUG(errs() << "CSEing " << *MI << " with " << *Dup);
496 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
497 const MachineOperand &MO = MI->getOperand(i);
403 if (MO.isReg() && MO.isDef())
404 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
405 }
498 if (MO.isReg() && MO.isDef())
499 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
500 }
406 MI.eraseFromParent();
501 MI->eraseFromParent();
407 DoneCSE = true;
408 ++NumCSEed;
409 }
410 }
411
412 // Otherwise, splice the instruction to the preheader.
413 if (!DoneCSE) {
502 DoneCSE = true;
503 ++NumCSEed;
504 }
505 }
506
507 // Otherwise, splice the instruction to the preheader.
508 if (!DoneCSE) {
414 CurPreheader->splice(CurPreheader->getFirstTerminator(),
415 MI.getParent(), &MI);
509 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
510
416 // Add to the CSE map.
417 if (CI != CSEMap.end())
511 // Add to the CSE map.
512 if (CI != CSEMap.end())
418 CI->second.push_back(&MI);
513 CI->second.push_back(MI);
419 else {
420 std::vector<const MachineInstr*> CSEMIs;
514 else {
515 std::vector<const MachineInstr*> CSEMIs;
421 CSEMIs.push_back(&MI);
422 CSEMap.insert(std::make_pair(BBOpcPair, CSEMIs));
516 CSEMIs.push_back(MI);
517 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
423 }
424 }
425
426 ++NumHoisted;
427 Changed = true;
428}
518 }
519 }
520
521 ++NumHoisted;
522 Changed = true;
523}