blob: d9623ab45c9ef7a7117968406e77298f16d13088 [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 Wendling074223a2008-03-10 08:13:01 +000086 // FIXME: Loop preheaders?
Bill Wendling0f940c92007-12-07 21:42:31 +000087 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88 AU.setPreservesCFG();
89 AU.addRequired<MachineLoopInfo>();
90 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +000091 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +000092 AU.addPreserved<MachineLoopInfo>();
93 AU.addPreserved<MachineDominatorTree>();
94 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +000095 }
Evan Chengaf6949d2009-02-05 08:45:46 +000096
97 virtual void releaseMemory() {
98 CSEMap.clear();
99 }
100
Bill Wendling0f940c92007-12-07 21:42:31 +0000101 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000102 /// CandidateInfo - Keep track of information about hoisting candidates.
103 struct CandidateInfo {
104 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000105 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000106 int FI;
107 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
108 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000109 };
110
111 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
112 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000113 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000114
115 /// HoistPostRA - When an instruction is found to only use loop invariant
116 /// operands that is safe to hoist, this instruction is called to do the
117 /// dirty work.
118 void HoistPostRA(MachineInstr *MI, unsigned Def);
119
120 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
121 /// gather register def and frame object update information.
122 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
123 SmallSet<int, 32> &StoredFIs,
124 SmallVector<CandidateInfo, 32> &Candidates);
125
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000126 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
127 /// current loop.
128 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000129
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000130 /// IsLICMCandidate - Returns true if the instruction may be a suitable
131 /// candidate for LICM. e.g. If the instruction is a call, then it's obviously
132 /// not safe to hoist it.
133 bool IsLICMCandidate(MachineInstr &I);
134
Bill Wendling041b3f82007-12-08 23:58:46 +0000135 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000136 /// invariant. I.e., all virtual register operands are defined outside of
137 /// the loop, physical registers aren't accessed (explicitly or implicitly),
138 /// and the instruction is hoistable.
139 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000140 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000141
Evan Cheng45e94d62009-02-04 09:19:56 +0000142 /// IsProfitableToHoist - Return true if it is potentially profitable to
143 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000144 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000145
Bill Wendling0f940c92007-12-07 21:42:31 +0000146 /// HoistRegion - Walk the specified region of the CFG (defined by all
147 /// blocks dominated by the specified block, and that are in the current
148 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
149 /// visit definitions before uses, allowing us to hoist a loop body in one
150 /// pass without iteration.
151 ///
152 void HoistRegion(MachineDomTreeNode *N);
153
Evan Cheng87b75ba2009-11-20 19:55:37 +0000154 /// isLoadFromConstantMemory - Return true if the given instruction is a
155 /// load from constant memory.
156 bool isLoadFromConstantMemory(MachineInstr *MI);
157
Dan Gohman5c952302009-10-29 17:47:20 +0000158 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
159 /// the load itself could be hoisted. Return the unfolded and hoistable
160 /// load, or null if the load couldn't be unfolded or if it wouldn't
161 /// be hoistable.
162 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
163
Evan Cheng78e5c112009-11-07 03:52:02 +0000164 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
165 /// duplicate of MI. Return this instruction if it's found.
166 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
167 std::vector<const MachineInstr*> &PrevMIs);
168
Evan Cheng9fb744e2009-11-05 00:51:13 +0000169 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
170 /// the preheader that compute the same value. If it's found, do a RAU on
171 /// with the definition of the existing instruction rather than hoisting
172 /// the instruction to the preheader.
173 bool EliminateCSE(MachineInstr *MI,
174 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
175
Bill Wendling0f940c92007-12-07 21:42:31 +0000176 /// Hoist - When an instruction is found to only use loop invariant operands
177 /// that is safe to hoist, this instruction is called to do the dirty work.
178 ///
Dan Gohman589f1f52009-10-28 03:21:57 +0000179 void Hoist(MachineInstr *MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000180
181 /// InitCSEMap - Initialize the CSE map with instructions that are in the
182 /// current loop preheader that may become duplicates of instructions that
183 /// are hoisted out of the loop.
184 void InitCSEMap(MachineBasicBlock *BB);
Bill Wendling0f940c92007-12-07 21:42:31 +0000185 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000186} // end anonymous namespace
187
Dan Gohman844731a2008-05-13 00:00:25 +0000188char MachineLICM::ID = 0;
189static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000190X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000191
Evan Chengd94671a2010-04-07 00:41:17 +0000192FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
193 return new MachineLICM(PreRegAlloc);
194}
Bill Wendling0f940c92007-12-07 21:42:31 +0000195
Dan Gohmanc475c362009-01-15 22:01:38 +0000196/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
197/// loop that has a preheader.
198static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
199 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
200 if (L->getLoopPreheader())
201 return false;
202 return true;
203}
204
Bill Wendling0f940c92007-12-07 21:42:31 +0000205bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000206 if (PreRegAlloc)
207 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
208 else
209 DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000210
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000211 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000212 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000213 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000214 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000215 MFI = MF.getFrameInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000216 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000217 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000218
219 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000220 MLI = &getAnalysis<MachineLoopInfo>();
221 DT = &getAnalysis<MachineDominatorTree>();
222 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000223
Evan Cheng4038f9c2010-04-08 01:03:47 +0000224 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I){
Bill Wendlinga17ad592007-12-11 22:22:22 +0000225 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000226
Evan Cheng4038f9c2010-04-08 01:03:47 +0000227 // If this is done before regalloc, only visit outer-most preheader-sporting
228 // loops.
229 if (PreRegAlloc && !LoopIsOuterMostWithPreheader(CurLoop))
Dan Gohmanc475c362009-01-15 22:01:38 +0000230 continue;
231
232 // Determine the block to which to hoist instructions. If we can't find a
233 // suitable loop preheader, we can't do any hoisting.
234 //
235 // FIXME: We are only hoisting if the basic block coming into this loop
236 // has only one successor. This isn't the case in general because we haven't
237 // broken critical edges or added preheaders.
238 CurPreheader = CurLoop->getLoopPreheader();
239 if (!CurPreheader)
240 continue;
241
Evan Chengd94671a2010-04-07 00:41:17 +0000242 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000243 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000244 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000245 // CSEMap is initialized for loop header when the first instruction is
246 // being hoisted.
247 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000248 FirstInLoop = true;
Evan Chengd94671a2010-04-07 00:41:17 +0000249 HoistRegion(N);
250 CSEMap.clear();
251 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000252 }
253
254 return Changed;
255}
256
Evan Cheng4038f9c2010-04-08 01:03:47 +0000257/// InstructionStoresToFI - Return true if instruction stores to the
258/// specified frame.
259static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
260 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
261 oe = MI->memoperands_end(); o != oe; ++o) {
262 if (!(*o)->isStore() || !(*o)->getValue())
263 continue;
264 if (const FixedStackPseudoSourceValue *Value =
265 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
266 if (Value->getFrameIndex() == FI)
267 return true;
268 }
269 }
270 return false;
271}
272
273/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
274/// gather register def and frame object update information.
275void MachineLICM::ProcessMI(MachineInstr *MI,
276 unsigned *PhysRegDefs,
277 SmallSet<int, 32> &StoredFIs,
278 SmallVector<CandidateInfo, 32> &Candidates) {
279 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000280 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000281 unsigned Def = 0;
282 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
283 const MachineOperand &MO = MI->getOperand(i);
284 if (MO.isFI()) {
285 // Remember if the instruction stores to the frame index.
286 int FI = MO.getIndex();
287 if (!StoredFIs.count(FI) &&
288 MFI->isSpillSlotObjectIndex(FI) &&
289 InstructionStoresToFI(MI, FI))
290 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000291 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000292 continue;
293 }
294
295 if (!MO.isReg())
296 continue;
297 unsigned Reg = MO.getReg();
298 if (!Reg)
299 continue;
300 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
301 "Not expecting virtual register!");
302
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000303 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000304 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000305 // If it's using a non-loop-invariant register, then it's obviously not
306 // safe to hoist.
307 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000308 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000309 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000310
311 if (MO.isImplicit()) {
312 ++PhysRegDefs[Reg];
313 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
314 ++PhysRegDefs[*AS];
315 if (!MO.isDead())
316 // Non-dead implicit def? This cannot be hoisted.
317 RuledOut = true;
318 // No need to check if a dead implicit def is also defined by
319 // another instruction.
320 continue;
321 }
322
323 // FIXME: For now, avoid instructions with multiple defs, unless
324 // it's a dead implicit def.
325 if (Def)
326 RuledOut = true;
327 else
328 Def = Reg;
329
330 // If we have already seen another instruction that defines the same
331 // register, then this is not safe.
332 if (++PhysRegDefs[Reg] > 1)
333 // MI defined register is seen defined by another instruction in
334 // the loop, it cannot be a LICM candidate.
335 RuledOut = true;
336 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
337 if (++PhysRegDefs[*AS] > 1)
338 RuledOut = true;
339 }
340
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000341 // Only consider reloads for now and remats which do not have register
342 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000343 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000344 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000345 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000346 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
347 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000348 }
349}
350
351/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
352/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000353void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000354 unsigned NumRegs = TRI->getNumRegs();
355 unsigned *PhysRegDefs = new unsigned[NumRegs];
356 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
357
Evan Cheng4038f9c2010-04-08 01:03:47 +0000358 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000359 SmallSet<int, 32> StoredFIs;
360
361 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000362 // collect potential LICM candidates.
363 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
364 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
365 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000366 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000367 // FIXME: That means a reload that're reused in successor block(s) will not
368 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000369 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000370 E = BB->livein_end(); I != E; ++I) {
371 unsigned Reg = *I;
372 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000373 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
374 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000375 }
376
377 for (MachineBasicBlock::iterator
378 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000379 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000380 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000381 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000382 }
Evan Chengd94671a2010-04-07 00:41:17 +0000383
384 // Now evaluate whether the potential candidates qualify.
385 // 1. Check if the candidate defined register is defined by another
386 // instruction in the loop.
387 // 2. If the candidate is a load from stack slot (always true for now),
388 // check if the slot is stored anywhere in the loop.
389 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000390 if (Candidates[i].FI != INT_MIN &&
391 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000392 continue;
393
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000394 if (PhysRegDefs[Candidates[i].Def] == 1) {
395 bool Safe = true;
396 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000397 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
398 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000399 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000400 continue;
401 if (PhysRegDefs[MO.getReg()]) {
402 // If it's using a non-loop-invariant register, then it's obviously
403 // not safe to hoist.
404 Safe = false;
405 break;
406 }
407 }
408 if (Safe)
409 HoistPostRA(MI, Candidates[i].Def);
410 }
Evan Chengd94671a2010-04-07 00:41:17 +0000411 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000412
413 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000414}
415
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000416/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
417/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000418void MachineLICM::AddToLiveIns(unsigned Reg) {
419 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000420 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
421 MachineBasicBlock *BB = Blocks[i];
422 if (!BB->isLiveIn(Reg))
423 BB->addLiveIn(Reg);
424 for (MachineBasicBlock::iterator
425 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
426 MachineInstr *MI = &*MII;
427 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
428 MachineOperand &MO = MI->getOperand(i);
429 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
430 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
431 MO.setIsKill(false);
432 }
433 }
434 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000435}
436
437/// HoistPostRA - When an instruction is found to only use loop invariant
438/// operands that is safe to hoist, this instruction is called to do the
439/// dirty work.
440void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Evan Chengd94671a2010-04-07 00:41:17 +0000441 // Now move the instructions to the predecessor, inserting it before any
442 // terminator instructions.
443 DEBUG({
444 dbgs() << "Hoisting " << *MI;
445 if (CurPreheader->getBasicBlock())
446 dbgs() << " to MachineBasicBlock "
447 << CurPreheader->getName();
448 if (MI->getParent()->getBasicBlock())
449 dbgs() << " from MachineBasicBlock "
450 << MI->getParent()->getName();
451 dbgs() << "\n";
452 });
453
454 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000455 MachineBasicBlock *MBB = MI->getParent();
456 CurPreheader->splice(CurPreheader->getFirstTerminator(), MBB, MI);
457
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000458 // Add register to livein list to all the BBs in the current loop since a
459 // loop invariant must be kept live throughout the whole loop. This is
460 // important to ensure later passes do not scavenge the def register.
461 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000462
463 ++NumPostRAHoisted;
464 Changed = true;
465}
466
Bill Wendling0f940c92007-12-07 21:42:31 +0000467/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
468/// dominated by the specified block, and that are in the current loop) in depth
469/// first order w.r.t the DominatorTree. This allows us to visit definitions
470/// before uses, allowing us to hoist a loop body in one pass without iteration.
471///
472void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
473 assert(N != 0 && "Null dominator tree node?");
474 MachineBasicBlock *BB = N->getBlock();
475
476 // If this subregion is not in the top level loop at all, exit.
477 if (!CurLoop->contains(BB)) return;
478
Dan Gohmanc475c362009-01-15 22:01:38 +0000479 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000480 MII = BB->begin(), E = BB->end(); MII != E; ) {
481 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000482 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000483 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000484 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000485
486 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Bill Wendling0f940c92007-12-07 21:42:31 +0000487 for (unsigned I = 0, E = Children.size(); I != E; ++I)
488 HoistRegion(Children[I]);
489}
490
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000491/// IsLICMCandidate - Returns true if the instruction may be a suitable
492/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
493/// not safe to hoist it.
494bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Evan Cheng63275372010-04-13 22:13:34 +0000495 if (I.isImplicitDef())
496 return false;
497
Chris Lattnera22edc82008-01-10 23:08:24 +0000498 const TargetInstrDesc &TID = I.getDesc();
499
500 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000501 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000502 TID.hasUnmodeledSideEffects())
503 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000504
Chris Lattnera22edc82008-01-10 23:08:24 +0000505 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000506 // Okay, this instruction does a load. As a refinement, we allow the target
507 // to decide whether the loaded value is actually a constant. If so, we can
508 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000509 if (!I.isInvariantLoad(AA))
Evan Cheng7adcdc32009-11-17 19:19:01 +0000510 // FIXME: we should be able to hoist loads with no other side effects if
511 // there are no other instructions which can change memory in this loop.
512 // This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000513 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000514 }
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000515 return true;
516}
517
518/// IsLoopInvariantInst - Returns true if the instruction is loop
519/// invariant. I.e., all virtual register operands are defined outside of the
520/// loop, physical registers aren't accessed explicitly, and there are no side
521/// effects that aren't captured by the operands or other flags.
522///
523bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
524 if (!IsLICMCandidate(I))
525 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000526
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000527 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000528 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
529 const MachineOperand &MO = I.getOperand(i);
530
Dan Gohmand735b802008-10-03 15:45:36 +0000531 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000532 continue;
533
Dan Gohmanc475c362009-01-15 22:01:38 +0000534 unsigned Reg = MO.getReg();
535 if (Reg == 0) continue;
536
537 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000538 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000539 if (MO.isUse()) {
540 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000541 // and we can freely move its uses. Alternatively, if it's allocatable,
542 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000543 if (!RegInfo->def_empty(Reg))
544 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000545 if (AllocatableSet.test(Reg))
546 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000547 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000548 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
549 unsigned AliasReg = *Alias;
550 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000551 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000552 if (AllocatableSet.test(AliasReg))
553 return false;
554 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000555 // Otherwise it's safe to move.
556 continue;
557 } else if (!MO.isDead()) {
558 // A def that isn't dead. We can't move it.
559 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000560 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
561 // If the reg is live into the loop, we can't hoist an instruction
562 // which would clobber it.
563 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000564 }
565 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000566
567 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000568 continue;
569
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000570 assert(RegInfo->getVRegDef(Reg) &&
571 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000572
573 // If the loop contains the definition of an operand, then the instruction
574 // isn't loop invariant.
Dan Gohman92329c72009-12-18 01:24:09 +0000575 if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000576 return false;
577 }
578
579 // If we got this far, the instruction is loop invariant!
580 return true;
581}
582
Evan Chengaf6949d2009-02-05 08:45:46 +0000583
584/// HasPHIUses - Return true if the specified register has any PHI use.
585static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000586 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
587 UE = RegInfo->use_end(); UI != UE; ++UI) {
588 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000589 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000590 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000591 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000592 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000593}
594
Evan Cheng87b75ba2009-11-20 19:55:37 +0000595/// isLoadFromConstantMemory - Return true if the given instruction is a
596/// load from constant memory. Machine LICM will hoist these even if they are
597/// not re-materializable.
598bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
599 if (!MI->getDesc().mayLoad()) return false;
600 if (!MI->hasOneMemOperand()) return false;
601 MachineMemOperand *MMO = *MI->memoperands_begin();
602 if (MMO->isVolatile()) return false;
603 if (!MMO->getValue()) return false;
604 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
605 if (PSV) {
606 MachineFunction &MF = *MI->getParent()->getParent();
607 return PSV->isConstant(MF.getFrameInfo());
608 } else {
609 return AA->pointsToConstantMemory(MMO->getValue());
610 }
611}
612
Evan Cheng45e94d62009-02-04 09:19:56 +0000613/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
614/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000615bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000616 // FIXME: For now, only hoist re-materilizable instructions. LICM will
617 // increase register pressure. We want to make sure it doesn't increase
618 // spilling.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000619 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
620 // these tend to help performance in low register pressure situation. The
621 // trade off is it may cause spill in high pressure situation. It will end up
622 // adding a store in the loop preheader. But the reload is no more expensive.
623 // The side benefit is these loads are frequently CSE'ed.
624 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
Evan Chengc26abd92009-11-20 23:31:34 +0000625 if (!isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000626 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000627 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000628
Evan Chengaf6949d2009-02-05 08:45:46 +0000629 // If result(s) of this instruction is used by PHIs, then don't hoist it.
630 // The presence of joins makes it difficult for current register allocator
631 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000632 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
633 const MachineOperand &MO = MI.getOperand(i);
634 if (!MO.isReg() || !MO.isDef())
635 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000636 if (HasPHIUses(MO.getReg(), RegInfo))
637 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000638 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000639
640 return true;
641}
642
Dan Gohman5c952302009-10-29 17:47:20 +0000643MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
644 // If not, we may be able to unfold a load and hoist that.
645 // First test whether the instruction is loading from an amenable
646 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000647 if (!isLoadFromConstantMemory(MI))
648 return 0;
649
Dan Gohman5c952302009-10-29 17:47:20 +0000650 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000651 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000652 unsigned NewOpc =
653 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
654 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000655 /*UnfoldStore=*/false,
656 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000657 if (NewOpc == 0) return 0;
658 const TargetInstrDesc &TID = TII->get(NewOpc);
659 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000660 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000661 // Ok, we're unfolding. Create a temporary register and do the unfold.
662 unsigned Reg = RegInfo->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000663
664 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000665 SmallVector<MachineInstr *, 2> NewMIs;
666 bool Success =
667 TII->unfoldMemoryOperand(MF, MI, Reg,
668 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
669 NewMIs);
670 (void)Success;
671 assert(Success &&
672 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
673 "succeeded!");
674 assert(NewMIs.size() == 2 &&
675 "Unfolded a load into multiple instructions!");
676 MachineBasicBlock *MBB = MI->getParent();
677 MBB->insert(MI, NewMIs[0]);
678 MBB->insert(MI, NewMIs[1]);
679 // If unfolding produced a load that wasn't loop-invariant or profitable to
680 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +0000681 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +0000682 NewMIs[0]->eraseFromParent();
683 NewMIs[1]->eraseFromParent();
684 return 0;
685 }
686 // Otherwise we successfully unfolded a load that we can hoist.
687 MI->eraseFromParent();
688 return NewMIs[0];
689}
690
Evan Cheng777c6b72009-11-03 21:40:02 +0000691void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
692 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
693 const MachineInstr *MI = &*I;
694 // FIXME: For now, only hoist re-materilizable instructions. LICM will
695 // increase register pressure. We want to make sure it doesn't increase
696 // spilling.
697 if (TII->isTriviallyReMaterializable(MI, AA)) {
698 unsigned Opcode = MI->getOpcode();
699 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
700 CI = CSEMap.find(Opcode);
701 if (CI != CSEMap.end())
702 CI->second.push_back(MI);
703 else {
704 std::vector<const MachineInstr*> CSEMIs;
705 CSEMIs.push_back(MI);
706 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
707 }
708 }
709 }
710}
711
Evan Cheng78e5c112009-11-07 03:52:02 +0000712const MachineInstr*
713MachineLICM::LookForDuplicate(const MachineInstr *MI,
714 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +0000715 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
716 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +0000717 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +0000718 return PrevMI;
719 }
720 return 0;
721}
722
723bool MachineLICM::EliminateCSE(MachineInstr *MI,
724 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000725 if (CI == CSEMap.end())
726 return false;
727
728 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +0000729 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000730
731 // Replace virtual registers defined by MI by their counterparts defined
732 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +0000733 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
734 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000735
736 // Physical registers may not differ here.
737 assert((!MO.isReg() || MO.getReg() == 0 ||
738 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
739 MO.getReg() == Dup->getOperand(i).getReg()) &&
740 "Instructions with different phys regs are not identical!");
741
742 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +0000743 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000744 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +0000745 RegInfo->clearKillFlags(Dup->getOperand(i).getReg());
746 }
Evan Cheng9fb744e2009-11-05 00:51:13 +0000747 }
Evan Cheng78e5c112009-11-07 03:52:02 +0000748 MI->eraseFromParent();
749 ++NumCSEed;
750 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +0000751 }
752 return false;
753}
754
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000755/// Hoist - When an instruction is found to use only loop invariant operands
756/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000757///
Dan Gohman589f1f52009-10-28 03:21:57 +0000758void MachineLICM::Hoist(MachineInstr *MI) {
759 // 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 Gohmanc475c362009-01-15 22:01:38 +0000770 if (CurPreheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000771 dbgs() << " to MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000772 << CurPreheader->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) {
782 InitCSEMap(CurPreheader);
783 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.
Evan Cheng777c6b72009-11-03 21:40:02 +0000792 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
793
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}