blob: ffcc8abbc7b3e5e12b505dfe468ea46e8d7a29a0 [file] [log] [blame]
Bill Wendling0f940c92007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bill Wendling0f940c92007-12-07 21:42:31 +00007//
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//
Dan Gohmanc475c362009-01-15 22:01:38 +000013// 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//
Bill Wendling0f940c92007-12-07 21:42:31 +000021//===----------------------------------------------------------------------===//
22
23#define DEBUG_TYPE "machine-licm"
Chris Lattnerac695822008-01-04 06:41:45 +000024#include "llvm/CodeGen/Passes.h"
Evan Cheng78e5c112009-11-07 03:52:02 +000025#include "llvm/CodeGen/MachineConstantPool.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000026#include "llvm/CodeGen/MachineDominators.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000028#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling9258cd32008-01-02 19:32:43 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000030#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000031#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000032#include "llvm/Target/TargetInstrInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000033#include "llvm/Target/TargetMachine.h"
Dan Gohmane33f44c2009-10-07 17:38:06 +000034#include "llvm/Analysis/AliasAnalysis.h"
Evan Chengaf6949d2009-02-05 08:45:46 +000035#include "llvm/ADT/DenseMap.h"
Chris Lattnerac695822008-01-04 06:41:45 +000036#include "llvm/ADT/Statistic.h"
Chris Lattnerac695822008-01-04 06:41:45 +000037#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000038#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000039
40using namespace llvm;
41
Bill Wendling041b3f82007-12-08 23:58:46 +000042STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Evan Chengaf6949d2009-02-05 08:45:46 +000043STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
Bill Wendlingb48519c2007-12-08 01:47:01 +000044
Bill Wendling0f940c92007-12-07 21:42:31 +000045namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000046 class MachineLICM : public MachineFunctionPass {
Evan Cheng78e5c112009-11-07 03:52:02 +000047 MachineConstantPool *MCP;
Bill Wendling9258cd32008-01-02 19:32:43 +000048 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000049 const TargetInstrInfo *TII;
Dan Gohmana8fb3362009-09-25 23:58:45 +000050 const TargetRegisterInfo *TRI;
Dan Gohman45094e32009-09-26 02:34:00 +000051 BitVector AllocatableSet;
Bill Wendling12ebf142007-12-11 19:40:06 +000052
Bill Wendling0f940c92007-12-07 21:42:31 +000053 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000054 AliasAnalysis *AA; // Alias analysis info.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000055 MachineLoopInfo *LI; // Current MachineLoopInfo
56 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling9258cd32008-01-02 19:32:43 +000057 MachineRegisterInfo *RegInfo; // Machine register information
Bill Wendling0f940c92007-12-07 21:42:31 +000058
Bill Wendling0f940c92007-12-07 21:42:31 +000059 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000060 bool Changed; // True if a loop is changed.
Evan Cheng777c6b72009-11-03 21:40:02 +000061 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000062 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000063 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000064
Evan Cheng777c6b72009-11-03 21:40:02 +000065 // For each opcode, keep a list of potentail CSE instructions.
66 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Bill Wendling0f940c92007-12-07 21:42:31 +000067 public:
68 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000069 MachineLICM() : MachineFunctionPass(&ID) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000070
71 virtual bool runOnMachineFunction(MachineFunction &MF);
72
Dan Gohman72241702008-12-18 01:37:56 +000073 const char *getPassName() const { return "Machine Instruction LICM"; }
74
Bill Wendling074223a2008-03-10 08:13:01 +000075 // FIXME: Loop preheaders?
Bill Wendling0f940c92007-12-07 21:42:31 +000076 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
77 AU.setPreservesCFG();
78 AU.addRequired<MachineLoopInfo>();
79 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +000080 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +000081 AU.addPreserved<MachineLoopInfo>();
82 AU.addPreserved<MachineDominatorTree>();
83 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +000084 }
Evan Chengaf6949d2009-02-05 08:45:46 +000085
86 virtual void releaseMemory() {
87 CSEMap.clear();
88 }
89
Bill Wendling0f940c92007-12-07 21:42:31 +000090 private:
Bill Wendling041b3f82007-12-08 23:58:46 +000091 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +000092 /// invariant. I.e., all virtual register operands are defined outside of
93 /// the loop, physical registers aren't accessed (explicitly or implicitly),
94 /// and the instruction is hoistable.
95 ///
Bill Wendling041b3f82007-12-08 23:58:46 +000096 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +000097
Evan Cheng45e94d62009-02-04 09:19:56 +000098 /// IsProfitableToHoist - Return true if it is potentially profitable to
99 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000100 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000101
Bill Wendling0f940c92007-12-07 21:42:31 +0000102 /// HoistRegion - Walk the specified region of the CFG (defined by all
103 /// blocks dominated by the specified block, and that are in the current
104 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
105 /// visit definitions before uses, allowing us to hoist a loop body in one
106 /// pass without iteration.
107 ///
108 void HoistRegion(MachineDomTreeNode *N);
109
Evan Cheng87b75ba2009-11-20 19:55:37 +0000110 /// isLoadFromConstantMemory - Return true if the given instruction is a
111 /// load from constant memory.
112 bool isLoadFromConstantMemory(MachineInstr *MI);
113
Dan Gohman5c952302009-10-29 17:47:20 +0000114 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
115 /// the load itself could be hoisted. Return the unfolded and hoistable
116 /// load, or null if the load couldn't be unfolded or if it wouldn't
117 /// be hoistable.
118 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
119
Evan Cheng78e5c112009-11-07 03:52:02 +0000120 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
121 /// duplicate of MI. Return this instruction if it's found.
122 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
123 std::vector<const MachineInstr*> &PrevMIs);
124
Evan Cheng9fb744e2009-11-05 00:51:13 +0000125 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
126 /// the preheader that compute the same value. If it's found, do a RAU on
127 /// with the definition of the existing instruction rather than hoisting
128 /// the instruction to the preheader.
129 bool EliminateCSE(MachineInstr *MI,
130 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
131
Bill Wendling0f940c92007-12-07 21:42:31 +0000132 /// Hoist - When an instruction is found to only use loop invariant operands
133 /// that is safe to hoist, this instruction is called to do the dirty work.
134 ///
Dan Gohman589f1f52009-10-28 03:21:57 +0000135 void Hoist(MachineInstr *MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000136
137 /// InitCSEMap - Initialize the CSE map with instructions that are in the
138 /// current loop preheader that may become duplicates of instructions that
139 /// are hoisted out of the loop.
140 void InitCSEMap(MachineBasicBlock *BB);
Bill Wendling0f940c92007-12-07 21:42:31 +0000141 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000142} // end anonymous namespace
143
Dan Gohman844731a2008-05-13 00:00:25 +0000144char MachineLICM::ID = 0;
145static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000146X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000147
Bill Wendling0f940c92007-12-07 21:42:31 +0000148FunctionPass *llvm::createMachineLICMPass() { return new MachineLICM(); }
149
Dan Gohmanc475c362009-01-15 22:01:38 +0000150/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
151/// loop that has a preheader.
152static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
153 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
154 if (L->getLoopPreheader())
155 return false;
156 return true;
157}
158
Bill Wendling0f940c92007-12-07 21:42:31 +0000159/// Hoist expressions out of the specified loop. Note, alias info for inner loop
160/// is not preserved so it is not a good idea to run LICM multiple times on one
161/// loop.
162///
163bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
David Greene65a41eb2010-01-05 00:03:48 +0000164 DEBUG(dbgs() << "******** Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000165
Evan Cheng777c6b72009-11-03 21:40:02 +0000166 Changed = FirstInLoop = false;
Evan Cheng78e5c112009-11-07 03:52:02 +0000167 MCP = MF.getConstantPool();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000168 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000169 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000170 TRI = TM->getRegisterInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000171 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000172 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000173
174 // Get our Loop information...
175 LI = &getAnalysis<MachineLoopInfo>();
176 DT = &getAnalysis<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000177 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000178
Evan Cheng777c6b72009-11-03 21:40:02 +0000179 for (MachineLoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
Bill Wendlinga17ad592007-12-11 22:22:22 +0000180 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000181
Dan Gohmanc475c362009-01-15 22:01:38 +0000182 // Only visit outer-most preheader-sporting loops.
183 if (!LoopIsOuterMostWithPreheader(CurLoop))
184 continue;
185
186 // Determine the block to which to hoist instructions. If we can't find a
187 // suitable loop preheader, we can't do any hoisting.
188 //
189 // FIXME: We are only hoisting if the basic block coming into this loop
190 // has only one successor. This isn't the case in general because we haven't
191 // broken critical edges or added preheaders.
192 CurPreheader = CurLoop->getLoopPreheader();
193 if (!CurPreheader)
194 continue;
195
Evan Cheng777c6b72009-11-03 21:40:02 +0000196 // CSEMap is initialized for loop header when the first instruction is
197 // being hoisted.
198 FirstInLoop = true;
Dan Gohmanc475c362009-01-15 22:01:38 +0000199 HoistRegion(DT->getNode(CurLoop->getHeader()));
Evan Cheng777c6b72009-11-03 21:40:02 +0000200 CSEMap.clear();
Bill Wendling0f940c92007-12-07 21:42:31 +0000201 }
202
203 return Changed;
204}
205
Bill Wendling0f940c92007-12-07 21:42:31 +0000206/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
207/// dominated by the specified block, and that are in the current loop) in depth
208/// first order w.r.t the DominatorTree. This allows us to visit definitions
209/// before uses, allowing us to hoist a loop body in one pass without iteration.
210///
211void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
212 assert(N != 0 && "Null dominator tree node?");
213 MachineBasicBlock *BB = N->getBlock();
214
215 // If this subregion is not in the top level loop at all, exit.
216 if (!CurLoop->contains(BB)) return;
217
Dan Gohmanc475c362009-01-15 22:01:38 +0000218 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000219 MII = BB->begin(), E = BB->end(); MII != E; ) {
220 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000221 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000222 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000223 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000224
225 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
226
227 for (unsigned I = 0, E = Children.size(); I != E; ++I)
228 HoistRegion(Children[I]);
229}
230
Bill Wendling041b3f82007-12-08 23:58:46 +0000231/// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000232/// invariant. I.e., all virtual register operands are defined outside of the
Bill Wendling60ff1a32007-12-20 01:08:10 +0000233/// loop, physical registers aren't accessed explicitly, and there are no side
234/// effects that aren't captured by the operands or other flags.
Bill Wendling0f940c92007-12-07 21:42:31 +0000235///
Bill Wendling041b3f82007-12-08 23:58:46 +0000236bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000237 const TargetInstrDesc &TID = I.getDesc();
238
239 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000240 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000241 TID.hasUnmodeledSideEffects())
242 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000243
Chris Lattnera22edc82008-01-10 23:08:24 +0000244 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000245 // Okay, this instruction does a load. As a refinement, we allow the target
246 // to decide whether the loaded value is actually a constant. If so, we can
247 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000248 if (!I.isInvariantLoad(AA))
Evan Cheng7adcdc32009-11-17 19:19:01 +0000249 // FIXME: we should be able to hoist loads with no other side effects if
250 // there are no other instructions which can change memory in this loop.
251 // This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000252 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000253 }
Bill Wendling074223a2008-03-10 08:13:01 +0000254
Bill Wendling280f4562007-12-18 21:38:04 +0000255 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +0000256 dbgs() << "--- Checking if we can hoist " << I;
Chris Lattner749c6f62008-01-07 07:27:27 +0000257 if (I.getDesc().getImplicitUses()) {
David Greene65a41eb2010-01-05 00:03:48 +0000258 dbgs() << " * Instruction has implicit uses:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000259
Dan Gohman6f0d0242008-02-10 18:45:23 +0000260 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000261 for (const unsigned *ImpUses = I.getDesc().getImplicitUses();
Chris Lattner69244302008-01-07 01:56:04 +0000262 *ImpUses; ++ImpUses)
David Greene65a41eb2010-01-05 00:03:48 +0000263 dbgs() << " -> " << TRI->getName(*ImpUses) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000264 }
265
Chris Lattner749c6f62008-01-07 07:27:27 +0000266 if (I.getDesc().getImplicitDefs()) {
David Greene65a41eb2010-01-05 00:03:48 +0000267 dbgs() << " * Instruction has implicit defines:\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000268
Dan Gohman6f0d0242008-02-10 18:45:23 +0000269 const TargetRegisterInfo *TRI = TM->getRegisterInfo();
Chris Lattner749c6f62008-01-07 07:27:27 +0000270 for (const unsigned *ImpDefs = I.getDesc().getImplicitDefs();
Chris Lattner69244302008-01-07 01:56:04 +0000271 *ImpDefs; ++ImpDefs)
David Greene65a41eb2010-01-05 00:03:48 +0000272 dbgs() << " -> " << TRI->getName(*ImpDefs) << "\n";
Bill Wendling280f4562007-12-18 21:38:04 +0000273 }
Bill Wendling280f4562007-12-18 21:38:04 +0000274 });
275
Bill Wendlingd3361e92008-08-18 00:33:49 +0000276 if (I.getDesc().getImplicitDefs() || I.getDesc().getImplicitUses()) {
David Greene65a41eb2010-01-05 00:03:48 +0000277 DEBUG(dbgs() << "Cannot hoist with implicit defines or uses\n");
Bill Wendlingd3361e92008-08-18 00:33:49 +0000278 return false;
279 }
280
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000281 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000282 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
283 const MachineOperand &MO = I.getOperand(i);
284
Dan Gohmand735b802008-10-03 15:45:36 +0000285 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000286 continue;
287
Dan Gohmanc475c362009-01-15 22:01:38 +0000288 unsigned Reg = MO.getReg();
289 if (Reg == 0) continue;
290
291 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000292 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000293 if (MO.isUse()) {
294 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000295 // and we can freely move its uses. Alternatively, if it's allocatable,
296 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000297 if (!RegInfo->def_empty(Reg))
298 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000299 if (AllocatableSet.test(Reg))
300 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000301 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000302 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
303 unsigned AliasReg = *Alias;
304 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000305 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000306 if (AllocatableSet.test(AliasReg))
307 return false;
308 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000309 // Otherwise it's safe to move.
310 continue;
311 } else if (!MO.isDead()) {
312 // A def that isn't dead. We can't move it.
313 return false;
314 }
315 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000316
317 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000318 continue;
319
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000320 assert(RegInfo->getVRegDef(Reg) &&
321 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000322
323 // If the loop contains the definition of an operand, then the instruction
324 // isn't loop invariant.
Dan Gohman92329c72009-12-18 01:24:09 +0000325 if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000326 return false;
327 }
328
329 // If we got this far, the instruction is loop invariant!
330 return true;
331}
332
Evan Chengaf6949d2009-02-05 08:45:46 +0000333
334/// HasPHIUses - Return true if the specified register has any PHI use.
335static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000336 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
337 UE = RegInfo->use_end(); UI != UE; ++UI) {
338 MachineInstr *UseMI = &*UI;
Evan Chengaf6949d2009-02-05 08:45:46 +0000339 if (UseMI->getOpcode() == TargetInstrInfo::PHI)
340 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000341 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000342 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000343}
344
Evan Cheng87b75ba2009-11-20 19:55:37 +0000345/// isLoadFromConstantMemory - Return true if the given instruction is a
346/// load from constant memory. Machine LICM will hoist these even if they are
347/// not re-materializable.
348bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
349 if (!MI->getDesc().mayLoad()) return false;
350 if (!MI->hasOneMemOperand()) return false;
351 MachineMemOperand *MMO = *MI->memoperands_begin();
352 if (MMO->isVolatile()) return false;
353 if (!MMO->getValue()) return false;
354 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
355 if (PSV) {
356 MachineFunction &MF = *MI->getParent()->getParent();
357 return PSV->isConstant(MF.getFrameInfo());
358 } else {
359 return AA->pointsToConstantMemory(MMO->getValue());
360 }
361}
362
Evan Cheng45e94d62009-02-04 09:19:56 +0000363/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
364/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000365bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengefc78392009-02-27 00:02:22 +0000366 if (MI.getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
367 return false;
368
Evan Cheng45e94d62009-02-04 09:19:56 +0000369 // FIXME: For now, only hoist re-materilizable instructions. LICM will
370 // increase register pressure. We want to make sure it doesn't increase
371 // spilling.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000372 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
373 // these tend to help performance in low register pressure situation. The
374 // trade off is it may cause spill in high pressure situation. It will end up
375 // adding a store in the loop preheader. But the reload is no more expensive.
376 // The side benefit is these loads are frequently CSE'ed.
377 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
Evan Chengc26abd92009-11-20 23:31:34 +0000378 if (!isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000379 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000380 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000381
Evan Chengaf6949d2009-02-05 08:45:46 +0000382 // If result(s) of this instruction is used by PHIs, then don't hoist it.
383 // The presence of joins makes it difficult for current register allocator
384 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000385 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
386 const MachineOperand &MO = MI.getOperand(i);
387 if (!MO.isReg() || !MO.isDef())
388 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000389 if (HasPHIUses(MO.getReg(), RegInfo))
390 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000391 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000392
393 return true;
394}
395
Dan Gohman5c952302009-10-29 17:47:20 +0000396MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
397 // If not, we may be able to unfold a load and hoist that.
398 // First test whether the instruction is loading from an amenable
399 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000400 if (!isLoadFromConstantMemory(MI))
401 return 0;
402
Dan Gohman5c952302009-10-29 17:47:20 +0000403 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000404 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000405 unsigned NewOpc =
406 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
407 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000408 /*UnfoldStore=*/false,
409 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000410 if (NewOpc == 0) return 0;
411 const TargetInstrDesc &TID = TII->get(NewOpc);
412 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000413 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000414 // Ok, we're unfolding. Create a temporary register and do the unfold.
415 unsigned Reg = RegInfo->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000416
417 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000418 SmallVector<MachineInstr *, 2> NewMIs;
419 bool Success =
420 TII->unfoldMemoryOperand(MF, MI, Reg,
421 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
422 NewMIs);
423 (void)Success;
424 assert(Success &&
425 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
426 "succeeded!");
427 assert(NewMIs.size() == 2 &&
428 "Unfolded a load into multiple instructions!");
429 MachineBasicBlock *MBB = MI->getParent();
430 MBB->insert(MI, NewMIs[0]);
431 MBB->insert(MI, NewMIs[1]);
432 // If unfolding produced a load that wasn't loop-invariant or profitable to
433 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +0000434 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +0000435 NewMIs[0]->eraseFromParent();
436 NewMIs[1]->eraseFromParent();
437 return 0;
438 }
439 // Otherwise we successfully unfolded a load that we can hoist.
440 MI->eraseFromParent();
441 return NewMIs[0];
442}
443
Evan Cheng777c6b72009-11-03 21:40:02 +0000444void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
445 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
446 const MachineInstr *MI = &*I;
447 // FIXME: For now, only hoist re-materilizable instructions. LICM will
448 // increase register pressure. We want to make sure it doesn't increase
449 // spilling.
450 if (TII->isTriviallyReMaterializable(MI, AA)) {
451 unsigned Opcode = MI->getOpcode();
452 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
453 CI = CSEMap.find(Opcode);
454 if (CI != CSEMap.end())
455 CI->second.push_back(MI);
456 else {
457 std::vector<const MachineInstr*> CSEMIs;
458 CSEMIs.push_back(MI);
459 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
460 }
461 }
462 }
463}
464
Evan Cheng78e5c112009-11-07 03:52:02 +0000465const MachineInstr*
466MachineLICM::LookForDuplicate(const MachineInstr *MI,
467 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +0000468 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
469 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng78e5c112009-11-07 03:52:02 +0000470 if (TII->isIdentical(MI, PrevMI, RegInfo))
Evan Cheng9fb744e2009-11-05 00:51:13 +0000471 return PrevMI;
472 }
473 return 0;
474}
475
476bool MachineLICM::EliminateCSE(MachineInstr *MI,
477 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000478 if (CI == CSEMap.end())
479 return false;
480
481 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +0000482 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Evan Cheng78e5c112009-11-07 03:52:02 +0000483 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
484 const MachineOperand &MO = MI->getOperand(i);
485 if (MO.isReg() && MO.isDef())
486 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
Evan Cheng9fb744e2009-11-05 00:51:13 +0000487 }
Evan Cheng78e5c112009-11-07 03:52:02 +0000488 MI->eraseFromParent();
489 ++NumCSEed;
490 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +0000491 }
492 return false;
493}
494
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000495/// Hoist - When an instruction is found to use only loop invariant operands
496/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000497///
Dan Gohman589f1f52009-10-28 03:21:57 +0000498void MachineLICM::Hoist(MachineInstr *MI) {
499 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +0000500 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000501 // If not, try unfolding a hoistable load.
502 MI = ExtractHoistableLoad(MI);
503 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000504 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000505
Dan Gohmanc475c362009-01-15 22:01:38 +0000506 // Now move the instructions to the predecessor, inserting it before any
507 // terminator instructions.
508 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +0000509 dbgs() << "Hoisting " << *MI;
Dan Gohmanc475c362009-01-15 22:01:38 +0000510 if (CurPreheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000511 dbgs() << " to MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000512 << CurPreheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000513 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000514 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000515 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +0000516 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000517 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000518
Evan Cheng777c6b72009-11-03 21:40:02 +0000519 // If this is the first instruction being hoisted to the preheader,
520 // initialize the CSE map with potential common expressions.
521 InitCSEMap(CurPreheader);
522
Evan Chengaf6949d2009-02-05 08:45:46 +0000523 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +0000524 unsigned Opcode = MI->getOpcode();
525 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
526 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +0000527 if (!EliminateCSE(MI, CI)) {
528 // Otherwise, splice the instruction to the preheader.
Evan Cheng777c6b72009-11-03 21:40:02 +0000529 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
530
Evan Chengaf6949d2009-02-05 08:45:46 +0000531 // Add to the CSE map.
532 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000533 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000534 else {
535 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000536 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000537 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +0000538 }
539 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000540
Dan Gohmanc475c362009-01-15 22:01:38 +0000541 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000542 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000543}