blob: 5136166bb32c201927d916f1321161e1d9c8010b [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.
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);
Bill Wendling0f940c92007-12-07 21:42:31 +0000184 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000185} // end anonymous namespace
186
Dan Gohman844731a2008-05-13 00:00:25 +0000187char MachineLICM::ID = 0;
188static RegisterPass<MachineLICM>
Bill Wendling8870ce92008-07-07 05:42:27 +0000189X("machinelicm", "Machine Loop Invariant Code Motion");
Dan Gohman844731a2008-05-13 00:00:25 +0000190
Evan Chengd94671a2010-04-07 00:41:17 +0000191FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
192 return new MachineLICM(PreRegAlloc);
193}
Bill Wendling0f940c92007-12-07 21:42:31 +0000194
Dan Gohmanc475c362009-01-15 22:01:38 +0000195/// LoopIsOuterMostWithPreheader - Test if the given loop is the outer-most
196/// loop that has a preheader.
197static bool LoopIsOuterMostWithPreheader(MachineLoop *CurLoop) {
198 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
199 if (L->getLoopPreheader())
200 return false;
201 return true;
202}
203
Bill Wendling0f940c92007-12-07 21:42:31 +0000204bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000205 if (PreRegAlloc)
206 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM ********\n");
207 else
208 DEBUG(dbgs() << "******** Post-regalloc Machine LICM ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000209
Evan Cheng4038f9c2010-04-08 01:03:47 +0000210 Changed = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000211 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000212 TII = TM->getInstrInfo();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000213 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000214 MFI = MF.getFrameInfo();
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000215 RegInfo = &MF.getRegInfo();
Dan Gohman45094e32009-09-26 02:34:00 +0000216 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000217
218 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000219 MLI = &getAnalysis<MachineLoopInfo>();
220 DT = &getAnalysis<MachineDominatorTree>();
221 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000222
Evan Cheng4038f9c2010-04-08 01:03:47 +0000223 for (MachineLoopInfo::iterator I = MLI->begin(), E = MLI->end(); I != E; ++I){
Bill Wendlinga17ad592007-12-11 22:22:22 +0000224 CurLoop = *I;
Bill Wendling0f940c92007-12-07 21:42:31 +0000225
Evan Cheng4038f9c2010-04-08 01:03:47 +0000226 // If this is done before regalloc, only visit outer-most preheader-sporting
227 // loops.
228 if (PreRegAlloc && !LoopIsOuterMostWithPreheader(CurLoop))
Dan Gohmanc475c362009-01-15 22:01:38 +0000229 continue;
230
231 // Determine the block to which to hoist instructions. If we can't find a
232 // suitable loop preheader, we can't do any hoisting.
233 //
234 // FIXME: We are only hoisting if the basic block coming into this loop
235 // has only one successor. This isn't the case in general because we haven't
236 // broken critical edges or added preheaders.
237 CurPreheader = CurLoop->getLoopPreheader();
238 if (!CurPreheader)
239 continue;
240
Evan Chengd94671a2010-04-07 00:41:17 +0000241 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000242 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000243 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000244 // CSEMap is initialized for loop header when the first instruction is
245 // being hoisted.
246 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Chengd94671a2010-04-07 00:41:17 +0000247 HoistRegion(N);
248 CSEMap.clear();
249 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000250 }
251
252 return Changed;
253}
254
Evan Cheng4038f9c2010-04-08 01:03:47 +0000255/// InstructionStoresToFI - Return true if instruction stores to the
256/// specified frame.
257static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
258 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
259 oe = MI->memoperands_end(); o != oe; ++o) {
260 if (!(*o)->isStore() || !(*o)->getValue())
261 continue;
262 if (const FixedStackPseudoSourceValue *Value =
263 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
264 if (Value->getFrameIndex() == FI)
265 return true;
266 }
267 }
268 return false;
269}
270
271/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
272/// gather register def and frame object update information.
273void MachineLICM::ProcessMI(MachineInstr *MI,
274 unsigned *PhysRegDefs,
275 SmallSet<int, 32> &StoredFIs,
276 SmallVector<CandidateInfo, 32> &Candidates) {
277 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000278 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000279 unsigned Def = 0;
280 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
281 const MachineOperand &MO = MI->getOperand(i);
282 if (MO.isFI()) {
283 // Remember if the instruction stores to the frame index.
284 int FI = MO.getIndex();
285 if (!StoredFIs.count(FI) &&
286 MFI->isSpillSlotObjectIndex(FI) &&
287 InstructionStoresToFI(MI, FI))
288 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000289 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000290 continue;
291 }
292
293 if (!MO.isReg())
294 continue;
295 unsigned Reg = MO.getReg();
296 if (!Reg)
297 continue;
298 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
299 "Not expecting virtual register!");
300
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000301 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000302 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000303 // If it's using a non-loop-invariant register, then it's obviously not
304 // safe to hoist.
305 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000306 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000307 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000308
309 if (MO.isImplicit()) {
310 ++PhysRegDefs[Reg];
311 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
312 ++PhysRegDefs[*AS];
313 if (!MO.isDead())
314 // Non-dead implicit def? This cannot be hoisted.
315 RuledOut = true;
316 // No need to check if a dead implicit def is also defined by
317 // another instruction.
318 continue;
319 }
320
321 // FIXME: For now, avoid instructions with multiple defs, unless
322 // it's a dead implicit def.
323 if (Def)
324 RuledOut = true;
325 else
326 Def = Reg;
327
328 // If we have already seen another instruction that defines the same
329 // register, then this is not safe.
330 if (++PhysRegDefs[Reg] > 1)
331 // MI defined register is seen defined by another instruction in
332 // the loop, it cannot be a LICM candidate.
333 RuledOut = true;
334 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
335 if (++PhysRegDefs[*AS] > 1)
336 RuledOut = true;
337 }
338
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000339 // Only consider reloads for now and remats which do not have register
340 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000341 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000342 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000343 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000344 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
345 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000346 }
347}
348
349/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
350/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000351void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000352 unsigned NumRegs = TRI->getNumRegs();
353 unsigned *PhysRegDefs = new unsigned[NumRegs];
354 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
355
Evan Cheng4038f9c2010-04-08 01:03:47 +0000356 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000357 SmallSet<int, 32> StoredFIs;
358
359 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000360 // collect potential LICM candidates.
361 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
362 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
363 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000364 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000365 // FIXME: That means a reload that're reused in successor block(s) will not
366 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000367 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000368 E = BB->livein_end(); I != E; ++I) {
369 unsigned Reg = *I;
370 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000371 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
372 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000373 }
374
375 for (MachineBasicBlock::iterator
376 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000377 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000378 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000379 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000380 }
Evan Chengd94671a2010-04-07 00:41:17 +0000381
382 // Now evaluate whether the potential candidates qualify.
383 // 1. Check if the candidate defined register is defined by another
384 // instruction in the loop.
385 // 2. If the candidate is a load from stack slot (always true for now),
386 // check if the slot is stored anywhere in the loop.
387 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000388 if (Candidates[i].FI != INT_MIN &&
389 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000390 continue;
391
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000392 if (PhysRegDefs[Candidates[i].Def] == 1) {
393 bool Safe = true;
394 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000395 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
396 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000397 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000398 continue;
399 if (PhysRegDefs[MO.getReg()]) {
400 // If it's using a non-loop-invariant register, then it's obviously
401 // not safe to hoist.
402 Safe = false;
403 break;
404 }
405 }
406 if (Safe)
407 HoistPostRA(MI, Candidates[i].Def);
408 }
Evan Chengd94671a2010-04-07 00:41:17 +0000409 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000410
411 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000412}
413
Evan Cheng4038f9c2010-04-08 01:03:47 +0000414/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000415/// current loop.
416void MachineLICM::AddToLiveIns(unsigned Reg) {
417 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
418 for (unsigned i = 0, e = Blocks.size(); i != e; ++i)
419 Blocks[i]->addLiveIn(Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000420}
421
422/// HoistPostRA - When an instruction is found to only use loop invariant
423/// operands that is safe to hoist, this instruction is called to do the
424/// dirty work.
425void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Evan Chengd94671a2010-04-07 00:41:17 +0000426 // Now move the instructions to the predecessor, inserting it before any
427 // terminator instructions.
428 DEBUG({
429 dbgs() << "Hoisting " << *MI;
430 if (CurPreheader->getBasicBlock())
431 dbgs() << " to MachineBasicBlock "
432 << CurPreheader->getName();
433 if (MI->getParent()->getBasicBlock())
434 dbgs() << " from MachineBasicBlock "
435 << MI->getParent()->getName();
436 dbgs() << "\n";
437 });
438
439 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000440 MachineBasicBlock *MBB = MI->getParent();
441 CurPreheader->splice(CurPreheader->getFirstTerminator(), MBB, MI);
442
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000443 // Add register to livein list to all the BBs in the current loop since a
444 // loop invariant must be kept live throughout the whole loop. This is
445 // important to ensure later passes do not scavenge the def register.
446 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000447
448 ++NumPostRAHoisted;
449 Changed = true;
450}
451
Bill Wendling0f940c92007-12-07 21:42:31 +0000452/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
453/// dominated by the specified block, and that are in the current loop) in depth
454/// first order w.r.t the DominatorTree. This allows us to visit definitions
455/// before uses, allowing us to hoist a loop body in one pass without iteration.
456///
457void MachineLICM::HoistRegion(MachineDomTreeNode *N) {
458 assert(N != 0 && "Null dominator tree node?");
459 MachineBasicBlock *BB = N->getBlock();
460
461 // If this subregion is not in the top level loop at all, exit.
462 if (!CurLoop->contains(BB)) return;
463
Dan Gohmanc475c362009-01-15 22:01:38 +0000464 for (MachineBasicBlock::iterator
Evan Chengaf6949d2009-02-05 08:45:46 +0000465 MII = BB->begin(), E = BB->end(); MII != E; ) {
466 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
Evan Cheng777c6b72009-11-03 21:40:02 +0000467 Hoist(&*MII);
Evan Chengaf6949d2009-02-05 08:45:46 +0000468 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000469 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000470
471 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Bill Wendling0f940c92007-12-07 21:42:31 +0000472 for (unsigned I = 0, E = Children.size(); I != E; ++I)
473 HoistRegion(Children[I]);
474}
475
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000476/// IsLICMCandidate - Returns true if the instruction may be a suitable
477/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
478/// not safe to hoist it.
479bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Evan Cheng63275372010-04-13 22:13:34 +0000480 if (I.isImplicitDef())
481 return false;
482
Chris Lattnera22edc82008-01-10 23:08:24 +0000483 const TargetInstrDesc &TID = I.getDesc();
484
485 // Ignore stuff that we obviously can't hoist.
Dan Gohman237dee12008-12-23 17:28:50 +0000486 if (TID.mayStore() || TID.isCall() || TID.isTerminator() ||
Chris Lattnera22edc82008-01-10 23:08:24 +0000487 TID.hasUnmodeledSideEffects())
488 return false;
Evan Cheng9b61f332009-02-04 07:17:49 +0000489
Chris Lattnera22edc82008-01-10 23:08:24 +0000490 if (TID.mayLoad()) {
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000491 // Okay, this instruction does a load. As a refinement, we allow the target
492 // to decide whether the loaded value is actually a constant. If so, we can
493 // actually use it as a load.
Dan Gohmane33f44c2009-10-07 17:38:06 +0000494 if (!I.isInvariantLoad(AA))
Evan Cheng7adcdc32009-11-17 19:19:01 +0000495 // FIXME: we should be able to hoist loads with no other side effects if
496 // there are no other instructions which can change memory in this loop.
497 // This is a trivial form of alias analysis.
Chris Lattnera22edc82008-01-10 23:08:24 +0000498 return false;
Chris Lattnera22edc82008-01-10 23:08:24 +0000499 }
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000500 return true;
501}
502
503/// IsLoopInvariantInst - Returns true if the instruction is loop
504/// invariant. I.e., all virtual register operands are defined outside of the
505/// loop, physical registers aren't accessed explicitly, and there are no side
506/// effects that aren't captured by the operands or other flags.
507///
508bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
509 if (!IsLICMCandidate(I))
510 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000511
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000512 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000513 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
514 const MachineOperand &MO = I.getOperand(i);
515
Dan Gohmand735b802008-10-03 15:45:36 +0000516 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000517 continue;
518
Dan Gohmanc475c362009-01-15 22:01:38 +0000519 unsigned Reg = MO.getReg();
520 if (Reg == 0) continue;
521
522 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000523 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000524 if (MO.isUse()) {
525 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000526 // and we can freely move its uses. Alternatively, if it's allocatable,
527 // it could get allocated to something with a def during allocation.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000528 if (!RegInfo->def_empty(Reg))
529 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000530 if (AllocatableSet.test(Reg))
531 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000532 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000533 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
534 unsigned AliasReg = *Alias;
535 if (!RegInfo->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000536 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000537 if (AllocatableSet.test(AliasReg))
538 return false;
539 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000540 // Otherwise it's safe to move.
541 continue;
542 } else if (!MO.isDead()) {
543 // A def that isn't dead. We can't move it.
544 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000545 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
546 // If the reg is live into the loop, we can't hoist an instruction
547 // which would clobber it.
548 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000549 }
550 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000551
552 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000553 continue;
554
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000555 assert(RegInfo->getVRegDef(Reg) &&
556 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000557
558 // If the loop contains the definition of an operand, then the instruction
559 // isn't loop invariant.
Dan Gohman92329c72009-12-18 01:24:09 +0000560 if (CurLoop->contains(RegInfo->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000561 return false;
562 }
563
564 // If we got this far, the instruction is loop invariant!
565 return true;
566}
567
Evan Chengaf6949d2009-02-05 08:45:46 +0000568
569/// HasPHIUses - Return true if the specified register has any PHI use.
570static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *RegInfo) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000571 for (MachineRegisterInfo::use_iterator UI = RegInfo->use_begin(Reg),
572 UE = RegInfo->use_end(); UI != UE; ++UI) {
573 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000574 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000575 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000576 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000577 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000578}
579
Evan Cheng87b75ba2009-11-20 19:55:37 +0000580/// isLoadFromConstantMemory - Return true if the given instruction is a
581/// load from constant memory. Machine LICM will hoist these even if they are
582/// not re-materializable.
583bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
584 if (!MI->getDesc().mayLoad()) return false;
585 if (!MI->hasOneMemOperand()) return false;
586 MachineMemOperand *MMO = *MI->memoperands_begin();
587 if (MMO->isVolatile()) return false;
588 if (!MMO->getValue()) return false;
589 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
590 if (PSV) {
591 MachineFunction &MF = *MI->getParent()->getParent();
592 return PSV->isConstant(MF.getFrameInfo());
593 } else {
594 return AA->pointsToConstantMemory(MMO->getValue());
595 }
596}
597
Evan Cheng45e94d62009-02-04 09:19:56 +0000598/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
599/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000600bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000601 // FIXME: For now, only hoist re-materilizable instructions. LICM will
602 // increase register pressure. We want to make sure it doesn't increase
603 // spilling.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000604 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
605 // these tend to help performance in low register pressure situation. The
606 // trade off is it may cause spill in high pressure situation. It will end up
607 // adding a store in the loop preheader. But the reload is no more expensive.
608 // The side benefit is these loads are frequently CSE'ed.
609 if (!TII->isTriviallyReMaterializable(&MI, AA)) {
Evan Chengc26abd92009-11-20 23:31:34 +0000610 if (!isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000611 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000612 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000613
Evan Chengaf6949d2009-02-05 08:45:46 +0000614 // If result(s) of this instruction is used by PHIs, then don't hoist it.
615 // The presence of joins makes it difficult for current register allocator
616 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000617 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
618 const MachineOperand &MO = MI.getOperand(i);
619 if (!MO.isReg() || !MO.isDef())
620 continue;
Evan Chengaf6949d2009-02-05 08:45:46 +0000621 if (HasPHIUses(MO.getReg(), RegInfo))
622 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000623 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000624
625 return true;
626}
627
Dan Gohman5c952302009-10-29 17:47:20 +0000628MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
629 // If not, we may be able to unfold a load and hoist that.
630 // First test whether the instruction is loading from an amenable
631 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000632 if (!isLoadFromConstantMemory(MI))
633 return 0;
634
Dan Gohman5c952302009-10-29 17:47:20 +0000635 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000636 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000637 unsigned NewOpc =
638 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
639 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000640 /*UnfoldStore=*/false,
641 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000642 if (NewOpc == 0) return 0;
643 const TargetInstrDesc &TID = TII->get(NewOpc);
644 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000645 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000646 // Ok, we're unfolding. Create a temporary register and do the unfold.
647 unsigned Reg = RegInfo->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000648
649 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000650 SmallVector<MachineInstr *, 2> NewMIs;
651 bool Success =
652 TII->unfoldMemoryOperand(MF, MI, Reg,
653 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
654 NewMIs);
655 (void)Success;
656 assert(Success &&
657 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
658 "succeeded!");
659 assert(NewMIs.size() == 2 &&
660 "Unfolded a load into multiple instructions!");
661 MachineBasicBlock *MBB = MI->getParent();
662 MBB->insert(MI, NewMIs[0]);
663 MBB->insert(MI, NewMIs[1]);
664 // If unfolding produced a load that wasn't loop-invariant or profitable to
665 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +0000666 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +0000667 NewMIs[0]->eraseFromParent();
668 NewMIs[1]->eraseFromParent();
669 return 0;
670 }
671 // Otherwise we successfully unfolded a load that we can hoist.
672 MI->eraseFromParent();
673 return NewMIs[0];
674}
675
Evan Cheng777c6b72009-11-03 21:40:02 +0000676void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
677 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
678 const MachineInstr *MI = &*I;
679 // FIXME: For now, only hoist re-materilizable instructions. LICM will
680 // increase register pressure. We want to make sure it doesn't increase
681 // spilling.
682 if (TII->isTriviallyReMaterializable(MI, AA)) {
683 unsigned Opcode = MI->getOpcode();
684 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
685 CI = CSEMap.find(Opcode);
686 if (CI != CSEMap.end())
687 CI->second.push_back(MI);
688 else {
689 std::vector<const MachineInstr*> CSEMIs;
690 CSEMIs.push_back(MI);
691 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
692 }
693 }
694 }
695}
696
Evan Cheng78e5c112009-11-07 03:52:02 +0000697const MachineInstr*
698MachineLICM::LookForDuplicate(const MachineInstr *MI,
699 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +0000700 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
701 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +0000702 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +0000703 return PrevMI;
704 }
705 return 0;
706}
707
708bool MachineLICM::EliminateCSE(MachineInstr *MI,
709 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Cheng78e5c112009-11-07 03:52:02 +0000710 if (CI == CSEMap.end())
711 return false;
712
713 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +0000714 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000715
716 // Replace virtual registers defined by MI by their counterparts defined
717 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +0000718 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
719 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +0000720
721 // Physical registers may not differ here.
722 assert((!MO.isReg() || MO.getReg() == 0 ||
723 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
724 MO.getReg() == Dup->getOperand(i).getReg()) &&
725 "Instructions with different phys regs are not identical!");
726
727 if (MO.isReg() && MO.isDef() &&
728 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
Evan Cheng78e5c112009-11-07 03:52:02 +0000729 RegInfo->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
Evan Cheng9fb744e2009-11-05 00:51:13 +0000730 }
Evan Cheng78e5c112009-11-07 03:52:02 +0000731 MI->eraseFromParent();
732 ++NumCSEed;
733 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +0000734 }
735 return false;
736}
737
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000738/// Hoist - When an instruction is found to use only loop invariant operands
739/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +0000740///
Dan Gohman589f1f52009-10-28 03:21:57 +0000741void MachineLICM::Hoist(MachineInstr *MI) {
742 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +0000743 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +0000744 // If not, try unfolding a hoistable load.
745 MI = ExtractHoistableLoad(MI);
746 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +0000747 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000748
Dan Gohmanc475c362009-01-15 22:01:38 +0000749 // Now move the instructions to the predecessor, inserting it before any
750 // terminator instructions.
751 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +0000752 dbgs() << "Hoisting " << *MI;
Dan Gohmanc475c362009-01-15 22:01:38 +0000753 if (CurPreheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000754 dbgs() << " to MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000755 << CurPreheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +0000756 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +0000757 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +0000758 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +0000759 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +0000760 });
Bill Wendling0f940c92007-12-07 21:42:31 +0000761
Evan Cheng777c6b72009-11-03 21:40:02 +0000762 // If this is the first instruction being hoisted to the preheader,
763 // initialize the CSE map with potential common expressions.
764 InitCSEMap(CurPreheader);
765
Evan Chengaf6949d2009-02-05 08:45:46 +0000766 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +0000767 unsigned Opcode = MI->getOpcode();
768 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
769 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +0000770 if (!EliminateCSE(MI, CI)) {
771 // Otherwise, splice the instruction to the preheader.
Evan Cheng777c6b72009-11-03 21:40:02 +0000772 CurPreheader->splice(CurPreheader->getFirstTerminator(),MI->getParent(),MI);
773
Evan Chengaf6949d2009-02-05 08:45:46 +0000774 // Add to the CSE map.
775 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +0000776 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +0000777 else {
778 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +0000779 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +0000780 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +0000781 }
782 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000783
Dan Gohmanc475c362009-01-15 22:01:38 +0000784 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +0000785 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +0000786}