blob: 3f060ccc4ea1dc7187da507ca3461f8c57dc8a07 [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"
Chris Lattnerac695822008-01-04 06:41:45 +000040#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000041#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000042
43using namespace llvm;
44
Evan Cheng03a9fdf2010-10-16 02:20:26 +000045STATISTIC(NumHoisted,
46 "Number of machine instructions hoisted out of loops");
47STATISTIC(NumLowRP,
48 "Number of instructions hoisted in low reg pressure situation");
49STATISTIC(NumHighLatency,
50 "Number of high latency instructions hoisted");
51STATISTIC(NumCSEed,
52 "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000053STATISTIC(NumPostRAHoisted,
54 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendlingb48519c2007-12-08 01:47:01 +000055
Bill Wendling0f940c92007-12-07 21:42:31 +000056namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000057 class MachineLICM : public MachineFunctionPass {
Evan Chengd94671a2010-04-07 00:41:17 +000058 bool PreRegAlloc;
59
Bill Wendling9258cd32008-01-02 19:32:43 +000060 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000061 const TargetInstrInfo *TII;
Evan Cheng0e673912010-10-14 01:16:09 +000062 const TargetLowering *TLI;
Dan Gohmana8fb3362009-09-25 23:58:45 +000063 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000064 const MachineFrameInfo *MFI;
Evan Cheng0e673912010-10-14 01:16:09 +000065 MachineRegisterInfo *MRI;
66 const InstrItineraryData *InstrItins;
Bill Wendling12ebf142007-12-11 19:40:06 +000067
Bill Wendling0f940c92007-12-07 21:42:31 +000068 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000069 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +000070 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000071 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000072
Bill Wendling0f940c92007-12-07 21:42:31 +000073 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000074 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +000075 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000076 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000077 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000078
Evan Chengd94671a2010-04-07 00:41:17 +000079 BitVector AllocatableSet;
80
Evan Cheng0e673912010-10-14 01:16:09 +000081 // Track 'estimated' register pressure.
Evan Cheng03a9fdf2010-10-16 02:20:26 +000082 SmallSet<unsigned, 32> RegSeen;
Evan Cheng0e673912010-10-14 01:16:09 +000083 SmallVector<unsigned, 8> RegPressure;
Evan Cheng03a9fdf2010-10-16 02:20:26 +000084
85 // Register pressure "limit" per register class. If the pressure
86 // is higher than the limit, then it's considered high.
Evan Cheng0e673912010-10-14 01:16:09 +000087 SmallVector<unsigned, 8> RegLimit;
88
Evan Cheng03a9fdf2010-10-16 02:20:26 +000089 // Register pressure on path leading from loop preheader to current BB.
90 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
91
Dale Johannesenc46a5f22010-07-29 17:45:24 +000092 // For each opcode, keep a list of potential CSE instructions.
Evan Cheng777c6b72009-11-03 21:40:02 +000093 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000094
Bill Wendling0f940c92007-12-07 21:42:31 +000095 public:
96 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +000097 MachineLICM() :
Owen Anderson081c34b2010-10-19 17:21:58 +000098 MachineFunctionPass(ID), PreRegAlloc(true) {
99 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
100 }
Evan Chengd94671a2010-04-07 00:41:17 +0000101
102 explicit MachineLICM(bool PreRA) :
Owen Anderson081c34b2010-10-19 17:21:58 +0000103 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
104 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
105 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000106
107 virtual bool runOnMachineFunction(MachineFunction &MF);
108
Dan Gohman72241702008-12-18 01:37:56 +0000109 const char *getPassName() const { return "Machine Instruction LICM"; }
110
Bill Wendling0f940c92007-12-07 21:42:31 +0000111 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
112 AU.setPreservesCFG();
113 AU.addRequired<MachineLoopInfo>();
114 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000115 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000116 AU.addPreserved<MachineLoopInfo>();
117 AU.addPreserved<MachineDominatorTree>();
118 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000119 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000120
121 virtual void releaseMemory() {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000122 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000123 RegPressure.clear();
124 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000125 BackTrace.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000126 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
127 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
128 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000129 CSEMap.clear();
130 }
131
Bill Wendling0f940c92007-12-07 21:42:31 +0000132 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000133 /// CandidateInfo - Keep track of information about hoisting candidates.
134 struct CandidateInfo {
135 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000136 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000137 int FI;
138 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
139 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000140 };
141
142 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
143 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000144 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000145
146 /// HoistPostRA - When an instruction is found to only use loop invariant
147 /// operands that is safe to hoist, this instruction is called to do the
148 /// dirty work.
149 void HoistPostRA(MachineInstr *MI, unsigned Def);
150
151 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
152 /// gather register def and frame object update information.
153 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
154 SmallSet<int, 32> &StoredFIs,
155 SmallVector<CandidateInfo, 32> &Candidates);
156
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000157 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
158 /// current loop.
159 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000160
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000161 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000162 /// candidate for LICM. e.g. If the instruction is a call, then it's
163 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000164 bool IsLICMCandidate(MachineInstr &I);
165
Bill Wendling041b3f82007-12-08 23:58:46 +0000166 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000167 /// invariant. I.e., all virtual register operands are defined outside of
168 /// the loop, physical registers aren't accessed (explicitly or implicitly),
169 /// and the instruction is hoistable.
170 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000171 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000172
Evan Cheng23128422010-10-19 18:58:51 +0000173 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
174 /// and an use in the current loop, return true if the target considered
175 /// it 'high'.
176 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx, unsigned Reg);
Evan Cheng0e673912010-10-14 01:16:09 +0000177
Evan Cheng134982d2010-10-20 22:03:58 +0000178 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
179 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000180 /// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000181 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
182
183 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
184 /// the current block and update their register pressures to reflect the
185 /// effect of hoisting MI from the current block to the preheader.
186 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000187
Evan Cheng45e94d62009-02-04 09:19:56 +0000188 /// IsProfitableToHoist - Return true if it is potentially profitable to
189 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000190 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000191
Bill Wendling0f940c92007-12-07 21:42:31 +0000192 /// HoistRegion - Walk the specified region of the CFG (defined by all
193 /// blocks dominated by the specified block, and that are in the current
194 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
195 /// visit definitions before uses, allowing us to hoist a loop body in one
196 /// pass without iteration.
197 ///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000198 void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
Bill Wendling0f940c92007-12-07 21:42:31 +0000199
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000200 /// InitRegPressure - Find all virtual register references that are liveout
201 /// of the preheader to initialize the starting "register pressure". Note
202 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000203 void InitRegPressure(MachineBasicBlock *BB);
204
Evan Cheng134982d2010-10-20 22:03:58 +0000205 /// UpdateRegPressure - Update estimate of register pressure after the
206 /// specified instruction.
207 void UpdateRegPressure(const MachineInstr *MI);
Evan Cheng0e673912010-10-14 01:16:09 +0000208
Evan Cheng87b75ba2009-11-20 19:55:37 +0000209 /// isLoadFromConstantMemory - Return true if the given instruction is a
210 /// load from constant memory.
211 bool isLoadFromConstantMemory(MachineInstr *MI);
212
Dan Gohman5c952302009-10-29 17:47:20 +0000213 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
214 /// the load itself could be hoisted. Return the unfolded and hoistable
215 /// load, or null if the load couldn't be unfolded or if it wouldn't
216 /// be hoistable.
217 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
218
Evan Cheng78e5c112009-11-07 03:52:02 +0000219 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
220 /// duplicate of MI. Return this instruction if it's found.
221 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
222 std::vector<const MachineInstr*> &PrevMIs);
223
Evan Cheng9fb744e2009-11-05 00:51:13 +0000224 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
225 /// the preheader that compute the same value. If it's found, do a RAU on
226 /// with the definition of the existing instruction rather than hoisting
227 /// the instruction to the preheader.
228 bool EliminateCSE(MachineInstr *MI,
229 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
230
Bill Wendling0f940c92007-12-07 21:42:31 +0000231 /// Hoist - When an instruction is found to only use loop invariant operands
232 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000233 /// It returns true if the instruction is hoisted.
234 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000235
236 /// InitCSEMap - Initialize the CSE map with instructions that are in the
237 /// current loop preheader that may become duplicates of instructions that
238 /// are hoisted out of the loop.
239 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000240
241 /// getCurPreheader - Get the preheader for the current loop, splitting
242 /// a critical edge if needed.
243 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000244 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000245} // end anonymous namespace
246
Dan Gohman844731a2008-05-13 00:00:25 +0000247char MachineLICM::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000248INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
249 "Machine Loop Invariant Code Motion", false, false)
250INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
251INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
252INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
253INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000254 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000255
Evan Chengd94671a2010-04-07 00:41:17 +0000256FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
257 return new MachineLICM(PreRegAlloc);
258}
Bill Wendling0f940c92007-12-07 21:42:31 +0000259
Dan Gohman853d3fb2010-06-22 17:25:57 +0000260/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
261/// loop that has a unique predecessor.
262static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000263 // Check whether this loop even has a unique predecessor.
264 if (!CurLoop->getLoopPredecessor())
265 return false;
266 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000267 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000268 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000269 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000270 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000271 return true;
272}
273
Bill Wendling0f940c92007-12-07 21:42:31 +0000274bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000275 if (PreRegAlloc)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000276 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Evan Chengd94671a2010-04-07 00:41:17 +0000277 else
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000278 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
279 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000280
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000281 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000282 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000283 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000284 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000285 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000286 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000287 MRI = &MF.getRegInfo();
288 InstrItins = TM->getInstrItineraryData();
Dan Gohman45094e32009-09-26 02:34:00 +0000289 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000290
Evan Cheng0e673912010-10-14 01:16:09 +0000291 if (PreRegAlloc) {
292 // Estimate register pressure during pre-regalloc pass.
293 unsigned NumRC = TRI->getNumRegClasses();
294 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000295 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000296 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000297 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
298 E = TRI->regclass_end(); I != E; ++I)
299 RegLimit[(*I)->getID()] = TLI->getRegPressureLimit(*I, MF);
300 }
301
Bill Wendling0f940c92007-12-07 21:42:31 +0000302 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000303 MLI = &getAnalysis<MachineLoopInfo>();
304 DT = &getAnalysis<MachineDominatorTree>();
305 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000306
Dan Gohmanaa742602010-07-09 18:49:45 +0000307 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
308 while (!Worklist.empty()) {
309 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000310 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000311
Evan Cheng4038f9c2010-04-08 01:03:47 +0000312 // If this is done before regalloc, only visit outer-most preheader-sporting
313 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000314 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
315 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000316 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000317 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000318
Evan Chengd94671a2010-04-07 00:41:17 +0000319 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000320 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000321 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000322 // CSEMap is initialized for loop header when the first instruction is
323 // being hoisted.
324 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000325 FirstInLoop = true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000326 HoistRegion(N, true);
Evan Chengd94671a2010-04-07 00:41:17 +0000327 CSEMap.clear();
328 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000329 }
330
331 return Changed;
332}
333
Evan Cheng4038f9c2010-04-08 01:03:47 +0000334/// InstructionStoresToFI - Return true if instruction stores to the
335/// specified frame.
336static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
337 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
338 oe = MI->memoperands_end(); o != oe; ++o) {
339 if (!(*o)->isStore() || !(*o)->getValue())
340 continue;
341 if (const FixedStackPseudoSourceValue *Value =
342 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
343 if (Value->getFrameIndex() == FI)
344 return true;
345 }
346 }
347 return false;
348}
349
350/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
351/// gather register def and frame object update information.
352void MachineLICM::ProcessMI(MachineInstr *MI,
353 unsigned *PhysRegDefs,
354 SmallSet<int, 32> &StoredFIs,
355 SmallVector<CandidateInfo, 32> &Candidates) {
356 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000357 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000358 unsigned Def = 0;
359 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
360 const MachineOperand &MO = MI->getOperand(i);
361 if (MO.isFI()) {
362 // Remember if the instruction stores to the frame index.
363 int FI = MO.getIndex();
364 if (!StoredFIs.count(FI) &&
365 MFI->isSpillSlotObjectIndex(FI) &&
366 InstructionStoresToFI(MI, FI))
367 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000368 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000369 continue;
370 }
371
372 if (!MO.isReg())
373 continue;
374 unsigned Reg = MO.getReg();
375 if (!Reg)
376 continue;
377 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
378 "Not expecting virtual register!");
379
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000380 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000381 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000382 // If it's using a non-loop-invariant register, then it's obviously not
383 // safe to hoist.
384 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000385 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000386 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000387
388 if (MO.isImplicit()) {
389 ++PhysRegDefs[Reg];
390 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
391 ++PhysRegDefs[*AS];
392 if (!MO.isDead())
393 // Non-dead implicit def? This cannot be hoisted.
394 RuledOut = true;
395 // No need to check if a dead implicit def is also defined by
396 // another instruction.
397 continue;
398 }
399
400 // FIXME: For now, avoid instructions with multiple defs, unless
401 // it's a dead implicit def.
402 if (Def)
403 RuledOut = true;
404 else
405 Def = Reg;
406
407 // If we have already seen another instruction that defines the same
408 // register, then this is not safe.
409 if (++PhysRegDefs[Reg] > 1)
410 // MI defined register is seen defined by another instruction in
411 // the loop, it cannot be a LICM candidate.
412 RuledOut = true;
413 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
414 if (++PhysRegDefs[*AS] > 1)
415 RuledOut = true;
416 }
417
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000418 // Only consider reloads for now and remats which do not have register
419 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000420 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000421 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000422 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000423 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
424 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000425 }
426}
427
428/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
429/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000430void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000431 unsigned NumRegs = TRI->getNumRegs();
432 unsigned *PhysRegDefs = new unsigned[NumRegs];
433 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
434
Evan Cheng4038f9c2010-04-08 01:03:47 +0000435 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000436 SmallSet<int, 32> StoredFIs;
437
438 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000439 // collect potential LICM candidates.
440 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
441 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
442 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000443 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000444 // FIXME: That means a reload that're reused in successor block(s) will not
445 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000446 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000447 E = BB->livein_end(); I != E; ++I) {
448 unsigned Reg = *I;
449 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000450 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
451 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000452 }
453
454 for (MachineBasicBlock::iterator
455 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000456 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000457 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000458 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000459 }
Evan Chengd94671a2010-04-07 00:41:17 +0000460
461 // Now evaluate whether the potential candidates qualify.
462 // 1. Check if the candidate defined register is defined by another
463 // instruction in the loop.
464 // 2. If the candidate is a load from stack slot (always true for now),
465 // check if the slot is stored anywhere in the loop.
466 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000467 if (Candidates[i].FI != INT_MIN &&
468 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000469 continue;
470
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000471 if (PhysRegDefs[Candidates[i].Def] == 1) {
472 bool Safe = true;
473 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000474 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
475 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000476 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000477 continue;
478 if (PhysRegDefs[MO.getReg()]) {
479 // If it's using a non-loop-invariant register, then it's obviously
480 // not safe to hoist.
481 Safe = false;
482 break;
483 }
484 }
485 if (Safe)
486 HoistPostRA(MI, Candidates[i].Def);
487 }
Evan Chengd94671a2010-04-07 00:41:17 +0000488 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000489
490 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000491}
492
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000493/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
494/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000495void MachineLICM::AddToLiveIns(unsigned Reg) {
496 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000497 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
498 MachineBasicBlock *BB = Blocks[i];
499 if (!BB->isLiveIn(Reg))
500 BB->addLiveIn(Reg);
501 for (MachineBasicBlock::iterator
502 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
503 MachineInstr *MI = &*MII;
504 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
505 MachineOperand &MO = MI->getOperand(i);
506 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
507 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
508 MO.setIsKill(false);
509 }
510 }
511 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000512}
513
514/// HoistPostRA - When an instruction is found to only use loop invariant
515/// operands that is safe to hoist, this instruction is called to do the
516/// dirty work.
517void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000518 MachineBasicBlock *Preheader = getCurPreheader();
519 if (!Preheader) return;
520
Evan Chengd94671a2010-04-07 00:41:17 +0000521 // Now move the instructions to the predecessor, inserting it before any
522 // terminator instructions.
523 DEBUG({
524 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000525 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000526 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000527 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000528 if (MI->getParent()->getBasicBlock())
529 dbgs() << " from MachineBasicBlock "
530 << MI->getParent()->getName();
531 dbgs() << "\n";
532 });
533
534 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000535 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000536 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000537
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000538 // Add register to livein list to all the BBs in the current loop since a
539 // loop invariant must be kept live throughout the whole loop. This is
540 // important to ensure later passes do not scavenge the def register.
541 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000542
543 ++NumPostRAHoisted;
544 Changed = true;
545}
546
Bill Wendling0f940c92007-12-07 21:42:31 +0000547/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
548/// dominated by the specified block, and that are in the current loop) in depth
549/// first order w.r.t the DominatorTree. This allows us to visit definitions
550/// before uses, allowing us to hoist a loop body in one pass without iteration.
551///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000552void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000553 assert(N != 0 && "Null dominator tree node?");
554 MachineBasicBlock *BB = N->getBlock();
555
556 // If this subregion is not in the top level loop at all, exit.
557 if (!CurLoop->contains(BB)) return;
558
Evan Cheng0e673912010-10-14 01:16:09 +0000559 MachineBasicBlock *Preheader = getCurPreheader();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000560 if (!Preheader)
561 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000562
Evan Cheng23128422010-10-19 18:58:51 +0000563 if (IsHeader) {
Evan Cheng134982d2010-10-20 22:03:58 +0000564 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000565 RegSeen.clear();
566 BackTrace.clear();
567 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000568 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000569
Evan Cheng23128422010-10-19 18:58:51 +0000570 // Remember livein register pressure.
571 BackTrace.push_back(RegPressure);
572
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000573 for (MachineBasicBlock::iterator
574 MII = BB->begin(), E = BB->end(); MII != E; ) {
575 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
576 MachineInstr *MI = &*MII;
Evan Cheng134982d2010-10-20 22:03:58 +0000577 if (!Hoist(MI, Preheader))
578 UpdateRegPressure(MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000579 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000580 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000581
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000582 // Don't hoist things out of a large switch statement. This often causes
583 // code to be hoisted that wasn't going to be executed, and increases
584 // register pressure in a situation where it's likely to matter.
Dale Johannesen21d35c12010-07-20 21:29:12 +0000585 if (BB->succ_size() < 25) {
586 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000587 for (unsigned I = 0, E = Children.size(); I != E; ++I)
588 HoistRegion(Children[I]);
Dale Johannesen21d35c12010-07-20 21:29:12 +0000589 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000590
Evan Cheng23128422010-10-19 18:58:51 +0000591 BackTrace.pop_back();
Bill Wendling0f940c92007-12-07 21:42:31 +0000592}
593
Evan Cheng134982d2010-10-20 22:03:58 +0000594static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
595 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
596}
597
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000598/// InitRegPressure - Find all virtual register references that are liveout of
599/// the preheader to initialize the starting "register pressure". Note this
600/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000601void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000602 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000603
Evan Cheng134982d2010-10-20 22:03:58 +0000604 // If the preheader has only a single predecessor and it ends with a
605 // fallthrough or an unconditional branch, then scan its predecessor for live
606 // defs as well. This happens whenever the preheader is created by splitting
607 // the critical edge from the loop predecessor to the loop header.
608 if (BB->pred_size() == 1) {
609 MachineBasicBlock *TBB = 0, *FBB = 0;
610 SmallVector<MachineOperand, 4> Cond;
611 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
612 InitRegPressure(*BB->pred_begin());
613 }
614
Evan Cheng0e673912010-10-14 01:16:09 +0000615 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
616 MII != E; ++MII) {
617 MachineInstr *MI = &*MII;
618 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
619 const MachineOperand &MO = MI->getOperand(i);
620 if (!MO.isReg() || MO.isImplicit())
621 continue;
622 unsigned Reg = MO.getReg();
623 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
624 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000625
Andrew Trickdc986d22010-10-19 02:50:50 +0000626 bool isNew = RegSeen.insert(Reg);
Evan Cheng0e673912010-10-14 01:16:09 +0000627 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
628 EVT VT = *RC->vt_begin();
629 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000630 if (MO.isDef())
631 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
632 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000633 bool isKill = isOperandKill(MO, MRI);
634 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000635 // Haven't seen this, it must be a livein.
636 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Evan Cheng134982d2010-10-20 22:03:58 +0000637 else if (!isNew && isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000638 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
639 }
Evan Cheng0e673912010-10-14 01:16:09 +0000640 }
641 }
642}
643
Evan Cheng134982d2010-10-20 22:03:58 +0000644/// UpdateRegPressure - Update estimate of register pressure after the
645/// specified instruction.
646void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
647 if (MI->isImplicitDef())
648 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000649
Evan Cheng134982d2010-10-20 22:03:58 +0000650 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000651 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
652 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000653 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000654 continue;
655 unsigned Reg = MO.getReg();
656 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
657 continue;
658
Andrew Trickdc986d22010-10-19 02:50:50 +0000659 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000660 if (MO.isDef())
661 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000662 else if (!isNew && isOperandKill(MO, MRI)) {
663 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
664 EVT VT = *RC->vt_begin();
665 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
666 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000667
Evan Cheng134982d2010-10-20 22:03:58 +0000668 if (RCCost > RegPressure[RCId])
669 RegPressure[RCId] = 0;
670 else
Evan Cheng23128422010-10-19 18:58:51 +0000671 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000672 }
Evan Cheng0e673912010-10-14 01:16:09 +0000673 }
Evan Cheng0e673912010-10-14 01:16:09 +0000674
Evan Cheng23128422010-10-19 18:58:51 +0000675 while (!Defs.empty()) {
676 unsigned Reg = Defs.pop_back_val();
Evan Cheng0e673912010-10-14 01:16:09 +0000677 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
678 EVT VT = *RC->vt_begin();
679 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
680 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
681 RegPressure[RCId] += RCCost;
682 }
683}
684
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000685/// IsLICMCandidate - Returns true if the instruction may be a suitable
686/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
687/// not safe to hoist it.
688bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000689 // Check if it's safe to move the instruction.
690 bool DontMoveAcrossStore = true;
691 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000692 return false;
Chris Lattner77910802010-07-12 00:00:35 +0000693
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000694 return true;
695}
696
697/// IsLoopInvariantInst - Returns true if the instruction is loop
698/// invariant. I.e., all virtual register operands are defined outside of the
699/// loop, physical registers aren't accessed explicitly, and there are no side
700/// effects that aren't captured by the operands or other flags.
701///
702bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
703 if (!IsLICMCandidate(I))
704 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000705
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000706 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000707 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
708 const MachineOperand &MO = I.getOperand(i);
709
Dan Gohmand735b802008-10-03 15:45:36 +0000710 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000711 continue;
712
Dan Gohmanc475c362009-01-15 22:01:38 +0000713 unsigned Reg = MO.getReg();
714 if (Reg == 0) continue;
715
716 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000717 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000718 if (MO.isUse()) {
719 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000720 // and we can freely move its uses. Alternatively, if it's allocatable,
721 // it could get allocated to something with a def during allocation.
Evan Cheng0e673912010-10-14 01:16:09 +0000722 if (!MRI->def_empty(Reg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000723 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000724 if (AllocatableSet.test(Reg))
725 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000726 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000727 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
728 unsigned AliasReg = *Alias;
Evan Cheng0e673912010-10-14 01:16:09 +0000729 if (!MRI->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000730 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000731 if (AllocatableSet.test(AliasReg))
732 return false;
733 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000734 // Otherwise it's safe to move.
735 continue;
736 } else if (!MO.isDead()) {
737 // A def that isn't dead. We can't move it.
738 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000739 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
740 // If the reg is live into the loop, we can't hoist an instruction
741 // which would clobber it.
742 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000743 }
744 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000745
746 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000747 continue;
748
Evan Cheng0e673912010-10-14 01:16:09 +0000749 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000750 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000751
752 // If the loop contains the definition of an operand, then the instruction
753 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000754 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000755 return false;
756 }
757
758 // If we got this far, the instruction is loop invariant!
759 return true;
760}
761
Evan Chengaf6949d2009-02-05 08:45:46 +0000762
763/// HasPHIUses - Return true if the specified register has any PHI use.
Evan Cheng0e673912010-10-14 01:16:09 +0000764static bool HasPHIUses(unsigned Reg, MachineRegisterInfo *MRI) {
765 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
766 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000767 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000768 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000769 return true;
Evan Cheng45e94d62009-02-04 09:19:56 +0000770 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000771 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000772}
773
Evan Cheng87b75ba2009-11-20 19:55:37 +0000774/// isLoadFromConstantMemory - Return true if the given instruction is a
775/// load from constant memory. Machine LICM will hoist these even if they are
776/// not re-materializable.
777bool MachineLICM::isLoadFromConstantMemory(MachineInstr *MI) {
778 if (!MI->getDesc().mayLoad()) return false;
779 if (!MI->hasOneMemOperand()) return false;
780 MachineMemOperand *MMO = *MI->memoperands_begin();
781 if (MMO->isVolatile()) return false;
782 if (!MMO->getValue()) return false;
783 const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(MMO->getValue());
784 if (PSV) {
785 MachineFunction &MF = *MI->getParent()->getParent();
786 return PSV->isConstant(MF.getFrameInfo());
787 } else {
Dan Gohmanf96e4bd2010-10-20 00:31:05 +0000788 return AA->pointsToConstantMemory(AliasAnalysis::Location(MMO->getValue(),
789 MMO->getSize(),
790 MMO->getTBAAInfo()));
Evan Cheng87b75ba2009-11-20 19:55:37 +0000791 }
792}
793
Evan Cheng23128422010-10-19 18:58:51 +0000794/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
795/// and an use in the current loop, return true if the target considered
796/// it 'high'.
797bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
798 unsigned DefIdx, unsigned Reg) {
Evan Cheng0e673912010-10-14 01:16:09 +0000799 if (MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000800 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000801
Evan Cheng0e673912010-10-14 01:16:09 +0000802 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
803 E = MRI->use_nodbg_end(); I != E; ++I) {
804 MachineInstr *UseMI = &*I;
805 if (!CurLoop->contains(UseMI->getParent()))
806 continue;
807 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
808 const MachineOperand &MO = UseMI->getOperand(i);
809 if (!MO.isReg() || !MO.isUse())
810 continue;
811 unsigned MOReg = MO.getReg();
812 if (MOReg != Reg)
813 continue;
814
Evan Cheng23128422010-10-19 18:58:51 +0000815 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
816 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000817 }
818
Evan Cheng23128422010-10-19 18:58:51 +0000819 // Only look at the first in loop use.
820 break;
Evan Cheng0e673912010-10-14 01:16:09 +0000821 }
822
Evan Cheng23128422010-10-19 18:58:51 +0000823 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000824}
825
Evan Cheng134982d2010-10-20 22:03:58 +0000826/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000827/// if hoisting an instruction of the given cost matrix can cause high
828/// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000829bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
830 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
831 CI != CE; ++CI) {
832 if (CI->second <= 0)
833 continue;
834
835 unsigned RCId = CI->first;
836 for (unsigned i = BackTrace.size(); i != 0; --i) {
837 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000838 if (RP[RCId] + CI->second >= RegLimit[RCId])
839 return true;
840 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000841 }
842
843 return false;
844}
845
Evan Cheng134982d2010-10-20 22:03:58 +0000846/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
847/// current block and update their register pressures to reflect the effect
848/// of hoisting MI from the current block to the preheader.
849void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
850 if (MI->isImplicitDef())
851 return;
852
853 // First compute the 'cost' of the instruction, i.e. its contribution
854 // to register pressure.
855 DenseMap<unsigned, int> Cost;
856 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
857 const MachineOperand &MO = MI->getOperand(i);
858 if (!MO.isReg() || MO.isImplicit())
859 continue;
860 unsigned Reg = MO.getReg();
861 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
862 continue;
863
864 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
865 EVT VT = *RC->vt_begin();
866 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
867 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
868 if (MO.isDef()) {
869 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
870 if (CI != Cost.end())
871 CI->second += RCCost;
872 else
873 Cost.insert(std::make_pair(RCId, RCCost));
874 } else if (isOperandKill(MO, MRI)) {
875 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
876 if (CI != Cost.end())
877 CI->second -= RCCost;
878 else
879 Cost.insert(std::make_pair(RCId, -RCCost));
880 }
881 }
882
883 // Update register pressure of blocks from loop header to current block.
884 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
885 SmallVector<unsigned, 8> &RP = BackTrace[i];
886 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
887 CI != CE; ++CI) {
888 unsigned RCId = CI->first;
889 RP[RCId] += CI->second;
890 }
891 }
892}
893
Evan Cheng45e94d62009-02-04 09:19:56 +0000894/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
895/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000896bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +0000897 if (MI.isImplicitDef())
898 return true;
899
Evan Cheng23128422010-10-19 18:58:51 +0000900 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
901 // will increase register pressure. It's probably not worth it if the
902 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000903 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
904 // these tend to help performance in low register pressure situation. The
905 // trade off is it may cause spill in high pressure situation. It will end up
906 // adding a store in the loop preheader. But the reload is no more expensive.
907 // The side benefit is these loads are frequently CSE'ed.
Evan Cheng23128422010-10-19 18:58:51 +0000908 if (MI.getDesc().isAsCheapAsAMove()) {
909 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +0000910 return false;
911 } else {
Evan Cheng23128422010-10-19 18:58:51 +0000912 // Estimate register pressure to determine whether to LICM the instruction.
Evan Cheng0e673912010-10-14 01:16:09 +0000913 // In low register pressure situation, we can be more aggressive about
914 // hoisting. Also, favors hoisting long latency instructions even in
915 // moderately high pressure situation.
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000916 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +0000917 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
918 const MachineOperand &MO = MI.getOperand(i);
919 if (!MO.isReg() || MO.isImplicit())
920 continue;
921 unsigned Reg = MO.getReg();
922 if (!Reg || TargetRegisterInfo::isPhysicalRegister(Reg))
923 continue;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000924 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +0000925 if (HasHighOperandLatency(MI, i, Reg)) {
926 ++NumHighLatency;
927 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000928 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000929
930 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
931 EVT VT = *RC->vt_begin();
932 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
933 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
934 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000935 if (CI != Cost.end())
936 CI->second += RCCost;
937 else
938 Cost.insert(std::make_pair(RCId, RCCost));
Evan Cheng134982d2010-10-20 22:03:58 +0000939 } else if (isOperandKill(MO, MRI)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000940 // Is a virtual register use is a kill, hoisting it out of the loop
941 // may actually reduce register pressure or be register pressure
Evan Cheng134982d2010-10-20 22:03:58 +0000942 // neutral.
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000943 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
944 EVT VT = *RC->vt_begin();
945 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
946 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
947 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
948 if (CI != Cost.end())
949 CI->second -= RCCost;
950 else
951 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +0000952 }
953 }
954
Evan Cheng134982d2010-10-20 22:03:58 +0000955 // Visit BBs from header to current BB, if hoisting this doesn't cause
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000956 // high register pressure, then it's safe to proceed.
Evan Cheng134982d2010-10-20 22:03:58 +0000957 if (!CanCauseHighRegPressure(Cost)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000958 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +0000959 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000960 }
Evan Cheng0e673912010-10-14 01:16:09 +0000961
962 // High register pressure situation, only hoist if the instruction is going to
963 // be remat'ed.
964 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
965 !isLoadFromConstantMemory(&MI))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000966 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000967 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000968
Evan Chengaf6949d2009-02-05 08:45:46 +0000969 // If result(s) of this instruction is used by PHIs, then don't hoist it.
970 // The presence of joins makes it difficult for current register allocator
971 // implementation to perform remat.
Evan Cheng45e94d62009-02-04 09:19:56 +0000972 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
973 const MachineOperand &MO = MI.getOperand(i);
974 if (!MO.isReg() || !MO.isDef())
975 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000976 if (HasPHIUses(MO.getReg(), MRI))
Evan Chengaf6949d2009-02-05 08:45:46 +0000977 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000978 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000979
980 return true;
981}
982
Dan Gohman5c952302009-10-29 17:47:20 +0000983MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +0000984 // Don't unfold simple loads.
985 if (MI->getDesc().canFoldAsLoad())
986 return 0;
987
Dan Gohman5c952302009-10-29 17:47:20 +0000988 // If not, we may be able to unfold a load and hoist that.
989 // First test whether the instruction is loading from an amenable
990 // memory location.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000991 if (!isLoadFromConstantMemory(MI))
992 return 0;
993
Dan Gohman5c952302009-10-29 17:47:20 +0000994 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +0000995 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +0000996 unsigned NewOpc =
997 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
998 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +0000999 /*UnfoldStore=*/false,
1000 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001001 if (NewOpc == 0) return 0;
1002 const TargetInstrDesc &TID = TII->get(NewOpc);
1003 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +00001004 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001005 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001006 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001007
1008 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001009 SmallVector<MachineInstr *, 2> NewMIs;
1010 bool Success =
1011 TII->unfoldMemoryOperand(MF, MI, Reg,
1012 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1013 NewMIs);
1014 (void)Success;
1015 assert(Success &&
1016 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1017 "succeeded!");
1018 assert(NewMIs.size() == 2 &&
1019 "Unfolded a load into multiple instructions!");
1020 MachineBasicBlock *MBB = MI->getParent();
1021 MBB->insert(MI, NewMIs[0]);
1022 MBB->insert(MI, NewMIs[1]);
1023 // If unfolding produced a load that wasn't loop-invariant or profitable to
1024 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001025 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001026 NewMIs[0]->eraseFromParent();
1027 NewMIs[1]->eraseFromParent();
1028 return 0;
1029 }
Evan Cheng134982d2010-10-20 22:03:58 +00001030
1031 // Update register pressure for the unfolded instruction.
1032 UpdateRegPressure(NewMIs[1]);
1033
Dan Gohman5c952302009-10-29 17:47:20 +00001034 // Otherwise we successfully unfolded a load that we can hoist.
1035 MI->eraseFromParent();
1036 return NewMIs[0];
1037}
1038
Evan Cheng777c6b72009-11-03 21:40:02 +00001039void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1040 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1041 const MachineInstr *MI = &*I;
1042 // FIXME: For now, only hoist re-materilizable instructions. LICM will
1043 // increase register pressure. We want to make sure it doesn't increase
1044 // spilling.
1045 if (TII->isTriviallyReMaterializable(MI, AA)) {
1046 unsigned Opcode = MI->getOpcode();
1047 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1048 CI = CSEMap.find(Opcode);
1049 if (CI != CSEMap.end())
1050 CI->second.push_back(MI);
1051 else {
1052 std::vector<const MachineInstr*> CSEMIs;
1053 CSEMIs.push_back(MI);
1054 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
1055 }
1056 }
1057 }
1058}
1059
Evan Cheng78e5c112009-11-07 03:52:02 +00001060const MachineInstr*
1061MachineLICM::LookForDuplicate(const MachineInstr *MI,
1062 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001063 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1064 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng506049f2010-03-03 01:44:33 +00001065 if (TII->produceSameValue(MI, PrevMI))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001066 return PrevMI;
1067 }
1068 return 0;
1069}
1070
1071bool MachineLICM::EliminateCSE(MachineInstr *MI,
1072 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001073 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1074 // the undef property onto uses.
1075 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001076 return false;
1077
1078 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001079 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001080
1081 // Replace virtual registers defined by MI by their counterparts defined
1082 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +00001083 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1084 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001085
1086 // Physical registers may not differ here.
1087 assert((!MO.isReg() || MO.getReg() == 0 ||
1088 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1089 MO.getReg() == Dup->getOperand(i).getReg()) &&
1090 "Instructions with different phys regs are not identical!");
1091
1092 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +00001093 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng0e673912010-10-14 01:16:09 +00001094 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1095 MRI->clearKillFlags(Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001096 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001097 }
Evan Cheng78e5c112009-11-07 03:52:02 +00001098 MI->eraseFromParent();
1099 ++NumCSEed;
1100 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001101 }
1102 return false;
1103}
1104
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001105/// Hoist - When an instruction is found to use only loop invariant operands
1106/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001107///
Evan Cheng134982d2010-10-20 22:03:58 +00001108bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001109 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001110 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001111 // If not, try unfolding a hoistable load.
1112 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001113 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001114 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001115
Dan Gohmanc475c362009-01-15 22:01:38 +00001116 // Now move the instructions to the predecessor, inserting it before any
1117 // terminator instructions.
1118 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001119 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001120 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001121 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001122 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001123 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001124 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001125 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001126 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001127 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001128
Evan Cheng777c6b72009-11-03 21:40:02 +00001129 // If this is the first instruction being hoisted to the preheader,
1130 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001131 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001132 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001133 FirstInLoop = false;
1134 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001135
Evan Chengaf6949d2009-02-05 08:45:46 +00001136 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001137 unsigned Opcode = MI->getOpcode();
1138 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1139 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001140 if (!EliminateCSE(MI, CI)) {
1141 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001142 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001143
Evan Cheng134982d2010-10-20 22:03:58 +00001144 // Update register pressure for BBs from header to this block.
1145 UpdateBackTraceRegPressure(MI);
1146
Dan Gohmane6cd7572010-05-13 20:34:42 +00001147 // Clear the kill flags of any register this instruction defines,
1148 // since they may need to be live throughout the entire loop
1149 // rather than just live for part of it.
1150 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1151 MachineOperand &MO = MI->getOperand(i);
1152 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001153 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001154 }
1155
Evan Chengaf6949d2009-02-05 08:45:46 +00001156 // Add to the CSE map.
1157 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001158 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001159 else {
1160 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001161 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001162 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001163 }
1164 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001165
Dan Gohmanc475c362009-01-15 22:01:38 +00001166 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001167 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001168
1169 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001170}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001171
1172MachineBasicBlock *MachineLICM::getCurPreheader() {
1173 // Determine the block to which to hoist instructions. If we can't find a
1174 // suitable loop predecessor, we can't do any hoisting.
1175
1176 // If we've tried to get a preheader and failed, don't try again.
1177 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1178 return 0;
1179
1180 if (!CurPreheader) {
1181 CurPreheader = CurLoop->getLoopPreheader();
1182 if (!CurPreheader) {
1183 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1184 if (!Pred) {
1185 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1186 return 0;
1187 }
1188
1189 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1190 if (!CurPreheader) {
1191 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1192 return 0;
1193 }
1194 }
1195 }
1196 return CurPreheader;
1197}