blob: 1f0412498b66ebc021488c3e572123af73ea4b93 [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"
Evan Cheng0e673912010-10-14 01:16:09 +000031#include "llvm/Target/TargetLowering.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000032#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000033#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng0e673912010-10-14 01:16:09 +000034#include "llvm/Target/TargetInstrItineraries.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000035#include "llvm/Target/TargetMachine.h"
Dan Gohmane33f44c2009-10-07 17:38:06 +000036#include "llvm/Analysis/AliasAnalysis.h"
Evan Chengaf6949d2009-02-05 08:45:46 +000037#include "llvm/ADT/DenseMap.h"
Evan Chengd94671a2010-04-07 00:41:17 +000038#include "llvm/ADT/SmallSet.h"
Chris Lattnerac695822008-01-04 06:41:45 +000039#include "llvm/ADT/Statistic.h"
Evan Cheng0e673912010-10-14 01:16:09 +000040#include "llvm/Support/CommandLine.h"
Chris Lattnerac695822008-01-04 06:41:45 +000041#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000042#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000043
44using namespace llvm;
45
Evan Cheng03a9fdf2010-10-16 02:20:26 +000046STATISTIC(NumHoisted,
47 "Number of machine instructions hoisted out of loops");
48STATISTIC(NumLowRP,
49 "Number of instructions hoisted in low reg pressure situation");
50STATISTIC(NumHighLatency,
51 "Number of high latency instructions hoisted");
52STATISTIC(NumCSEed,
53 "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000054STATISTIC(NumPostRAHoisted,
55 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendlingb48519c2007-12-08 01:47:01 +000056
Bill Wendling0f940c92007-12-07 21:42:31 +000057namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000058 class MachineLICM : public MachineFunctionPass {
Evan Chengd94671a2010-04-07 00:41:17 +000059 bool PreRegAlloc;
60
Bill Wendling9258cd32008-01-02 19:32:43 +000061 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000062 const TargetInstrInfo *TII;
Evan Cheng0e673912010-10-14 01:16:09 +000063 const TargetLowering *TLI;
Dan Gohmana8fb3362009-09-25 23:58:45 +000064 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000065 const MachineFrameInfo *MFI;
Evan Cheng0e673912010-10-14 01:16:09 +000066 MachineRegisterInfo *MRI;
67 const InstrItineraryData *InstrItins;
Bill Wendling12ebf142007-12-11 19:40:06 +000068
Bill Wendling0f940c92007-12-07 21:42:31 +000069 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000070 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +000071 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000072 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000073
Bill Wendling0f940c92007-12-07 21:42:31 +000074 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000075 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +000076 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000077 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000078 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000079
Evan Chengd94671a2010-04-07 00:41:17 +000080 BitVector AllocatableSet;
81
Evan Cheng0e673912010-10-14 01:16:09 +000082 // Track 'estimated' register pressure.
Evan Cheng03a9fdf2010-10-16 02:20:26 +000083 SmallSet<unsigned, 32> RegSeen;
Evan Cheng0e673912010-10-14 01:16:09 +000084 SmallVector<unsigned, 8> RegPressure;
Evan Cheng03a9fdf2010-10-16 02:20:26 +000085
86 // Register pressure "limit" per register class. If the pressure
87 // is higher than the limit, then it's considered high.
Evan Cheng0e673912010-10-14 01:16:09 +000088 SmallVector<unsigned, 8> RegLimit;
89
Evan Cheng03a9fdf2010-10-16 02:20:26 +000090 // Register pressure on path leading from loop preheader to current BB.
91 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
92
Dale Johannesenc46a5f22010-07-29 17:45:24 +000093 // For each opcode, keep a list of potential CSE instructions.
Evan Cheng777c6b72009-11-03 21:40:02 +000094 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000095
Bill Wendling0f940c92007-12-07 21:42:31 +000096 public:
97 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +000098 MachineLICM() :
Owen Anderson081c34b2010-10-19 17:21:58 +000099 MachineFunctionPass(ID), PreRegAlloc(true) {
100 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
101 }
Evan Chengd94671a2010-04-07 00:41:17 +0000102
103 explicit MachineLICM(bool PreRA) :
Owen Anderson081c34b2010-10-19 17:21:58 +0000104 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
105 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
106 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000107
108 virtual bool runOnMachineFunction(MachineFunction &MF);
109
Dan Gohman72241702008-12-18 01:37:56 +0000110 const char *getPassName() const { return "Machine Instruction LICM"; }
111
Bill Wendling0f940c92007-12-07 21:42:31 +0000112 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
113 AU.setPreservesCFG();
114 AU.addRequired<MachineLoopInfo>();
115 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000116 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000117 AU.addPreserved<MachineLoopInfo>();
118 AU.addPreserved<MachineDominatorTree>();
119 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000120 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000121
122 virtual void releaseMemory() {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000123 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000124 RegPressure.clear();
125 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000126 BackTrace.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000127 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
128 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
129 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000130 CSEMap.clear();
131 }
132
Bill Wendling0f940c92007-12-07 21:42:31 +0000133 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000134 /// CandidateInfo - Keep track of information about hoisting candidates.
135 struct CandidateInfo {
136 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000137 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000138 int FI;
139 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
140 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000141 };
142
143 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
144 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000145 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000146
147 /// HoistPostRA - When an instruction is found to only use loop invariant
148 /// operands that is safe to hoist, this instruction is called to do the
149 /// dirty work.
150 void HoistPostRA(MachineInstr *MI, unsigned Def);
151
152 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
153 /// gather register def and frame object update information.
154 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
155 SmallSet<int, 32> &StoredFIs,
156 SmallVector<CandidateInfo, 32> &Candidates);
157
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000158 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
159 /// current loop.
160 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000161
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000162 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000163 /// candidate for LICM. e.g. If the instruction is a call, then it's
164 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000165 bool IsLICMCandidate(MachineInstr &I);
166
Bill Wendling041b3f82007-12-08 23:58:46 +0000167 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000168 /// invariant. I.e., all virtual register operands are defined outside of
169 /// the loop, physical registers aren't accessed (explicitly or implicitly),
170 /// and the instruction is hoistable.
171 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000172 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000173
Evan Cheng23128422010-10-19 18:58:51 +0000174 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
175 /// and an use in the current loop, return true if the target considered
176 /// it 'high'.
177 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx, unsigned Reg);
Evan Cheng0e673912010-10-14 01:16:09 +0000178
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000179 /// IncreaseHighRegPressure - Visit BBs from preheader to current BB, check
180 /// if hoisting an instruction of the given cost matrix can cause high
181 /// register pressure.
182 bool IncreaseHighRegPressure(DenseMap<unsigned, int> &Cost);
183
Evan Cheng45e94d62009-02-04 09:19:56 +0000184 /// IsProfitableToHoist - Return true if it is potentially profitable to
185 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000186 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000187
Bill Wendling0f940c92007-12-07 21:42:31 +0000188 /// HoistRegion - Walk the specified region of the CFG (defined by all
189 /// blocks dominated by the specified block, and that are in the current
190 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
191 /// visit definitions before uses, allowing us to hoist a loop body in one
192 /// pass without iteration.
193 ///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000194 void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
Bill Wendling0f940c92007-12-07 21:42:31 +0000195
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000196 /// InitRegPressure - Find all virtual register references that are liveout
197 /// of the preheader to initialize the starting "register pressure". Note
198 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000199 void InitRegPressure(MachineBasicBlock *BB);
200
201 /// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
202 /// register pressure before and after executing a specifi instruction.
Evan Cheng23128422010-10-19 18:58:51 +0000203 void UpdateRegPressureBefore(const MachineInstr *MI,
204 SmallVector<unsigned, 4> &Defs);
205 void UpdateRegPressureAfter(SmallVector<unsigned, 4> &Defs);
Evan Cheng0e673912010-10-14 01:16:09 +0000206
Evan Cheng87b75ba2009-11-20 19:55:37 +0000207 /// isLoadFromConstantMemory - Return true if the given instruction is a
208 /// load from constant memory.
209 bool isLoadFromConstantMemory(MachineInstr *MI);
210
Dan Gohman5c952302009-10-29 17:47:20 +0000211 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
212 /// the load itself could be hoisted. Return the unfolded and hoistable
213 /// load, or null if the load couldn't be unfolded or if it wouldn't
214 /// be hoistable.
215 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
216
Evan Cheng78e5c112009-11-07 03:52:02 +0000217 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
218 /// duplicate of MI. Return this instruction if it's found.
219 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
220 std::vector<const MachineInstr*> &PrevMIs);
221
Evan Cheng9fb744e2009-11-05 00:51:13 +0000222 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
223 /// the preheader that compute the same value. If it's found, do a RAU on
224 /// with the definition of the existing instruction rather than hoisting
225 /// the instruction to the preheader.
226 bool EliminateCSE(MachineInstr *MI,
227 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
228
Bill Wendling0f940c92007-12-07 21:42:31 +0000229 /// Hoist - When an instruction is found to only use loop invariant operands
230 /// that is safe to hoist, this instruction is called to do the dirty work.
231 ///
Evan Cheng0e673912010-10-14 01:16:09 +0000232 void Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000233
234 /// InitCSEMap - Initialize the CSE map with instructions that are in the
235 /// current loop preheader that may become duplicates of instructions that
236 /// are hoisted out of the loop.
237 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000238
239 /// getCurPreheader - Get the preheader for the current loop, splitting
240 /// a critical edge if needed.
241 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000242 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000243} // end anonymous namespace
244
Dan Gohman844731a2008-05-13 00:00:25 +0000245char MachineLICM::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000246INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
247 "Machine Loop Invariant Code Motion", false, false)
248INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
249INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
250INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
251INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000252 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000253
Evan Chengd94671a2010-04-07 00:41:17 +0000254FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
255 return new MachineLICM(PreRegAlloc);
256}
Bill Wendling0f940c92007-12-07 21:42:31 +0000257
Dan Gohman853d3fb2010-06-22 17:25:57 +0000258/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
259/// loop that has a unique predecessor.
260static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000261 // Check whether this loop even has a unique predecessor.
262 if (!CurLoop->getLoopPredecessor())
263 return false;
264 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000265 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000266 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000267 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000268 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000269 return true;
270}
271
Bill Wendling0f940c92007-12-07 21:42:31 +0000272bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000273 if (PreRegAlloc)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000274 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Evan Chengd94671a2010-04-07 00:41:17 +0000275 else
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000276 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
277 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000278
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000279 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000280 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000281 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000282 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000283 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000284 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000285 MRI = &MF.getRegInfo();
286 InstrItins = TM->getInstrItineraryData();
Dan Gohman45094e32009-09-26 02:34:00 +0000287 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000288
Evan Cheng0e673912010-10-14 01:16:09 +0000289 if (PreRegAlloc) {
290 // Estimate register pressure during pre-regalloc pass.
291 unsigned NumRC = TRI->getNumRegClasses();
292 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000293 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000294 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000295 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
296 E = TRI->regclass_end(); I != E; ++I)
297 RegLimit[(*I)->getID()] = TLI->getRegPressureLimit(*I, MF);
298 }
299
Bill Wendling0f940c92007-12-07 21:42:31 +0000300 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000301 MLI = &getAnalysis<MachineLoopInfo>();
302 DT = &getAnalysis<MachineDominatorTree>();
303 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000304
Dan Gohmanaa742602010-07-09 18:49:45 +0000305 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
306 while (!Worklist.empty()) {
307 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000308 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000309
Evan Cheng4038f9c2010-04-08 01:03:47 +0000310 // If this is done before regalloc, only visit outer-most preheader-sporting
311 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000312 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
313 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000314 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000315 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000316
Evan Chengd94671a2010-04-07 00:41:17 +0000317 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000318 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000319 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000320 // CSEMap is initialized for loop header when the first instruction is
321 // being hoisted.
322 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000323 FirstInLoop = true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000324 HoistRegion(N, true);
Evan Chengd94671a2010-04-07 00:41:17 +0000325 CSEMap.clear();
326 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000327 }
328
329 return Changed;
330}
331
Evan Cheng4038f9c2010-04-08 01:03:47 +0000332/// InstructionStoresToFI - Return true if instruction stores to the
333/// specified frame.
334static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
335 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
336 oe = MI->memoperands_end(); o != oe; ++o) {
337 if (!(*o)->isStore() || !(*o)->getValue())
338 continue;
339 if (const FixedStackPseudoSourceValue *Value =
340 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
341 if (Value->getFrameIndex() == FI)
342 return true;
343 }
344 }
345 return false;
346}
347
348/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
349/// gather register def and frame object update information.
350void MachineLICM::ProcessMI(MachineInstr *MI,
351 unsigned *PhysRegDefs,
352 SmallSet<int, 32> &StoredFIs,
353 SmallVector<CandidateInfo, 32> &Candidates) {
354 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000355 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000356 unsigned Def = 0;
357 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
358 const MachineOperand &MO = MI->getOperand(i);
359 if (MO.isFI()) {
360 // Remember if the instruction stores to the frame index.
361 int FI = MO.getIndex();
362 if (!StoredFIs.count(FI) &&
363 MFI->isSpillSlotObjectIndex(FI) &&
364 InstructionStoresToFI(MI, FI))
365 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000366 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000367 continue;
368 }
369
370 if (!MO.isReg())
371 continue;
372 unsigned Reg = MO.getReg();
373 if (!Reg)
374 continue;
375 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
376 "Not expecting virtual register!");
377
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000378 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000379 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000380 // If it's using a non-loop-invariant register, then it's obviously not
381 // safe to hoist.
382 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000383 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000384 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000385
386 if (MO.isImplicit()) {
387 ++PhysRegDefs[Reg];
388 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
389 ++PhysRegDefs[*AS];
390 if (!MO.isDead())
391 // Non-dead implicit def? This cannot be hoisted.
392 RuledOut = true;
393 // No need to check if a dead implicit def is also defined by
394 // another instruction.
395 continue;
396 }
397
398 // FIXME: For now, avoid instructions with multiple defs, unless
399 // it's a dead implicit def.
400 if (Def)
401 RuledOut = true;
402 else
403 Def = Reg;
404
405 // If we have already seen another instruction that defines the same
406 // register, then this is not safe.
407 if (++PhysRegDefs[Reg] > 1)
408 // MI defined register is seen defined by another instruction in
409 // the loop, it cannot be a LICM candidate.
410 RuledOut = true;
411 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
412 if (++PhysRegDefs[*AS] > 1)
413 RuledOut = true;
414 }
415
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000416 // Only consider reloads for now and remats which do not have register
417 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000418 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000419 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000420 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000421 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
422 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000423 }
424}
425
426/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
427/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000428void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000429 unsigned NumRegs = TRI->getNumRegs();
430 unsigned *PhysRegDefs = new unsigned[NumRegs];
431 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
432
Evan Cheng4038f9c2010-04-08 01:03:47 +0000433 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000434 SmallSet<int, 32> StoredFIs;
435
436 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000437 // collect potential LICM candidates.
438 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
439 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
440 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000441 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000442 // FIXME: That means a reload that're reused in successor block(s) will not
443 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000444 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000445 E = BB->livein_end(); I != E; ++I) {
446 unsigned Reg = *I;
447 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000448 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
449 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000450 }
451
452 for (MachineBasicBlock::iterator
453 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000454 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000455 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000456 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000457 }
Evan Chengd94671a2010-04-07 00:41:17 +0000458
459 // Now evaluate whether the potential candidates qualify.
460 // 1. Check if the candidate defined register is defined by another
461 // instruction in the loop.
462 // 2. If the candidate is a load from stack slot (always true for now),
463 // check if the slot is stored anywhere in the loop.
464 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000465 if (Candidates[i].FI != INT_MIN &&
466 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000467 continue;
468
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000469 if (PhysRegDefs[Candidates[i].Def] == 1) {
470 bool Safe = true;
471 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000472 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
473 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000474 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000475 continue;
476 if (PhysRegDefs[MO.getReg()]) {
477 // If it's using a non-loop-invariant register, then it's obviously
478 // not safe to hoist.
479 Safe = false;
480 break;
481 }
482 }
483 if (Safe)
484 HoistPostRA(MI, Candidates[i].Def);
485 }
Evan Chengd94671a2010-04-07 00:41:17 +0000486 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000487
488 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000489}
490
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000491/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
492/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000493void MachineLICM::AddToLiveIns(unsigned Reg) {
494 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000495 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
496 MachineBasicBlock *BB = Blocks[i];
497 if (!BB->isLiveIn(Reg))
498 BB->addLiveIn(Reg);
499 for (MachineBasicBlock::iterator
500 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
501 MachineInstr *MI = &*MII;
502 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
503 MachineOperand &MO = MI->getOperand(i);
504 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
505 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
506 MO.setIsKill(false);
507 }
508 }
509 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000510}
511
512/// HoistPostRA - When an instruction is found to only use loop invariant
513/// operands that is safe to hoist, this instruction is called to do the
514/// dirty work.
515void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000516 MachineBasicBlock *Preheader = getCurPreheader();
517 if (!Preheader) return;
518
Evan Chengd94671a2010-04-07 00:41:17 +0000519 // Now move the instructions to the predecessor, inserting it before any
520 // terminator instructions.
521 DEBUG({
522 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000523 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000524 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000525 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000526 if (MI->getParent()->getBasicBlock())
527 dbgs() << " from MachineBasicBlock "
528 << MI->getParent()->getName();
529 dbgs() << "\n";
530 });
531
532 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000533 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000534 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000535
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000536 // Add register to livein list to all the BBs in the current loop since a
537 // loop invariant must be kept live throughout the whole loop. This is
538 // important to ensure later passes do not scavenge the def register.
539 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000540
541 ++NumPostRAHoisted;
542 Changed = true;
543}
544
Bill Wendling0f940c92007-12-07 21:42:31 +0000545/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
546/// dominated by the specified block, and that are in the current loop) in depth
547/// first order w.r.t the DominatorTree. This allows us to visit definitions
548/// before uses, allowing us to hoist a loop body in one pass without iteration.
549///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000550void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000551 assert(N != 0 && "Null dominator tree node?");
552 MachineBasicBlock *BB = N->getBlock();
553
554 // If this subregion is not in the top level loop at all, exit.
555 if (!CurLoop->contains(BB)) return;
556
Evan Cheng0e673912010-10-14 01:16:09 +0000557 MachineBasicBlock *Preheader = getCurPreheader();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000558 if (!Preheader)
559 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000560
Evan Cheng23128422010-10-19 18:58:51 +0000561 if (IsHeader) {
562 // Compute registers which are liveout of preheader.
563 RegSeen.clear();
564 BackTrace.clear();
565 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000566 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000567
Evan Cheng23128422010-10-19 18:58:51 +0000568 // Remember livein register pressure.
569 BackTrace.push_back(RegPressure);
570
571 SmallVector<unsigned, 4> Defs;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000572 for (MachineBasicBlock::iterator
573 MII = BB->begin(), E = BB->end(); MII != E; ) {
574 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
575 MachineInstr *MI = &*MII;
576
Evan Cheng23128422010-10-19 18:58:51 +0000577 assert(Defs.empty());
578 UpdateRegPressureBefore(MI, Defs);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000579 Hoist(MI, Preheader);
Evan Cheng23128422010-10-19 18:58:51 +0000580 UpdateRegPressureAfter(Defs);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000581
582 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000583 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000584
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000585 // Don't hoist things out of a large switch statement. This often causes
586 // code to be hoisted that wasn't going to be executed, and increases
587 // register pressure in a situation where it's likely to matter.
Dale Johannesen21d35c12010-07-20 21:29:12 +0000588 if (BB->succ_size() < 25) {
589 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000590 for (unsigned I = 0, E = Children.size(); I != E; ++I)
591 HoistRegion(Children[I]);
Dale Johannesen21d35c12010-07-20 21:29:12 +0000592 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000593
Evan Cheng23128422010-10-19 18:58:51 +0000594 BackTrace.pop_back();
Bill Wendling0f940c92007-12-07 21:42:31 +0000595}
596
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000597/// InitRegPressure - Find all virtual register references that are liveout of
598/// the preheader to initialize the starting "register pressure". Note this
599/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000600void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000601 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000602
Evan Cheng0e673912010-10-14 01:16:09 +0000603 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
604 MII != E; ++MII) {
605 MachineInstr *MI = &*MII;
606 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
607 const MachineOperand &MO = MI->getOperand(i);
608 if (!MO.isReg() || MO.isImplicit())
609 continue;
610 unsigned Reg = MO.getReg();
611 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
612 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000613
Andrew Trickdc986d22010-10-19 02:50:50 +0000614 bool isNew = RegSeen.insert(Reg);
Evan Cheng0e673912010-10-14 01:16:09 +0000615 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
616 EVT VT = *RC->vt_begin();
617 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000618 if (MO.isDef())
619 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
620 else {
621 if (isNew && !MO.isKill())
622 // Haven't seen this, it must be a livein.
623 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
624 else if (!isNew && MO.isKill())
625 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
626 }
Evan Cheng0e673912010-10-14 01:16:09 +0000627 }
628 }
629}
630
631/// UpdateRegPressureBefore / UpdateRegPressureAfter - Update estimate of
632/// register pressure before and after executing a specifi instruction.
Evan Cheng23128422010-10-19 18:58:51 +0000633void MachineLICM::UpdateRegPressureBefore(const MachineInstr *MI,
634 SmallVector<unsigned, 4> &Defs) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000635 bool NoImpact = MI->isImplicitDef() || MI->isPHI();
Evan Cheng0e673912010-10-14 01:16:09 +0000636
637 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
638 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000639 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000640 continue;
641 unsigned Reg = MO.getReg();
642 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
643 continue;
644
Andrew Trickdc986d22010-10-19 02:50:50 +0000645 bool isNew = RegSeen.insert(Reg);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000646 if (NoImpact)
647 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000648
Evan Cheng23128422010-10-19 18:58:51 +0000649 if (MO.isDef())
650 Defs.push_back(Reg);
651 else {
652 if (!isNew && MO.isKill()) {
653 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
654 EVT VT = *RC->vt_begin();
655 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
656 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000657
Evan Cheng23128422010-10-19 18:58:51 +0000658 assert(RCCost <= RegPressure[RCId]);
659 RegPressure[RCId] -= RCCost;
660 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000661 }
Evan Cheng0e673912010-10-14 01:16:09 +0000662 }
663}
664
Evan Cheng23128422010-10-19 18:58:51 +0000665void MachineLICM::UpdateRegPressureAfter(SmallVector<unsigned, 4> &Defs) {
666 while (!Defs.empty()) {
667 unsigned Reg = Defs.pop_back_val();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000668 RegSeen.insert(Reg);
Evan Cheng0e673912010-10-14 01:16:09 +0000669 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
670 EVT VT = *RC->vt_begin();
671 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
672 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
673 RegPressure[RCId] += RCCost;
674 }
675}
676
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000677/// IsLICMCandidate - Returns true if the instruction may be a suitable
678/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
679/// not safe to hoist it.
680bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000681 // Check if it's safe to move the instruction.
682 bool DontMoveAcrossStore = true;
683 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000684 return false;
Chris Lattner77910802010-07-12 00:00:35 +0000685
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000686 return true;
687}
688
689/// IsLoopInvariantInst - Returns true if the instruction is loop
690/// invariant. I.e., all virtual register operands are defined outside of the
691/// loop, physical registers aren't accessed explicitly, and there are no side
692/// effects that aren't captured by the operands or other flags.
693///
694bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
695 if (!IsLICMCandidate(I))
696 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000697
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000698 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000699 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
700 const MachineOperand &MO = I.getOperand(i);
701
Dan Gohmand735b802008-10-03 15:45:36 +0000702 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000703 continue;
704
Dan Gohmanc475c362009-01-15 22:01:38 +0000705 unsigned Reg = MO.getReg();
706 if (Reg == 0) continue;
707
708 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000709 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000710 if (MO.isUse()) {
711 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000712 // and we can freely move its uses. Alternatively, if it's allocatable,
713 // it could get allocated to something with a def during allocation.
Evan Cheng0e673912010-10-14 01:16:09 +0000714 if (!MRI->def_empty(Reg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000715 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000716 if (AllocatableSet.test(Reg))
717 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000718 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000719 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
720 unsigned AliasReg = *Alias;
Evan Cheng0e673912010-10-14 01:16:09 +0000721 if (!MRI->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000722 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000723 if (AllocatableSet.test(AliasReg))
724 return false;
725 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000726 // Otherwise it's safe to move.
727 continue;
728 } else if (!MO.isDead()) {
729 // A def that isn't dead. We can't move it.
730 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000731 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
732 // If the reg is live into the loop, we can't hoist an instruction
733 // which would clobber it.
734 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000735 }
736 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000737
738 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000739 continue;
740
Evan Cheng0e673912010-10-14 01:16:09 +0000741 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000742 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000743
744 // If the loop contains the definition of an operand, then the instruction
745 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000746 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000747 return false;
748 }
749
750 // If we got this far, the instruction is loop invariant!
751 return true;
752}
753
Evan Chengaf6949d2009-02-05 08:45:46 +0000754
755/// HasPHIUses - Return true if the specified register has any PHI use.
Evan Cheng0e673912010-10-14 01:16:09 +0000756static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *MRI) {
757 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
758 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000759 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000760 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000761 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000762 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000763 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000764}
765
Evan Cheng87b75ba2009-11-20 19:55:37 +0000766/// isLoadFromConstantMemory - Return true if the given instruction is a
767/// load from constant memory. Machine LICM will hoist these even if they are
768/// not re-materializable.
769bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
770 if (!MI->getDesc().mayLoad()) return false;
771 if (!MI->hasOneMemOperand()) return false;
772 MachineMemOperand *MMO = *MI->memoperands_begin();
773 if (MMO->isVolatile()) return false;
774 if (!MMO->getValue()) return false;
775 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
776 if (PSV) {
777 MachineFunction &MF = *MI->getParent()->getParent();
778 return PSV->isConstant(MF.getFrameInfo());
779 } else {
780 return AA->pointsToConstantMemory(MMO->getValue());
781 }
782}
783
Evan Cheng23128422010-10-19 18:58:51 +0000784/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
785/// and an use in the current loop, return true if the target considered
786/// it 'high'.
787bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
788 unsigned DefIdx, unsigned Reg) {
Evan Cheng0e673912010-10-14 01:16:09 +0000789 if (MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000790 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000791
Evan Cheng0e673912010-10-14 01:16:09 +0000792 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
793 E = MRI->use_nodbg_end(); I != E; ++I) {
794 MachineInstr *UseMI = &*I;
795 if (!CurLoop->contains(UseMI->getParent()))
796 continue;
797 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
798 const MachineOperand &MO = UseMI->getOperand(i);
799 if (!MO.isReg() || !MO.isUse())
800 continue;
801 unsigned MOReg = MO.getReg();
802 if (MOReg != Reg)
803 continue;
804
Evan Cheng23128422010-10-19 18:58:51 +0000805 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
806 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000807 }
808
Evan Cheng23128422010-10-19 18:58:51 +0000809 // Only look at the first in loop use.
810 break;
Evan Cheng0e673912010-10-14 01:16:09 +0000811 }
812
Evan Cheng23128422010-10-19 18:58:51 +0000813 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000814}
815
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000816/// IncreaseHighRegPressure - Visit BBs from preheader to current BB, check
817/// if hoisting an instruction of the given cost matrix can cause high
818/// register pressure.
819bool MachineLICM::IncreaseHighRegPressure(DenseMap<unsigned, int> &Cost) {
820 for (unsigned i = BackTrace.size(); i != 0; --i) {
821 bool AnyIncrease = false;
822 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
823 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
824 CI != CE; ++CI) {
825 if (CI->second <= 0)
826 continue;
827 AnyIncrease = true;
828 unsigned RCId = CI->first;
829 if (RP[RCId] + CI->second >= RegLimit[RCId])
830 return true;
831 }
832
833 if (!AnyIncrease)
834 // Hoisting the instruction doesn't increase register pressure.
835 return false;
836 }
837
838 return false;
839}
840
Evan Cheng45e94d62009-02-04 09:19:56 +0000841/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
842/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000843bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +0000844 if (MI.isImplicitDef())
845 return true;
846
Evan Cheng23128422010-10-19 18:58:51 +0000847 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
848 // will increase register pressure. It's probably not worth it if the
849 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000850 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
851 // these tend to help performance in low register pressure situation. The
852 // trade off is it may cause spill in high pressure situation. It will end up
853 // adding a store in the loop preheader. But the reload is no more expensive.
854 // The side benefit is these loads are frequently CSE'ed.
Evan Cheng23128422010-10-19 18:58:51 +0000855 if (MI.getDesc().isAsCheapAsAMove()) {
856 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +0000857 return false;
858 } else {
Evan Cheng23128422010-10-19 18:58:51 +0000859 // Estimate register pressure to determine whether to LICM the instruction.
Evan Cheng0e673912010-10-14 01:16:09 +0000860 // In low register pressure situation, we can be more aggressive about
861 // hoisting. Also, favors hoisting long latency instructions even in
862 // moderately high pressure situation.
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000863 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +0000864 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
865 const MachineOperand &MO = MI.getOperand(i);
866 if (!MO.isReg() || MO.isImplicit())
867 continue;
868 unsigned Reg = MO.getReg();
869 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
870 continue;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000871 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +0000872 if (HasHighOperandLatency(MI, i, Reg)) {
873 ++NumHighLatency;
874 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000875 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000876
877 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
878 EVT VT = *RC->vt_begin();
879 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
880 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
881 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
882 // If the instruction is not register pressure neutrail (or better),
883 // check if hoisting it will cause high register pressure in BB's
884 // leading up to this point.
885 if (CI != Cost.end())
886 CI->second += RCCost;
887 else
888 Cost.insert(std::make_pair(RCId, RCCost));
889 } else if (MO.isKill()) {
890 // Is a virtual register use is a kill, hoisting it out of the loop
891 // may actually reduce register pressure or be register pressure
892 // neutral
893 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
894 EVT VT = *RC->vt_begin();
895 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
896 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
897 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
898 if (CI != Cost.end())
899 CI->second -= RCCost;
900 else
901 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +0000902 }
903 }
904
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000905 // Visit BBs from preheader to current BB, if hoisting this doesn't cause
906 // high register pressure, then it's safe to proceed.
907 if (!IncreaseHighRegPressure(Cost)) {
908 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +0000909 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000910 }
Evan Cheng0e673912010-10-14 01:16:09 +0000911
912 // High register pressure situation, only hoist if the instruction is going to
913 // be remat'ed.
914 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
915 !isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000916 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000917 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000918
Evan Chengaf6949d2009-02-05 08:45:46 +0000919 // If result(s) of this instruction is used by PHIs, then don't hoist it.
920 // The presence of joins makes it difficult for current register allocator
921 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000922 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
923 const MachineOperand &MO = MI.getOperand(i);
924 if (!MO.isReg() || !MO.isDef())
925 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000926 if (HasPHIUses(MO.getReg(), MRI))
Evan Chengaf6949d2009-02-05 08:45:46 +0000927 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000928 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000929
930 return true;
931}
932
Dan Gohman5c952302009-10-29 17:47:20 +0000933MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +0000934 // Don't unfold simple loads.
935 if (MI->getDesc().canFoldAsLoad())
936 return 0;
937
Dan Gohman5c952302009-10-29 17:47:20 +0000938 // If not, we may be able to unfold a load and hoist that.
939 // First test whether the instruction is loading from an amenable
940 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000941 if (!isLoadFromConstantMemory(MI))
942 return 0;
943
Dan Gohman5c952302009-10-29 17:47:20 +0000944 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000945 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000946 unsigned NewOpc =
947 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
948 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000949 /*UnfoldStore=*/false,
950 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +0000951 if (NewOpc == 0) return 0;
952 const TargetInstrDesc &TID = TII->get(NewOpc);
953 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +0000954 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +0000955 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +0000956 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +0000957
958 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +0000959 SmallVector<MachineInstr *, 2> NewMIs;
960 bool Success =
961 TII->unfoldMemoryOperand(MF, MI, Reg,
962 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
963 NewMIs);
964 (void)Success;
965 assert(Success &&
966 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
967 "succeeded!");
968 assert(NewMIs.size() == 2 &&
969 "Unfolded a load into multiple instructions!");
970 MachineBasicBlock *MBB = MI->getParent();
971 MBB->insert(MI, NewMIs[0]);
972 MBB->insert(MI, NewMIs[1]);
973 // If unfolding produced a load that wasn't loop-invariant or profitable to
974 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +0000975 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +0000976 NewMIs[0]->eraseFromParent();
977 NewMIs[1]->eraseFromParent();
978 return 0;
979 }
980 // Otherwise we successfully unfolded a load that we can hoist.
981 MI->eraseFromParent();
982 return NewMIs[0];
983}
984
Evan Cheng777c6b72009-11-03 21:40:02 +0000985void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
986 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
987 const MachineInstr *MI = &*I;
988 // FIXME: For now, only hoist re-materilizable instructions. LICM will
989 // increase register pressure. We want to make sure it doesn't increase
990 // spilling.
991 if (TII->isTriviallyReMaterializable(MI, AA)) {
992 unsigned Opcode = MI->getOpcode();
993 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
994 CI = CSEMap.find(Opcode);
995 if (CI != CSEMap.end())
996 CI->second.push_back(MI);
997 else {
998 std::vector<const MachineInstr*> CSEMIs;
999 CSEMIs.push_back(MI);
1000 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1001 }
1002 }
1003 }
1004}
1005
Evan Cheng78e5c112009-11-07 03:52:02 +00001006const MachineInstr*
1007MachineLICM::LookForDuplicate(const MachineInstr *MI,
1008 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001009 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1010 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +00001011 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001012 return PrevMI;
1013 }
1014 return 0;
1015}
1016
1017bool MachineLICM::EliminateCSE(MachineInstr *MI,
1018 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001019 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1020 // the undef property onto uses.
1021 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001022 return false;
1023
1024 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001025 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001026
1027 // Replace virtual registers defined by MI by their counterparts defined
1028 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +00001029 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1030 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001031
1032 // Physical registers may not differ here.
1033 assert((!MO.isReg() || MO.getReg() == 0 ||
1034 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1035 MO.getReg() == Dup->getOperand(i).getReg()) &&
1036 "Instructions with different phys regs are not identical!");
1037
1038 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +00001039 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng0e673912010-10-14 01:16:09 +00001040 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1041 MRI->clearKillFlags(Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001042 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001043 }
Evan Cheng78e5c112009-11-07 03:52:02 +00001044 MI->eraseFromParent();
1045 ++NumCSEed;
1046 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001047 }
1048 return false;
1049}
1050
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001051/// Hoist - When an instruction is found to use only loop invariant operands
1052/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001053///
Evan Cheng0e673912010-10-14 01:16:09 +00001054void MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001055 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001056 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001057 // If not, try unfolding a hoistable load.
1058 MI = ExtractHoistableLoad(MI);
1059 if (!MI) return;
Dan Gohman589f1f52009-10-28 03:21:57 +00001060 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001061
Dan Gohmanc475c362009-01-15 22:01:38 +00001062 // Now move the instructions to the predecessor, inserting it before any
1063 // terminator instructions.
1064 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001065 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001066 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001067 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001068 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001069 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001070 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001071 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001072 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001073 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001074
Evan Cheng777c6b72009-11-03 21:40:02 +00001075 // If this is the first instruction being hoisted to the preheader,
1076 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001077 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001078 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001079 FirstInLoop = false;
1080 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001081
Evan Chengaf6949d2009-02-05 08:45:46 +00001082 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001083 unsigned Opcode = MI->getOpcode();
1084 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1085 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001086 if (!EliminateCSE(MI, CI)) {
1087 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001088 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001089
Dan Gohmane6cd7572010-05-13 20:34:42 +00001090 // Clear the kill flags of any register this instruction defines,
1091 // since they may need to be live throughout the entire loop
1092 // rather than just live for part of it.
1093 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1094 MachineOperand &MO = MI->getOperand(i);
1095 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001096 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001097 }
1098
Evan Chengaf6949d2009-02-05 08:45:46 +00001099 // Add to the CSE map.
1100 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001101 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001102 else {
1103 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001104 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001105 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001106 }
1107 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001108
Dan Gohmanc475c362009-01-15 22:01:38 +00001109 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001110 Changed = true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001111}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001112
1113MachineBasicBlock *MachineLICM::getCurPreheader() {
1114 // Determine the block to which to hoist instructions. If we can't find a
1115 // suitable loop predecessor, we can't do any hoisting.
1116
1117 // If we've tried to get a preheader and failed, don't try again.
1118 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1119 return 0;
1120
1121 if (!CurPreheader) {
1122 CurPreheader = CurLoop->getLoopPreheader();
1123 if (!CurPreheader) {
1124 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1125 if (!Pred) {
1126 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1127 return 0;
1128 }
1129
1130 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1131 if (!CurPreheader) {
1132 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1133 return 0;
1134 }
1135 }
1136 }
1137 return CurPreheader;
1138}