blob: 9b24a9a2391b549a0c367767c2b79f5e90347fcc [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 Gohmanc475c362009-01-15 22:01:38 +0000202 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000203 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000204 return false;
205 return true;
206}
207
Bill Wendling0f940c92007-12-07 21:42:31 +0000208bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000209 if (PreRegAlloc)
210 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
211 else
212 DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000213
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000214 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000215 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000216 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000217 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000218 MFI = MF.getFrameInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000219 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000220 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000221
222 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000223 MLI = &getAnalysis<MachineLoopInfo>();
224 DT = &getAnalysis<MachineDominatorTree>();
225 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000226
Evan Cheng4038f9c2010-04-08 01:03:47 +0000227 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I){
Bill Wendlinga17ad592007-12-11 22:22:22 +0000228 CurLoop = *I;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000229 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000230
Evan Cheng4038f9c2010-04-08 01:03:47 +0000231 // If this is done before regalloc, only visit outer-most preheader-sporting
232 // loops.
Dan Gohman853d3fb2010-06-22 17:25:57 +0000233 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop))
Dan Gohmanc475c362009-01-15 22:01:38 +0000234 continue;
235
Evan Chengd94671a2010-04-07 00:41:17 +0000236 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000237 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000238 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000239 // CSEMap is initialized for loop header when the first instruction is
240 // being hoisted.
241 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000242 FirstInLoop = true;
Evan Chengd94671a2010-04-07 00:41:17 +0000243 HoistRegion(N);
244 CSEMap.clear();
245 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000246 }
247
248 return Changed;
249}
250
Evan Cheng4038f9c2010-04-08 01:03:47 +0000251/// InstructionStoresToFI - Return true if instruction stores to the
252/// specified frame.
253static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
254 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
255 oe = MI->memoperands_end(); o != oe; ++o) {
256 if (!(*o)->isStore() || !(*o)->getValue())
257 continue;
258 if (const FixedStackPseudoSourceValue *Value =
259 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
260 if (Value->getFrameIndex() == FI)
261 return true;
262 }
263 }
264 return false;
265}
266
267/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
268/// gather register def and frame object update information.
269void MachineLICM::ProcessMI(MachineInstr *MI,
270 unsigned *PhysRegDefs,
271 SmallSet<int, 32> &StoredFIs,
272 SmallVector<CandidateInfo, 32> &Candidates) {
273 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000274 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000275 unsigned Def = 0;
276 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
277 const MachineOperand &MO = MI->getOperand(i);
278 if (MO.isFI()) {
279 // Remember if the instruction stores to the frame index.
280 int FI = MO.getIndex();
281 if (!StoredFIs.count(FI) &&
282 MFI->isSpillSlotObjectIndex(FI) &&
283 InstructionStoresToFI(MI, FI))
284 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000285 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000286 continue;
287 }
288
289 if (!MO.isReg())
290 continue;
291 unsigned Reg = MO.getReg();
292 if (!Reg)
293 continue;
294 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
295 "Not expecting virtual register!");
296
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000297 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000298 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000299 // If it's using a non-loop-invariant register, then it's obviously not
300 // safe to hoist.
301 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000302 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000303 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000304
305 if (MO.isImplicit()) {
306 ++PhysRegDefs[Reg];
307 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
308 ++PhysRegDefs[*AS];
309 if (!MO.isDead())
310 // Non-dead implicit def? This cannot be hoisted.
311 RuledOut = true;
312 // No need to check if a dead implicit def is also defined by
313 // another instruction.
314 continue;
315 }
316
317 // FIXME: For now, avoid instructions with multiple defs, unless
318 // it's a dead implicit def.
319 if (Def)
320 RuledOut = true;
321 else
322 Def = Reg;
323
324 // If we have already seen another instruction that defines the same
325 // register, then this is not safe.
326 if (++PhysRegDefs[Reg] > 1)
327 // MI defined register is seen defined by another instruction in
328 // the loop, it cannot be a LICM candidate.
329 RuledOut = true;
330 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
331 if (++PhysRegDefs[*AS] > 1)
332 RuledOut = true;
333 }
334
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000335 // Only consider reloads for now and remats which do not have register
336 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000337 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000338 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000339 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000340 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
341 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000342 }
343}
344
345/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
346/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000347void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000348 unsigned NumRegs = TRI->getNumRegs();
349 unsigned *PhysRegDefs = new unsigned[NumRegs];
350 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
351
Evan Cheng4038f9c2010-04-08 01:03:47 +0000352 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000353 SmallSet<int, 32> StoredFIs;
354
355 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000356 // collect potential LICM candidates.
357 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
358 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
359 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000360 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000361 // FIXME: That means a reload that're reused in successor block(s) will not
362 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000363 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000364 E = BB->livein_end(); I != E; ++I) {
365 unsigned Reg = *I;
366 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000367 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
368 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000369 }
370
371 for (MachineBasicBlock::iterator
372 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000373 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000374 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000375 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000376 }
Evan Chengd94671a2010-04-07 00:41:17 +0000377
378 // Now evaluate whether the potential candidates qualify.
379 // 1. Check if the candidate defined register is defined by another
380 // instruction in the loop.
381 // 2. If the candidate is a load from stack slot (always true for now),
382 // check if the slot is stored anywhere in the loop.
383 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000384 if (Candidates[i].FI != INT_MIN &&
385 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000386 continue;
387
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000388 if (PhysRegDefs[Candidates[i].Def] == 1) {
389 bool Safe = true;
390 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000391 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
392 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000393 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000394 continue;
395 if (PhysRegDefs[MO.getReg()]) {
396 // If it's using a non-loop-invariant register, then it's obviously
397 // not safe to hoist.
398 Safe = false;
399 break;
400 }
401 }
402 if (Safe)
403 HoistPostRA(MI, Candidates[i].Def);
404 }
Evan Chengd94671a2010-04-07 00:41:17 +0000405 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000406
407 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000408}
409
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000410/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
411/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000412void MachineLICM::AddToLiveIns(unsigned Reg) {
413 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000414 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
415 MachineBasicBlock *BB = Blocks[i];
416 if (!BB->isLiveIn(Reg))
417 BB->addLiveIn(Reg);
418 for (MachineBasicBlock::iterator
419 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
420 MachineInstr *MI = &*MII;
421 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
422 MachineOperand &MO = MI->getOperand(i);
423 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
424 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
425 MO.setIsKill(false);
426 }
427 }
428 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000429}
430
431/// HoistPostRA - When an instruction is found to only use loop invariant
432/// operands that is safe to hoist, this instruction is called to do the
433/// dirty work.
434void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000435 MachineBasicBlock *Preheader = getCurPreheader();
436 if (!Preheader) return;
437
Evan Chengd94671a2010-04-07 00:41:17 +0000438 // Now move the instructions to the predecessor, inserting it before any
439 // terminator instructions.
440 DEBUG({
441 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000442 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000443 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000444 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000445 if (MI->getParent()->getBasicBlock())
446 dbgs() << " from MachineBasicBlock "
447 << MI->getParent()->getName();
448 dbgs() << "\n";
449 });
450
451 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000452 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000453 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000454
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000455 // Add register to livein list to all the BBs in the current loop since a
456 // loop invariant must be kept live throughout the whole loop. This is
457 // important to ensure later passes do not scavenge the def register.
458 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000459
460 ++NumPostRAHoisted;
461 Changed = true;
462}
463
Bill Wendling0f940c92007-12-07 21:42:31 +0000464/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
465/// dominated by the specified block, and that are in the current loop) in depth
466/// first order w.r.t the DominatorTree. This allows us to visit definitions
467/// before uses, allowing us to hoist a loop body in one pass without iteration.
468///
469void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
470 assert(N != 0 && "Null dominator tree node?");
471 MachineBasicBlock *BB = N->getBlock();
472
473 // If this subregion is not in the top level loop at all, exit.
474 if (!CurLoop->contains(BB)) return;
475
Dan Gohmanc475c362009-01-15 22:01:38 +0000476 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000477 MII = BB->begin(), E = BB->end(); MII != E; ) {
478 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000479 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000480 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000481 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000482
483 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Bill Wendling0f940c92007-12-07 21:42:31 +0000484 for (unsigned I = 0, E = Children.size(); I != E; ++I)
485 HoistRegion(Children[I]);
486}
487
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000488/// IsLICMCandidate - Returns true if the instruction may be a suitable
489/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
490/// not safe to hoist it.
491bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Evan Cheng63275372010-04-13 22:13:34 +0000492 if (I.isImplicitDef())
493 return false;
494
Chris Lattnera22edc82008-01-10 23:08:24 +0000495 const TargetInstrDesc &TID = I.getDesc();
496
497 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000498 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000499 TID.hasUnmodeledSideEffects())
500 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000501
Chris Lattnera22edc82008-01-10 23:08:24 +0000502 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000503 // Okay, this instruction does a load. As a refinement, we allow the target
504 // to decide whether the loaded value is actually a constant. If so, we can
505 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000506 if (!I.isInvariantLoad(AA))
Evan Cheng7adcdc32009-11-17 19:19:01 +0000507 // FIXME: we should be able to hoist loads with no other side effects if
508 // there are no other instructions which can change memory in this loop.
509 // This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000510 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000511 }
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000512 return true;
513}
514
515/// IsLoopInvariantInst - Returns true if the instruction is loop
516/// invariant. I.e., all virtual register operands are defined outside of the
517/// loop, physical registers aren't accessed explicitly, and there are no side
518/// effects that aren't captured by the operands or other flags.
519///
520bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
521 if (!IsLICMCandidate(I))
522 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000523
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000524 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000525 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
526 const MachineOperand &MO = I.getOperand(i);
527
Dan Gohmand735b802008-10-03 15:45:36 +0000528 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000529 continue;
530
Dan Gohmanc475c362009-01-15 22:01:38 +0000531 unsigned Reg = MO.getReg();
532 if (Reg == 0) continue;
533
534 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000535 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000536 if (MO.isUse()) {
537 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000538 // and we can freely move its uses. Alternatively, if it's allocatable,
539 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000540 if (!RegInfo->def_empty(Reg))
541 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000542 if (AllocatableSet.test(Reg))
543 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000544 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000545 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
546 unsigned AliasReg = *Alias;
547 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000548 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000549 if (AllocatableSet.test(AliasReg))
550 return false;
551 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000552 // Otherwise it's safe to move.
553 continue;
554 } else if (!MO.isDead()) {
555 // A def that isn't dead. We can't move it.
556 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000557 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
558 // If the reg is live into the loop, we can't hoist an instruction
559 // which would clobber it.
560 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000561 }
562 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000563
564 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000565 continue;
566
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000567 assert(RegInfo->getVRegDef(Reg) &&
568 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000569
570 // If the loop contains the definition of an operand, then the instruction
571 // isn't loop invariant.
Dan Gohman92329c72009-12-18 01:24:09 +0000572 if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000573 return false;
574 }
575
576 // If we got this far, the instruction is loop invariant!
577 return true;
578}
579
Evan Chengaf6949d2009-02-05 08:45:46 +0000580
581/// HasPHIUses - Return true if the specified register has any PHI use.
582static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000583 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
584 UE = RegInfo->use_end(); UI != UE; ++UI) {
585 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000586 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000587 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000588 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000589 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000590}
591
Evan Cheng87b75ba2009-11-20 19:55:37 +0000592/// isLoadFromConstantMemory - Return true if the given instruction is a
593/// load from constant memory. Machine LICM will hoist these even if they are
594/// not re-materializable.
595bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
596 if (!MI->getDesc().mayLoad()) return false;
597 if (!MI->hasOneMemOperand()) return false;
598 MachineMemOperand *MMO = *MI->memoperands_begin();
599 if (MMO->isVolatile()) return false;
600 if (!MMO->getValue()) return false;
601 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
602 if (PSV) {
603 MachineFunction &MF = *MI->getParent()->getParent();
604 return PSV->isConstant(MF.getFrameInfo());
605 } else {
606 return AA->pointsToConstantMemory(MMO->getValue());
607 }
608}
609
Evan Cheng45e94d62009-02-04 09:19:56 +0000610/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
611/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000612bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000613 // FIXME: For now, only hoist re-materilizable instructions. LICM will
614 // increase register pressure. We want to make sure it doesn't increase
615 // spilling.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000616 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
617 // these tend to help performance in low register pressure situation. The
618 // trade off is it may cause spill in high pressure situation. It will end up
619 // adding a store in the loop preheader. But the reload is no more expensive.
620 // The side benefit is these loads are frequently CSE'ed.
621 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
Evan Chengc26abd92009-11-20 23:31:34 +0000622 if (!isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000623 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000624 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000625
Evan Chengaf6949d2009-02-05 08:45:46 +0000626 // If result(s) of this instruction is used by PHIs, then don't hoist it.
627 // The presence of joins makes it difficult for current register allocator
628 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000629 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
630 const MachineOperand &MO = MI.getOperand(i);
631 if (!MO.isReg() || !MO.isDef())
632 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000633 if (HasPHIUses(MO.getReg(), RegInfo))
634 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000635 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000636
637 return true;
638}
639
Dan Gohman5c952302009-10-29 17:47:20 +0000640MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
641 // If not, we may be able to unfold a load and hoist that.
642 // First test whether the instruction is loading from an amenable
643 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000644 if (!isLoadFromConstantMemory(MI))
645 return 0;
646
Dan Gohman5c952302009-10-29 17:47:20 +0000647 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000648 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000649 unsigned NewOpc =
650 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
651 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000652 /*UnfoldStore=*/false,
653 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000654 if (NewOpc == 0) return 0;
655 const TargetInstrDesc &TID = TII->get(NewOpc);
656 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000657 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000658 // Ok, we're unfolding. Create a temporary register and do the unfold.
659 unsigned Reg = RegInfo->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000660
661 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000662 SmallVector<MachineInstr *, 2> NewMIs;
663 bool Success =
664 TII->unfoldMemoryOperand(MF, MI, Reg,
665 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
666 NewMIs);
667 (void)Success;
668 assert(Success &&
669 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
670 "succeeded!");
671 assert(NewMIs.size() == 2 &&
672 "Unfolded a load into multiple instructions!");
673 MachineBasicBlock *MBB = MI->getParent();
674 MBB->insert(MI, NewMIs[0]);
675 MBB->insert(MI, NewMIs[1]);
676 // If unfolding produced a load that wasn't loop-invariant or profitable to
677 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +0000678 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +0000679 NewMIs[0]->eraseFromParent();
680 NewMIs[1]->eraseFromParent();
681 return 0;
682 }
683 // Otherwise we successfully unfolded a load that we can hoist.
684 MI->eraseFromParent();
685 return NewMIs[0];
686}
687
Evan Cheng777c6b72009-11-03 21:40:02 +0000688void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
689 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
690 const MachineInstr *MI = &*I;
691 // FIXME: For now, only hoist re-materilizable instructions. LICM will
692 // increase register pressure. We want to make sure it doesn't increase
693 // spilling.
694 if (TII->isTriviallyReMaterializable(MI, AA)) {
695 unsigned Opcode = MI->getOpcode();
696 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
697 CI = CSEMap.find(Opcode);
698 if (CI != CSEMap.end())
699 CI->second.push_back(MI);
700 else {
701 std::vector<const MachineInstr*> CSEMIs;
702 CSEMIs.push_back(MI);
703 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
704 }
705 }
706 }
707}
708
Evan Cheng78e5c112009-11-07 03:52:02 +0000709const MachineInstr*
710MachineLICM::LookForDuplicate(const MachineInstr *MI,
711 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +0000712 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
713 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +0000714 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +0000715 return PrevMI;
716 }
717 return 0;
718}
719
720bool MachineLICM::EliminateCSE(MachineInstr *MI,
721 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000722 if (CI == CSEMap.end())
723 return false;
724
725 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +0000726 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000727
728 // Replace virtual registers defined by MI by their counterparts defined
729 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +0000730 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
731 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000732
733 // Physical registers may not differ here.
734 assert((!MO.isReg() || MO.getReg() == 0 ||
735 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
736 MO.getReg() == Dup->getOperand(i).getReg()) &&
737 "Instructions with different phys regs are not identical!");
738
739 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +0000740 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000741 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +0000742 RegInfo->clearKillFlags(Dup->getOperand(i).getReg());
743 }
Evan Cheng9fb744e2009-11-05 00:51:13 +0000744 }
Evan Cheng78e5c112009-11-07 03:52:02 +0000745 MI->eraseFromParent();
746 ++NumCSEed;
747 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +0000748 }
749 return false;
750}
751
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000752/// Hoist - When an instruction is found to use only loop invariant operands
753/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000754///
Dan Gohman589f1f52009-10-28 03:21:57 +0000755void MachineLICM::Hoist(MachineInstr *MI) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000756 MachineBasicBlock *Preheader = getCurPreheader();
757 if (!Preheader) return;
758
Dan Gohman589f1f52009-10-28 03:21:57 +0000759 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +0000760 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000761 // If not, try unfolding a hoistable load.
762 MI = ExtractHoistableLoad(MI);
763 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000764 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000765
Dan Gohmanc475c362009-01-15 22:01:38 +0000766 // Now move the instructions to the predecessor, inserting it before any
767 // terminator instructions.
768 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +0000769 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000770 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000771 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000772 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000773 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000774 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000775 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +0000776 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000777 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000778
Evan Cheng777c6b72009-11-03 21:40:02 +0000779 // If this is the first instruction being hoisted to the preheader,
780 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000781 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000782 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000783 FirstInLoop = false;
784 }
Evan Cheng777c6b72009-11-03 21:40:02 +0000785
Evan Chengaf6949d2009-02-05 08:45:46 +0000786 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +0000787 unsigned Opcode = MI->getOpcode();
788 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
789 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +0000790 if (!EliminateCSE(MI, CI)) {
791 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +0000792 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000793
Dan Gohmane6cd7572010-05-13 20:34:42 +0000794 // Clear the kill flags of any register this instruction defines,
795 // since they may need to be live throughout the entire loop
796 // rather than just live for part of it.
797 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
798 MachineOperand &MO = MI->getOperand(i);
799 if (MO.isReg() && MO.isDef() && !MO.isDead())
800 RegInfo->clearKillFlags(MO.getReg());
801 }
802
Evan Chengaf6949d2009-02-05 08:45:46 +0000803 // Add to the CSE map.
804 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000805 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000806 else {
807 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000808 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000809 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +0000810 }
811 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000812
Dan Gohmanc475c362009-01-15 22:01:38 +0000813 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000814 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000815}
Dan Gohman853d3fb2010-06-22 17:25:57 +0000816
817MachineBasicBlock *MachineLICM::getCurPreheader() {
818 // Determine the block to which to hoist instructions. If we can't find a
819 // suitable loop predecessor, we can't do any hoisting.
820
821 // If we've tried to get a preheader and failed, don't try again.
822 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
823 return 0;
824
825 if (!CurPreheader) {
826 CurPreheader = CurLoop->getLoopPreheader();
827 if (!CurPreheader) {
828 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
829 if (!Pred) {
830 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
831 return 0;
832 }
833
834 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
835 if (!CurPreheader) {
836 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
837 return 0;
838 }
839 }
840 }
841 return CurPreheader;
842}