blob: 709b2d1587a86c940c8adad1417c4bcb8a434498 [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"
Bill Wendling0f940c92007-12-07 21:42:31 +000025#include "llvm/CodeGen/MachineDominators.h"
Evan Chengd94671a2010-04-07 00:41:17 +000026#include "llvm/CodeGen/MachineFrameInfo.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"
Evan Chengd94671a2010-04-07 00:41:17 +000036#include "llvm/ADT/SmallSet.h"
Chris Lattnerac695822008-01-04 06:41:45 +000037#include "llvm/ADT/Statistic.h"
Chris Lattnerac695822008-01-04 06:41:45 +000038#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000039#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000040
41using namespace llvm;
42
Bill Wendling041b3f82007-12-08 23:58:46 +000043STATISTIC(NumHoisted, "Number of machine instructions hoisted out of loops");
Evan Chengaf6949d2009-02-05 08:45:46 +000044STATISTIC(NumCSEed, "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000045STATISTIC(NumPostRAHoisted,
46 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendlingb48519c2007-12-08 01:47:01 +000047
Bill Wendling0f940c92007-12-07 21:42:31 +000048namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000049 class MachineLICM : public MachineFunctionPass {
Evan Chengd94671a2010-04-07 00:41:17 +000050 bool PreRegAlloc;
51
Bill Wendling9258cd32008-01-02 19:32:43 +000052 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000053 const TargetInstrInfo *TII;
Dan Gohmana8fb3362009-09-25 23:58:45 +000054 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000055 const MachineFrameInfo *MFI;
56 MachineRegisterInfo *RegInfo;
Bill Wendling12ebf142007-12-11 19:40:06 +000057
Bill Wendling0f940c92007-12-07 21:42:31 +000058 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000059 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +000060 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000061 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000062
Bill Wendling0f940c92007-12-07 21:42:31 +000063 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000064 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +000065 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000066 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000067 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000068
Evan Chengd94671a2010-04-07 00:41:17 +000069 BitVector AllocatableSet;
70
Evan Cheng777c6b72009-11-03 21:40:02 +000071 // For each opcode, keep a list of potentail CSE instructions.
72 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000073
Bill Wendling0f940c92007-12-07 21:42:31 +000074 public:
75 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +000076 MachineLICM() :
77 MachineFunctionPass(&ID), PreRegAlloc(true) {}
78
79 explicit MachineLICM(bool PreRA) :
80 MachineFunctionPass(&ID), PreRegAlloc(PreRA) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000081
82 virtual bool runOnMachineFunction(MachineFunction &MF);
83
Dan Gohman72241702008-12-18 01:37:56 +000084 const char *getPassName() const { return "Machine Instruction LICM"; }
85
Bill Wendling0f940c92007-12-07 21:42:31 +000086 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
87 AU.setPreservesCFG();
88 AU.addRequired<MachineLoopInfo>();
89 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +000090 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +000091 AU.addPreserved<MachineLoopInfo>();
92 AU.addPreserved<MachineDominatorTree>();
93 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +000094 }
Evan Chengaf6949d2009-02-05 08:45:46 +000095
96 virtual void releaseMemory() {
97 CSEMap.clear();
98 }
99
Bill Wendling0f940c92007-12-07 21:42:31 +0000100 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000101 /// CandidateInfo - Keep track of information about hoisting candidates.
102 struct CandidateInfo {
103 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000104 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000105 int FI;
106 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
107 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000108 };
109
110 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
111 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000112 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000113
114 /// HoistPostRA - When an instruction is found to only use loop invariant
115 /// operands that is safe to hoist, this instruction is called to do the
116 /// dirty work.
117 void HoistPostRA(MachineInstr *MI, unsigned Def);
118
119 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
120 /// gather register def and frame object update information.
121 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
122 SmallSet<int, 32> &StoredFIs,
123 SmallVector<CandidateInfo, 32> &Candidates);
124
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000125 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
126 /// current loop.
127 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000128
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000129 /// IsLICMCandidate - Returns true if the instruction may be a suitable
130 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
131 /// not safe to hoist it.
132 bool IsLICMCandidate(MachineInstr &I);
133
Bill Wendling041b3f82007-12-08 23:58:46 +0000134 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000135 /// invariant. I.e., all virtual register operands are defined outside of
136 /// the loop, physical registers aren't accessed (explicitly or implicitly),
137 /// and the instruction is hoistable.
138 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000139 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000140
Evan Cheng45e94d62009-02-04 09:19:56 +0000141 /// IsProfitableToHoist - Return true if it is potentially profitable to
142 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000143 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000144
Bill Wendling0f940c92007-12-07 21:42:31 +0000145 /// HoistRegion - Walk the specified region of the CFG (defined by all
146 /// blocks dominated by the specified block, and that are in the current
147 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
148 /// visit definitions before uses, allowing us to hoist a loop body in one
149 /// pass without iteration.
150 ///
151 void HoistRegion(MachineDomTreeNode *N);
152
Evan Cheng87b75ba2009-11-20 19:55:37 +0000153 /// isLoadFromConstantMemory - Return true if the given instruction is a
154 /// load from constant memory.
155 bool isLoadFromConstantMemory(MachineInstr *MI);
156
Dan Gohman5c952302009-10-29 17:47:20 +0000157 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
158 /// the load itself could be hoisted. Return the unfolded and hoistable
159 /// load, or null if the load couldn't be unfolded or if it wouldn't
160 /// be hoistable.
161 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
162
Evan Cheng78e5c112009-11-07 03:52:02 +0000163 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
164 /// duplicate of MI. Return this instruction if it's found.
165 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
166 std::vector<const MachineInstr*> &PrevMIs);
167
Evan Cheng9fb744e2009-11-05 00:51:13 +0000168 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
169 /// the preheader that compute the same value. If it's found, do a RAU on
170 /// with the definition of the existing instruction rather than hoisting
171 /// the instruction to the preheader.
172 bool EliminateCSE(MachineInstr *MI,
173 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
174
Bill Wendling0f940c92007-12-07 21:42:31 +0000175 /// Hoist - When an instruction is found to only use loop invariant operands
176 /// that is safe to hoist, this instruction is called to do the dirty work.
177 ///
Dan Gohman589f1f52009-10-28 03:21:57 +0000178 void Hoist(MachineInstr *MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000179
180 /// InitCSEMap - Initialize the CSE map with instructions that are in the
181 /// current loop preheader that may become duplicates of instructions that
182 /// are hoisted out of the loop.
183 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000184
185 /// getCurPreheader - Get the preheader for the current loop, splitting
186 /// a critical edge if needed.
187 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000188 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000189} // end anonymous namespace
190
Dan Gohman844731a2008-05-13 00:00:25 +0000191char MachineLICM::ID = 0;
192static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000193X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000194
Evan Chengd94671a2010-04-07 00:41:17 +0000195FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
196 return new MachineLICM(PreRegAlloc);
197}
Bill Wendling0f940c92007-12-07 21:42:31 +0000198
Dan Gohman853d3fb2010-06-22 17:25:57 +0000199/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
200/// loop that has a unique predecessor.
201static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000202 // Check whether this loop even has a unique predecessor.
203 if (!CurLoop->getLoopPredecessor())
204 return false;
205 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000206 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000207 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000208 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000209 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000210 return true;
211}
212
Bill Wendling0f940c92007-12-07 21:42:31 +0000213bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000214 if (PreRegAlloc)
215 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
216 else
217 DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000218
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000219 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000220 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000221 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000222 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000223 MFI = MF.getFrameInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000224 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000225 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000226
227 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000228 MLI = &getAnalysis<MachineLoopInfo>();
229 DT = &getAnalysis<MachineDominatorTree>();
230 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000231
Dan Gohmanaa742602010-07-09 18:49:45 +0000232 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
233 while (!Worklist.empty()) {
234 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000235 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000236
Evan Cheng4038f9c2010-04-08 01:03:47 +0000237 // If this is done before regalloc, only visit outer-most preheader-sporting
238 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000239 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
240 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000241 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000242 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000243
Evan Chengd94671a2010-04-07 00:41:17 +0000244 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000245 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000246 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000247 // CSEMap is initialized for loop header when the first instruction is
248 // being hoisted.
249 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000250 FirstInLoop = true;
Evan Chengd94671a2010-04-07 00:41:17 +0000251 HoistRegion(N);
252 CSEMap.clear();
253 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000254 }
255
256 return Changed;
257}
258
Evan Cheng4038f9c2010-04-08 01:03:47 +0000259/// InstructionStoresToFI - Return true if instruction stores to the
260/// specified frame.
261static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
262 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
263 oe = MI->memoperands_end(); o != oe; ++o) {
264 if (!(*o)->isStore() || !(*o)->getValue())
265 continue;
266 if (const FixedStackPseudoSourceValue *Value =
267 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
268 if (Value->getFrameIndex() == FI)
269 return true;
270 }
271 }
272 return false;
273}
274
275/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
276/// gather register def and frame object update information.
277void MachineLICM::ProcessMI(MachineInstr *MI,
278 unsigned *PhysRegDefs,
279 SmallSet<int, 32> &StoredFIs,
280 SmallVector<CandidateInfo, 32> &Candidates) {
281 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000282 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000283 unsigned Def = 0;
284 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
285 const MachineOperand &MO = MI->getOperand(i);
286 if (MO.isFI()) {
287 // Remember if the instruction stores to the frame index.
288 int FI = MO.getIndex();
289 if (!StoredFIs.count(FI) &&
290 MFI->isSpillSlotObjectIndex(FI) &&
291 InstructionStoresToFI(MI, FI))
292 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000293 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000294 continue;
295 }
296
297 if (!MO.isReg())
298 continue;
299 unsigned Reg = MO.getReg();
300 if (!Reg)
301 continue;
302 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
303 "Not expecting virtual register!");
304
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000305 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000306 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000307 // If it's using a non-loop-invariant register, then it's obviously not
308 // safe to hoist.
309 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000310 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000311 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000312
313 if (MO.isImplicit()) {
314 ++PhysRegDefs[Reg];
315 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
316 ++PhysRegDefs[*AS];
317 if (!MO.isDead())
318 // Non-dead implicit def? This cannot be hoisted.
319 RuledOut = true;
320 // No need to check if a dead implicit def is also defined by
321 // another instruction.
322 continue;
323 }
324
325 // FIXME: For now, avoid instructions with multiple defs, unless
326 // it's a dead implicit def.
327 if (Def)
328 RuledOut = true;
329 else
330 Def = Reg;
331
332 // If we have already seen another instruction that defines the same
333 // register, then this is not safe.
334 if (++PhysRegDefs[Reg] > 1)
335 // MI defined register is seen defined by another instruction in
336 // the loop, it cannot be a LICM candidate.
337 RuledOut = true;
338 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
339 if (++PhysRegDefs[*AS] > 1)
340 RuledOut = true;
341 }
342
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000343 // Only consider reloads for now and remats which do not have register
344 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000345 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000346 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000347 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000348 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
349 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000350 }
351}
352
353/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
354/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000355void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000356 unsigned NumRegs = TRI->getNumRegs();
357 unsigned *PhysRegDefs = new unsigned[NumRegs];
358 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
359
Evan Cheng4038f9c2010-04-08 01:03:47 +0000360 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000361 SmallSet<int, 32> StoredFIs;
362
363 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000364 // collect potential LICM candidates.
365 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
366 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
367 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000368 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000369 // FIXME: That means a reload that're reused in successor block(s) will not
370 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000371 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000372 E = BB->livein_end(); I != E; ++I) {
373 unsigned Reg = *I;
374 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000375 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
376 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000377 }
378
379 for (MachineBasicBlock::iterator
380 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000381 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000382 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000383 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000384 }
Evan Chengd94671a2010-04-07 00:41:17 +0000385
386 // Now evaluate whether the potential candidates qualify.
387 // 1. Check if the candidate defined register is defined by another
388 // instruction in the loop.
389 // 2. If the candidate is a load from stack slot (always true for now),
390 // check if the slot is stored anywhere in the loop.
391 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000392 if (Candidates[i].FI != INT_MIN &&
393 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000394 continue;
395
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000396 if (PhysRegDefs[Candidates[i].Def] == 1) {
397 bool Safe = true;
398 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000399 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
400 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000401 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000402 continue;
403 if (PhysRegDefs[MO.getReg()]) {
404 // If it's using a non-loop-invariant register, then it's obviously
405 // not safe to hoist.
406 Safe = false;
407 break;
408 }
409 }
410 if (Safe)
411 HoistPostRA(MI, Candidates[i].Def);
412 }
Evan Chengd94671a2010-04-07 00:41:17 +0000413 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000414
415 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000416}
417
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000418/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
419/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000420void MachineLICM::AddToLiveIns(unsigned Reg) {
421 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000422 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
423 MachineBasicBlock *BB = Blocks[i];
424 if (!BB->isLiveIn(Reg))
425 BB->addLiveIn(Reg);
426 for (MachineBasicBlock::iterator
427 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
428 MachineInstr *MI = &*MII;
429 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
430 MachineOperand &MO = MI->getOperand(i);
431 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
432 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
433 MO.setIsKill(false);
434 }
435 }
436 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000437}
438
439/// HoistPostRA - When an instruction is found to only use loop invariant
440/// operands that is safe to hoist, this instruction is called to do the
441/// dirty work.
442void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000443 MachineBasicBlock *Preheader = getCurPreheader();
444 if (!Preheader) return;
445
Evan Chengd94671a2010-04-07 00:41:17 +0000446 // Now move the instructions to the predecessor, inserting it before any
447 // terminator instructions.
448 DEBUG({
449 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000450 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000451 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000452 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000453 if (MI->getParent()->getBasicBlock())
454 dbgs() << " from MachineBasicBlock "
455 << MI->getParent()->getName();
456 dbgs() << "\n";
457 });
458
459 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000460 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000461 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000462
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000463 // Add register to livein list to all the BBs in the current loop since a
464 // loop invariant must be kept live throughout the whole loop. This is
465 // important to ensure later passes do not scavenge the def register.
466 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000467
468 ++NumPostRAHoisted;
469 Changed = true;
470}
471
Bill Wendling0f940c92007-12-07 21:42:31 +0000472/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
473/// dominated by the specified block, and that are in the current loop) in depth
474/// first order w.r.t the DominatorTree. This allows us to visit definitions
475/// before uses, allowing us to hoist a loop body in one pass without iteration.
476///
477void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
478 assert(N != 0 && "Null dominator tree node?");
479 MachineBasicBlock *BB = N->getBlock();
480
481 // If this subregion is not in the top level loop at all, exit.
482 if (!CurLoop->contains(BB)) return;
483
Dan Gohmanc475c362009-01-15 22:01:38 +0000484 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000485 MII = BB->begin(), E = BB->end(); MII != E; ) {
486 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000487 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000488 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000489 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000490
491 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Bill Wendling0f940c92007-12-07 21:42:31 +0000492 for (unsigned I = 0, E = Children.size(); I != E; ++I)
493 HoistRegion(Children[I]);
494}
495
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000496/// IsLICMCandidate - Returns true if the instruction may be a suitable
497/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
498/// not safe to hoist it.
499bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Evan Cheng63275372010-04-13 22:13:34 +0000500 if (I.isImplicitDef())
501 return false;
502
Chris Lattnera22edc82008-01-10 23:08:24 +0000503 const TargetInstrDesc &TID = I.getDesc();
504
505 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000506 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000507 TID.hasUnmodeledSideEffects())
508 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000509
Chris Lattnera22edc82008-01-10 23:08:24 +0000510 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000511 // Okay, this instruction does a load. As a refinement, we allow the target
512 // to decide whether the loaded value is actually a constant. If so, we can
513 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000514 if (!I.isInvariantLoad(AA))
Evan Cheng7adcdc32009-11-17 19:19:01 +0000515 // FIXME: we should be able to hoist loads with no other side effects if
516 // there are no other instructions which can change memory in this loop.
517 // This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000518 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000519 }
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000520 return true;
521}
522
523/// IsLoopInvariantInst - Returns true if the instruction is loop
524/// invariant. I.e., all virtual register operands are defined outside of the
525/// loop, physical registers aren't accessed explicitly, and there are no side
526/// effects that aren't captured by the operands or other flags.
527///
528bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
529 if (!IsLICMCandidate(I))
530 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000531
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000532 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000533 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
534 const MachineOperand &MO = I.getOperand(i);
535
Dan Gohmand735b802008-10-03 15:45:36 +0000536 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000537 continue;
538
Dan Gohmanc475c362009-01-15 22:01:38 +0000539 unsigned Reg = MO.getReg();
540 if (Reg == 0) continue;
541
542 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000543 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000544 if (MO.isUse()) {
545 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000546 // and we can freely move its uses. Alternatively, if it's allocatable,
547 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000548 if (!RegInfo->def_empty(Reg))
549 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000550 if (AllocatableSet.test(Reg))
551 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000552 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000553 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
554 unsigned AliasReg = *Alias;
555 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000556 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000557 if (AllocatableSet.test(AliasReg))
558 return false;
559 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000560 // Otherwise it's safe to move.
561 continue;
562 } else if (!MO.isDead()) {
563 // A def that isn't dead. We can't move it.
564 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000565 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
566 // If the reg is live into the loop, we can't hoist an instruction
567 // which would clobber it.
568 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000569 }
570 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000571
572 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000573 continue;
574
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000575 assert(RegInfo->getVRegDef(Reg) &&
576 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000577
578 // If the loop contains the definition of an operand, then the instruction
579 // isn't loop invariant.
Dan Gohman92329c72009-12-18 01:24:09 +0000580 if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000581 return false;
582 }
583
584 // If we got this far, the instruction is loop invariant!
585 return true;
586}
587
Evan Chengaf6949d2009-02-05 08:45:46 +0000588
589/// HasPHIUses - Return true if the specified register has any PHI use.
590static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000591 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
592 UE = RegInfo->use_end(); UI != UE; ++UI) {
593 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000594 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000595 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000596 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000597 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000598}
599
Evan Cheng87b75ba2009-11-20 19:55:37 +0000600/// isLoadFromConstantMemory - Return true if the given instruction is a
601/// load from constant memory. Machine LICM will hoist these even if they are
602/// not re-materializable.
603bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
604 if (!MI->getDesc().mayLoad()) return false;
605 if (!MI->hasOneMemOperand()) return false;
606 MachineMemOperand *MMO = *MI->memoperands_begin();
607 if (MMO->isVolatile()) return false;
608 if (!MMO->getValue()) return false;
609 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
610 if (PSV) {
611 MachineFunction &MF = *MI->getParent()->getParent();
612 return PSV->isConstant(MF.getFrameInfo());
613 } else {
614 return AA->pointsToConstantMemory(MMO->getValue());
615 }
616}
617
Evan Cheng45e94d62009-02-04 09:19:56 +0000618/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
619/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000620bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000621 // FIXME: For now, only hoist re-materilizable instructions. LICM will
622 // increase register pressure. We want to make sure it doesn't increase
623 // spilling.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000624 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
625 // these tend to help performance in low register pressure situation. The
626 // trade off is it may cause spill in high pressure situation. It will end up
627 // adding a store in the loop preheader. But the reload is no more expensive.
628 // The side benefit is these loads are frequently CSE'ed.
629 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
Evan Chengc26abd92009-11-20 23:31:34 +0000630 if (!isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000631 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000632 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000633
Evan Chengaf6949d2009-02-05 08:45:46 +0000634 // If result(s) of this instruction is used by PHIs, then don't hoist it.
635 // The presence of joins makes it difficult for current register allocator
636 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000637 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
638 const MachineOperand &MO = MI.getOperand(i);
639 if (!MO.isReg() || !MO.isDef())
640 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000641 if (HasPHIUses(MO.getReg(), RegInfo))
642 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000643 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000644
645 return true;
646}
647
Dan Gohman5c952302009-10-29 17:47:20 +0000648MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
649 // If not, we may be able to unfold a load and hoist that.
650 // First test whether the instruction is loading from an amenable
651 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000652 if (!isLoadFromConstantMemory(MI))
653 return 0;
654
Dan Gohman5c952302009-10-29 17:47:20 +0000655 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000656 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000657 unsigned NewOpc =
658 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
659 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000660 /*UnfoldStore=*/false,
661 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000662 if (NewOpc == 0) return 0;
663 const TargetInstrDesc &TID = TII->get(NewOpc);
664 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000665 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000666 // Ok, we're unfolding. Create a temporary register and do the unfold.
667 unsigned Reg = RegInfo->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000668
669 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000670 SmallVector<MachineInstr *, 2> NewMIs;
671 bool Success =
672 TII->unfoldMemoryOperand(MF, MI, Reg,
673 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
674 NewMIs);
675 (void)Success;
676 assert(Success &&
677 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
678 "succeeded!");
679 assert(NewMIs.size() == 2 &&
680 "Unfolded a load into multiple instructions!");
681 MachineBasicBlock *MBB = MI->getParent();
682 MBB->insert(MI, NewMIs[0]);
683 MBB->insert(MI, NewMIs[1]);
684 // If unfolding produced a load that wasn't loop-invariant or profitable to
685 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +0000686 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +0000687 NewMIs[0]->eraseFromParent();
688 NewMIs[1]->eraseFromParent();
689 return 0;
690 }
691 // Otherwise we successfully unfolded a load that we can hoist.
692 MI->eraseFromParent();
693 return NewMIs[0];
694}
695
Evan Cheng777c6b72009-11-03 21:40:02 +0000696void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
697 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
698 const MachineInstr *MI = &*I;
699 // FIXME: For now, only hoist re-materilizable instructions. LICM will
700 // increase register pressure. We want to make sure it doesn't increase
701 // spilling.
702 if (TII->isTriviallyReMaterializable(MI, AA)) {
703 unsigned Opcode = MI->getOpcode();
704 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
705 CI = CSEMap.find(Opcode);
706 if (CI != CSEMap.end())
707 CI->second.push_back(MI);
708 else {
709 std::vector<const MachineInstr*> CSEMIs;
710 CSEMIs.push_back(MI);
711 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
712 }
713 }
714 }
715}
716
Evan Cheng78e5c112009-11-07 03:52:02 +0000717const MachineInstr*
718MachineLICM::LookForDuplicate(const MachineInstr *MI,
719 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +0000720 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
721 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +0000722 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +0000723 return PrevMI;
724 }
725 return 0;
726}
727
728bool MachineLICM::EliminateCSE(MachineInstr *MI,
729 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000730 if (CI == CSEMap.end())
731 return false;
732
733 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +0000734 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000735
736 // Replace virtual registers defined by MI by their counterparts defined
737 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +0000738 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
739 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000740
741 // Physical registers may not differ here.
742 assert((!MO.isReg() || MO.getReg() == 0 ||
743 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
744 MO.getReg() == Dup->getOperand(i).getReg()) &&
745 "Instructions with different phys regs are not identical!");
746
747 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +0000748 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000749 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +0000750 RegInfo->clearKillFlags(Dup->getOperand(i).getReg());
751 }
Evan Cheng9fb744e2009-11-05 00:51:13 +0000752 }
Evan Cheng78e5c112009-11-07 03:52:02 +0000753 MI->eraseFromParent();
754 ++NumCSEed;
755 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +0000756 }
757 return false;
758}
759
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000760/// Hoist - When an instruction is found to use only loop invariant operands
761/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000762///
Dan Gohman589f1f52009-10-28 03:21:57 +0000763void MachineLICM::Hoist(MachineInstr *MI) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000764 MachineBasicBlock *Preheader = getCurPreheader();
765 if (!Preheader) return;
766
Dan Gohman589f1f52009-10-28 03:21:57 +0000767 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +0000768 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000769 // If not, try unfolding a hoistable load.
770 MI = ExtractHoistableLoad(MI);
771 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000772 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000773
Dan Gohmanc475c362009-01-15 22:01:38 +0000774 // Now move the instructions to the predecessor, inserting it before any
775 // terminator instructions.
776 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +0000777 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000778 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000779 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000780 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000781 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000782 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000783 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +0000784 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000785 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000786
Evan Cheng777c6b72009-11-03 21:40:02 +0000787 // If this is the first instruction being hoisted to the preheader,
788 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000789 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000790 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000791 FirstInLoop = false;
792 }
Evan Cheng777c6b72009-11-03 21:40:02 +0000793
Evan Chengaf6949d2009-02-05 08:45:46 +0000794 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +0000795 unsigned Opcode = MI->getOpcode();
796 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
797 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +0000798 if (!EliminateCSE(MI, CI)) {
799 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +0000800 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000801
Dan Gohmane6cd7572010-05-13 20:34:42 +0000802 // Clear the kill flags of any register this instruction defines,
803 // since they may need to be live throughout the entire loop
804 // rather than just live for part of it.
805 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
806 MachineOperand &MO = MI->getOperand(i);
807 if (MO.isReg() && MO.isDef() && !MO.isDead())
808 RegInfo->clearKillFlags(MO.getReg());
809 }
810
Evan Chengaf6949d2009-02-05 08:45:46 +0000811 // Add to the CSE map.
812 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000813 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000814 else {
815 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000816 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000817 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +0000818 }
819 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000820
Dan Gohmanc475c362009-01-15 22:01:38 +0000821 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000822 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000823}
Dan Gohman853d3fb2010-06-22 17:25:57 +0000824
825MachineBasicBlock *MachineLICM::getCurPreheader() {
826 // Determine the block to which to hoist instructions. If we can't find a
827 // suitable loop predecessor, we can't do any hoisting.
828
829 // If we've tried to get a preheader and failed, don't try again.
830 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
831 return 0;
832
833 if (!CurPreheader) {
834 CurPreheader = CurLoop->getLoopPreheader();
835 if (!CurPreheader) {
836 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
837 if (!Pred) {
838 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
839 return 0;
840 }
841
842 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
843 if (!CurPreheader) {
844 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
845 return 0;
846 }
847 }
848 }
849 return CurPreheader;
850}