blob: 1db30d8c4e608c2064d05690a7739c7e7b78d105 [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.
65 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000066 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000067
Evan Chengd94671a2010-04-07 00:41:17 +000068 BitVector AllocatableSet;
69
Evan Cheng777c6b72009-11-03 21:40:02 +000070 // For each opcode, keep a list of potentail CSE instructions.
71 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000072
Bill Wendling0f940c92007-12-07 21:42:31 +000073 public:
74 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +000075 MachineLICM() :
76 MachineFunctionPass(&ID), PreRegAlloc(true) {}
77
78 explicit MachineLICM(bool PreRA) :
79 MachineFunctionPass(&ID), PreRegAlloc(PreRA) {}
Bill Wendling0f940c92007-12-07 21:42:31 +000080
81 virtual bool runOnMachineFunction(MachineFunction &MF);
82
Dan Gohman72241702008-12-18 01:37:56 +000083 const char *getPassName() const { return "Machine Instruction LICM"; }
84
Bill Wendling074223a2008-03-10 08:13:01 +000085 // FIXME: Loop preheaders?
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.
112 void HoistRegionPostRA(MachineDomTreeNode *N);
113
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
125 /// AddToLiveIns - Add 'Reg' to the livein sets of BBs in the backedge path
126 /// from MBB to LoopHeader (inclusive).
127 void AddToLiveIns(unsigned Reg,
128 MachineBasicBlock *MBB, MachineBasicBlock *LoopHeader);
129
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 Cheng4038f9c2010-04-08 01:03:47 +0000211 Changed = 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 Cheng777c6b72009-11-03 21:40:02 +0000242 // CSEMap is initialized for loop header when the first instruction is
243 // being hoisted.
Evan Chengd94671a2010-04-07 00:41:17 +0000244 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
245 if (!PreRegAlloc)
246 HoistRegionPostRA(N);
247 else {
248 HoistRegion(N);
249 CSEMap.clear();
250 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000251 }
252
253 return Changed;
254}
255
Evan Cheng4038f9c2010-04-08 01:03:47 +0000256/// InstructionStoresToFI - Return true if instruction stores to the
257/// specified frame.
258static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
259 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
260 oe = MI->memoperands_end(); o != oe; ++o) {
261 if (!(*o)->isStore() || !(*o)->getValue())
262 continue;
263 if (const FixedStackPseudoSourceValue *Value =
264 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
265 if (Value->getFrameIndex() == FI)
266 return true;
267 }
268 }
269 return false;
270}
271
272/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
273/// gather register def and frame object update information.
274void MachineLICM::ProcessMI(MachineInstr *MI,
275 unsigned *PhysRegDefs,
276 SmallSet<int, 32> &StoredFIs,
277 SmallVector<CandidateInfo, 32> &Candidates) {
278 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000279 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000280 unsigned Def = 0;
281 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
282 const MachineOperand &MO = MI->getOperand(i);
283 if (MO.isFI()) {
284 // Remember if the instruction stores to the frame index.
285 int FI = MO.getIndex();
286 if (!StoredFIs.count(FI) &&
287 MFI->isSpillSlotObjectIndex(FI) &&
288 InstructionStoresToFI(MI, FI))
289 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000290 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000291 continue;
292 }
293
294 if (!MO.isReg())
295 continue;
296 unsigned Reg = MO.getReg();
297 if (!Reg)
298 continue;
299 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
300 "Not expecting virtual register!");
301
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000302 if (!MO.isDef()) {
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000303 if (PhysRegDefs[Reg])
304 // If it's using a non-loop-invariant register, then it's obviously not
305 // safe to hoist.
306 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000307 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000308 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000309
310 if (MO.isImplicit()) {
311 ++PhysRegDefs[Reg];
312 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
313 ++PhysRegDefs[*AS];
314 if (!MO.isDead())
315 // Non-dead implicit def? This cannot be hoisted.
316 RuledOut = true;
317 // No need to check if a dead implicit def is also defined by
318 // another instruction.
319 continue;
320 }
321
322 // FIXME: For now, avoid instructions with multiple defs, unless
323 // it's a dead implicit def.
324 if (Def)
325 RuledOut = true;
326 else
327 Def = Reg;
328
329 // If we have already seen another instruction that defines the same
330 // register, then this is not safe.
331 if (++PhysRegDefs[Reg] > 1)
332 // MI defined register is seen defined by another instruction in
333 // the loop, it cannot be a LICM candidate.
334 RuledOut = true;
335 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
336 if (++PhysRegDefs[*AS] > 1)
337 RuledOut = true;
338 }
339
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000340 // Only consider reloads for now and remats which do not have register
341 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000342 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000343 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000344 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000345 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
346 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000347 }
348}
349
350/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
351/// invariants out to the preheader.
Evan Chengd94671a2010-04-07 00:41:17 +0000352void MachineLICM::HoistRegionPostRA(MachineDomTreeNode *N) {
353 assert(N != 0 && "Null dominator tree node?");
354
355 unsigned NumRegs = TRI->getNumRegs();
356 unsigned *PhysRegDefs = new unsigned[NumRegs];
357 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
358
Evan Cheng4038f9c2010-04-08 01:03:47 +0000359 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000360 SmallSet<int, 32> StoredFIs;
361
362 // Walk the entire region, count number of defs for each register, and
363 // return potential LICM candidates.
364 SmallVector<MachineDomTreeNode*, 8> WorkList;
365 WorkList.push_back(N);
366 do {
367 N = WorkList.pop_back_val();
368 MachineBasicBlock *BB = N->getBlock();
369
Evan Cheng4038f9c2010-04-08 01:03:47 +0000370 if (!CurLoop->contains(MLI->getLoopFor(BB)))
Evan Chengd94671a2010-04-07 00:41:17 +0000371 continue;
372 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000373 // FIXME: That means a reload that're reused in successor block(s) will not
374 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000375 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000376 E = BB->livein_end(); I != E; ++I) {
377 unsigned Reg = *I;
378 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000379 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
380 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000381 }
382
383 for (MachineBasicBlock::iterator
384 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000385 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000386 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000387 }
388
389 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
390 for (unsigned I = 0, E = Children.size(); I != E; ++I)
391 WorkList.push_back(Children[I]);
392 } while (!WorkList.empty());
393
394 // Now evaluate whether the potential candidates qualify.
395 // 1. Check if the candidate defined register is defined by another
396 // instruction in the loop.
397 // 2. If the candidate is a load from stack slot (always true for now),
398 // check if the slot is stored anywhere in the loop.
399 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000400 if (Candidates[i].FI != INT_MIN &&
401 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000402 continue;
403
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000404 if (PhysRegDefs[Candidates[i].Def] == 1) {
405 bool Safe = true;
406 MachineInstr *MI = Candidates[i].MI;
407 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
408 const MachineOperand &MO = MI->getOperand(i);
409 if (!MO.isReg() || MO.isDef())
410 continue;
411 if (PhysRegDefs[MO.getReg()]) {
412 // If it's using a non-loop-invariant register, then it's obviously
413 // not safe to hoist.
414 Safe = false;
415 break;
416 }
417 }
418 if (Safe)
419 HoistPostRA(MI, Candidates[i].Def);
420 }
Evan Chengd94671a2010-04-07 00:41:17 +0000421 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000422
423 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000424}
425
Evan Cheng4038f9c2010-04-08 01:03:47 +0000426/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
427/// backedge path from MBB to LoopHeader.
428void MachineLICM::AddToLiveIns(unsigned Reg, MachineBasicBlock *MBB,
429 MachineBasicBlock *LoopHeader) {
430 SmallPtrSet<MachineBasicBlock*, 4> Visited;
431 SmallVector<MachineBasicBlock*, 4> WorkList;
432 WorkList.push_back(MBB);
433 do {
434 MBB = WorkList.pop_back_val();
435 if (!Visited.insert(MBB))
436 continue;
437 MBB->addLiveIn(Reg);
438 if (MBB == LoopHeader)
439 continue;
440 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
441 E = MBB->pred_end(); PI != E; ++PI)
442 WorkList.push_back(*PI);
443 } while (!WorkList.empty());
444}
445
446/// HoistPostRA - When an instruction is found to only use loop invariant
447/// operands that is safe to hoist, this instruction is called to do the
448/// dirty work.
449void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Evan Chengd94671a2010-04-07 00:41:17 +0000450 // Now move the instructions to the predecessor, inserting it before any
451 // terminator instructions.
452 DEBUG({
453 dbgs() << "Hoisting " << *MI;
454 if (CurPreheader->getBasicBlock())
455 dbgs() << " to MachineBasicBlock "
456 << CurPreheader->getName();
457 if (MI->getParent()->getBasicBlock())
458 dbgs() << " from MachineBasicBlock "
459 << MI->getParent()->getName();
460 dbgs() << "\n";
461 });
462
463 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000464 MachineBasicBlock *MBB = MI->getParent();
465 CurPreheader->splice(CurPreheader->getFirstTerminator(), MBB, MI);
466
467 // Add register to livein list to BBs in the path from loop header to original
468 // BB. Note, currently it's not necessary to worry about adding it to all BB's
469 // with uses. Reload that're reused in successor block(s) are not being
470 // hoisted.
471 AddToLiveIns(Def, MBB, CurLoop->getHeader());
Evan Chengd94671a2010-04-07 00:41:17 +0000472
473 ++NumPostRAHoisted;
474 Changed = true;
475}
476
Bill Wendling0f940c92007-12-07 21:42:31 +0000477/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
478/// dominated by the specified block, and that are in the current loop) in depth
479/// first order w.r.t the DominatorTree. This allows us to visit definitions
480/// before uses, allowing us to hoist a loop body in one pass without iteration.
481///
482void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
483 assert(N != 0 && "Null dominator tree node?");
484 MachineBasicBlock *BB = N->getBlock();
485
486 // If this subregion is not in the top level loop at all, exit.
487 if (!CurLoop->contains(BB)) return;
488
Dan Gohmanc475c362009-01-15 22:01:38 +0000489 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000490 MII = BB->begin(), E = BB->end(); MII != E; ) {
491 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000492 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000493 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000494 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000495
496 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Bill Wendling0f940c92007-12-07 21:42:31 +0000497 for (unsigned I = 0, E = Children.size(); I != E; ++I)
498 HoistRegion(Children[I]);
499}
500
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000501/// IsLICMCandidate - Returns true if the instruction may be a suitable
502/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
503/// not safe to hoist it.
504bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattnera22edc82008-01-10 23:08:24 +0000505 const TargetInstrDesc &TID = I.getDesc();
506
507 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000508 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000509 TID.hasUnmodeledSideEffects())
510 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000511
Chris Lattnera22edc82008-01-10 23:08:24 +0000512 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000513 // Okay, this instruction does a load. As a refinement, we allow the target
514 // to decide whether the loaded value is actually a constant. If so, we can
515 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000516 if (!I.isInvariantLoad(AA))
Evan Cheng7adcdc32009-11-17 19:19:01 +0000517 // FIXME: we should be able to hoist loads with no other side effects if
518 // there are no other instructions which can change memory in this loop.
519 // This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000520 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000521 }
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000522 return true;
523}
524
525/// IsLoopInvariantInst - Returns true if the instruction is loop
526/// invariant. I.e., all virtual register operands are defined outside of the
527/// loop, physical registers aren't accessed explicitly, and there are no side
528/// effects that aren't captured by the operands or other flags.
529///
530bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
531 if (!IsLICMCandidate(I))
532 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000533
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000534 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000535 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
536 const MachineOperand &MO = I.getOperand(i);
537
Dan Gohmand735b802008-10-03 15:45:36 +0000538 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000539 continue;
540
Dan Gohmanc475c362009-01-15 22:01:38 +0000541 unsigned Reg = MO.getReg();
542 if (Reg == 0) continue;
543
544 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000545 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000546 if (MO.isUse()) {
547 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000548 // and we can freely move its uses. Alternatively, if it's allocatable,
549 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000550 if (!RegInfo->def_empty(Reg))
551 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000552 if (AllocatableSet.test(Reg))
553 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000554 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000555 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
556 unsigned AliasReg = *Alias;
557 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000558 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000559 if (AllocatableSet.test(AliasReg))
560 return false;
561 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000562 // Otherwise it's safe to move.
563 continue;
564 } else if (!MO.isDead()) {
565 // A def that isn't dead. We can't move it.
566 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000567 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
568 // If the reg is live into the loop, we can't hoist an instruction
569 // which would clobber it.
570 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000571 }
572 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000573
574 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000575 continue;
576
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000577 assert(RegInfo->getVRegDef(Reg) &&
578 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000579
580 // If the loop contains the definition of an operand, then the instruction
581 // isn't loop invariant.
Dan Gohman92329c72009-12-18 01:24:09 +0000582 if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000583 return false;
584 }
585
586 // If we got this far, the instruction is loop invariant!
587 return true;
588}
589
Evan Chengaf6949d2009-02-05 08:45:46 +0000590
591/// HasPHIUses - Return true if the specified register has any PHI use.
592static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000593 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
594 UE = RegInfo->use_end(); UI != UE; ++UI) {
595 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000596 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000597 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000598 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000599 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000600}
601
Evan Cheng87b75ba2009-11-20 19:55:37 +0000602/// isLoadFromConstantMemory - Return true if the given instruction is a
603/// load from constant memory. Machine LICM will hoist these even if they are
604/// not re-materializable.
605bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
606 if (!MI->getDesc().mayLoad()) return false;
607 if (!MI->hasOneMemOperand()) return false;
608 MachineMemOperand *MMO = *MI->memoperands_begin();
609 if (MMO->isVolatile()) return false;
610 if (!MMO->getValue()) return false;
611 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
612 if (PSV) {
613 MachineFunction &MF = *MI->getParent()->getParent();
614 return PSV->isConstant(MF.getFrameInfo());
615 } else {
616 return AA->pointsToConstantMemory(MMO->getValue());
617 }
618}
619
Evan Cheng45e94d62009-02-04 09:19:56 +0000620/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
621/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000622bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Chris Lattner518bb532010-02-09 19:54:29 +0000623 if (MI.isImplicitDef())
Evan Chengefc78392009-02-27 00:02:22 +0000624 return false;
625
Evan Cheng45e94d62009-02-04 09:19:56 +0000626 // FIXME: For now, only hoist re-materilizable instructions. LICM will
627 // increase register pressure. We want to make sure it doesn't increase
628 // spilling.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000629 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
630 // these tend to help performance in low register pressure situation. The
631 // trade off is it may cause spill in high pressure situation. It will end up
632 // adding a store in the loop preheader. But the reload is no more expensive.
633 // The side benefit is these loads are frequently CSE'ed.
634 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
Evan Chengc26abd92009-11-20 23:31:34 +0000635 if (!isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000636 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000637 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000638
Evan Chengaf6949d2009-02-05 08:45:46 +0000639 // If result(s) of this instruction is used by PHIs, then don't hoist it.
640 // The presence of joins makes it difficult for current register allocator
641 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000642 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
643 const MachineOperand &MO = MI.getOperand(i);
644 if (!MO.isReg() || !MO.isDef())
645 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000646 if (HasPHIUses(MO.getReg(), RegInfo))
647 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000648 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000649
650 return true;
651}
652
Dan Gohman5c952302009-10-29 17:47:20 +0000653MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
654 // If not, we may be able to unfold a load and hoist that.
655 // First test whether the instruction is loading from an amenable
656 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000657 if (!isLoadFromConstantMemory(MI))
658 return 0;
659
Dan Gohman5c952302009-10-29 17:47:20 +0000660 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000661 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000662 unsigned NewOpc =
663 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
664 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000665 /*UnfoldStore=*/false,
666 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000667 if (NewOpc == 0) return 0;
668 const TargetInstrDesc &TID = TII->get(NewOpc);
669 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000670 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000671 // Ok, we're unfolding. Create a temporary register and do the unfold.
672 unsigned Reg = RegInfo->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000673
674 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000675 SmallVector<MachineInstr *, 2> NewMIs;
676 bool Success =
677 TII->unfoldMemoryOperand(MF, MI, Reg,
678 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
679 NewMIs);
680 (void)Success;
681 assert(Success &&
682 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
683 "succeeded!");
684 assert(NewMIs.size() == 2 &&
685 "Unfolded a load into multiple instructions!");
686 MachineBasicBlock *MBB = MI->getParent();
687 MBB->insert(MI, NewMIs[0]);
688 MBB->insert(MI, NewMIs[1]);
689 // If unfolding produced a load that wasn't loop-invariant or profitable to
690 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +0000691 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +0000692 NewMIs[0]->eraseFromParent();
693 NewMIs[1]->eraseFromParent();
694 return 0;
695 }
696 // Otherwise we successfully unfolded a load that we can hoist.
697 MI->eraseFromParent();
698 return NewMIs[0];
699}
700
Evan Cheng777c6b72009-11-03 21:40:02 +0000701void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
702 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
703 const MachineInstr *MI = &*I;
704 // FIXME: For now, only hoist re-materilizable instructions. LICM will
705 // increase register pressure. We want to make sure it doesn't increase
706 // spilling.
707 if (TII->isTriviallyReMaterializable(MI, AA)) {
708 unsigned Opcode = MI->getOpcode();
709 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
710 CI = CSEMap.find(Opcode);
711 if (CI != CSEMap.end())
712 CI->second.push_back(MI);
713 else {
714 std::vector<const MachineInstr*> CSEMIs;
715 CSEMIs.push_back(MI);
716 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
717 }
718 }
719 }
720}
721
Evan Cheng78e5c112009-11-07 03:52:02 +0000722const MachineInstr*
723MachineLICM::LookForDuplicate(const MachineInstr *MI,
724 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +0000725 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
726 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +0000727 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +0000728 return PrevMI;
729 }
730 return 0;
731}
732
733bool MachineLICM::EliminateCSE(MachineInstr *MI,
734 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000735 if (CI == CSEMap.end())
736 return false;
737
738 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +0000739 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000740
741 // Replace virtual registers defined by MI by their counterparts defined
742 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +0000743 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
744 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000745
746 // Physical registers may not differ here.
747 assert((!MO.isReg() || MO.getReg() == 0 ||
748 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
749 MO.getReg() == Dup->getOperand(i).getReg()) &&
750 "Instructions with different phys regs are not identical!");
751
752 if (MO.isReg() && MO.isDef() &&
753 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
Evan Cheng78e5c112009-11-07 03:52:02 +0000754 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
Evan Cheng9fb744e2009-11-05 00:51:13 +0000755 }
Evan Cheng78e5c112009-11-07 03:52:02 +0000756 MI->eraseFromParent();
757 ++NumCSEed;
758 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +0000759 }
760 return false;
761}
762
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000763/// Hoist - When an instruction is found to use only loop invariant operands
764/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000765///
Dan Gohman589f1f52009-10-28 03:21:57 +0000766void MachineLICM::Hoist(MachineInstr *MI) {
767 // 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 Gohmanc475c362009-01-15 22:01:38 +0000778 if (CurPreheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000779 dbgs() << " to MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000780 << CurPreheader->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.
789 InitCSEMap(CurPreheader);
790
Evan Chengaf6949d2009-02-05 08:45:46 +0000791 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +0000792 unsigned Opcode = MI->getOpcode();
793 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
794 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +0000795 if (!EliminateCSE(MI, CI)) {
796 // Otherwise, splice the instruction to the preheader.
Evan Cheng777c6b72009-11-03 21:40:02 +0000797 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
798
Evan Chengaf6949d2009-02-05 08:45:46 +0000799 // Add to the CSE map.
800 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000801 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000802 else {
803 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000804 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000805 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +0000806 }
807 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000808
Dan Gohmanc475c362009-01-15 22:01:38 +0000809 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000810 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000811}