blob: dfc622d0eda8cb882302101030ee27a10487c796 [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 Chengab8be962011-06-29 01:14:12 +000031#include "llvm/MC/MCInstrItineraries.h"
Evan Cheng0e673912010-10-14 01:16:09 +000032#include "llvm/Target/TargetLowering.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000033#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000034#include "llvm/Target/TargetInstrInfo.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 Cheng7007e4c2011-10-12 21:33:49 +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 +000043using namespace llvm;
44
Evan Cheng7007e4c2011-10-12 21:33:49 +000045static cl::opt<bool>
46AvoidSpeculation("avoid-speculation",
47 cl::desc("MachineLICM should avoid speculation"),
Evan Cheng73b5bb32011-10-26 01:26:57 +000048 cl::init(true), cl::Hidden);
Evan Cheng7007e4c2011-10-12 21:33:49 +000049
Evan Cheng03a9fdf2010-10-16 02:20:26 +000050STATISTIC(NumHoisted,
51 "Number of machine instructions hoisted out of loops");
52STATISTIC(NumLowRP,
53 "Number of instructions hoisted in low reg pressure situation");
54STATISTIC(NumHighLatency,
55 "Number of high latency instructions hoisted");
56STATISTIC(NumCSEed,
57 "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000058STATISTIC(NumPostRAHoisted,
59 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendlingb48519c2007-12-08 01:47:01 +000060
Bill Wendling0f940c92007-12-07 21:42:31 +000061namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000062 class MachineLICM : public MachineFunctionPass {
Bill Wendling9258cd32008-01-02 19:32:43 +000063 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000064 const TargetInstrInfo *TII;
Evan Cheng0e673912010-10-14 01:16:09 +000065 const TargetLowering *TLI;
Dan Gohmana8fb3362009-09-25 23:58:45 +000066 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000067 const MachineFrameInfo *MFI;
Evan Cheng0e673912010-10-14 01:16:09 +000068 MachineRegisterInfo *MRI;
69 const InstrItineraryData *InstrItins;
Andrew Trick9d41bd52012-02-08 21:23:03 +000070 bool PreRegAlloc;
Bill Wendling12ebf142007-12-11 19:40:06 +000071
Bill Wendling0f940c92007-12-07 21:42:31 +000072 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000073 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +000074 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000075 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000076
Bill Wendling0f940c92007-12-07 21:42:31 +000077 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000078 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +000079 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000080 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000081 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000082
Evan Cheng0e673912010-10-14 01:16:09 +000083 // Track 'estimated' register pressure.
Evan Cheng03a9fdf2010-10-16 02:20:26 +000084 SmallSet<unsigned, 32> RegSeen;
Evan Cheng0e673912010-10-14 01:16:09 +000085 SmallVector<unsigned, 8> RegPressure;
Evan Cheng03a9fdf2010-10-16 02:20:26 +000086
87 // Register pressure "limit" per register class. If the pressure
88 // is higher than the limit, then it's considered high.
Evan Cheng0e673912010-10-14 01:16:09 +000089 SmallVector<unsigned, 8> RegLimit;
90
Evan Cheng03a9fdf2010-10-16 02:20:26 +000091 // Register pressure on path leading from loop preheader to current BB.
92 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
93
Dale Johannesenc46a5f22010-07-29 17:45:24 +000094 // For each opcode, keep a list of potential CSE instructions.
Evan Cheng777c6b72009-11-03 21:40:02 +000095 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000096
Evan Chengfad62872011-10-11 23:48:44 +000097 enum {
98 SpeculateFalse = 0,
99 SpeculateTrue = 1,
100 SpeculateUnknown = 2
101 };
102
Devang Patel2e350472011-10-11 18:09:58 +0000103 // If a MBB does not dominate loop exiting blocks then it may not safe
104 // to hoist loads from this block.
Evan Chengfad62872011-10-11 23:48:44 +0000105 // Tri-state: 0 - false, 1 - true, 2 - unknown
106 unsigned SpeculationState;
Devang Patel2e350472011-10-11 18:09:58 +0000107
Bill Wendling0f940c92007-12-07 21:42:31 +0000108 public:
109 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +0000110 MachineLICM() :
Owen Anderson081c34b2010-10-19 17:21:58 +0000111 MachineFunctionPass(ID), PreRegAlloc(true) {
112 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
113 }
Evan Chengd94671a2010-04-07 00:41:17 +0000114
115 explicit MachineLICM(bool PreRA) :
Owen Anderson081c34b2010-10-19 17:21:58 +0000116 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
117 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
118 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000119
120 virtual bool runOnMachineFunction(MachineFunction &MF);
121
Bill Wendling0f940c92007-12-07 21:42:31 +0000122 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Bill Wendling0f940c92007-12-07 21:42:31 +0000123 AU.addRequired<MachineLoopInfo>();
124 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000125 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000126 AU.addPreserved<MachineLoopInfo>();
127 AU.addPreserved<MachineDominatorTree>();
128 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000129 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000130
131 virtual void releaseMemory() {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000132 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000133 RegPressure.clear();
134 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000135 BackTrace.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000136 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
137 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
138 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000139 CSEMap.clear();
140 }
141
Bill Wendling0f940c92007-12-07 21:42:31 +0000142 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000143 /// CandidateInfo - Keep track of information about hoisting candidates.
144 struct CandidateInfo {
145 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000146 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000147 int FI;
148 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
149 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000150 };
151
152 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
153 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000154 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000155
156 /// HoistPostRA - When an instruction is found to only use loop invariant
157 /// operands that is safe to hoist, this instruction is called to do the
158 /// dirty work.
159 void HoistPostRA(MachineInstr *MI, unsigned Def);
160
161 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
162 /// gather register def and frame object update information.
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000163 void ProcessMI(MachineInstr *MI,
164 BitVector &PhysRegDefs,
165 BitVector &PhysRegClobbers,
Evan Cheng4038f9c2010-04-08 01:03:47 +0000166 SmallSet<int, 32> &StoredFIs,
167 SmallVector<CandidateInfo, 32> &Candidates);
168
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000169 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
170 /// current loop.
171 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000172
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000173 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000174 /// candidate for LICM. e.g. If the instruction is a call, then it's
175 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000176 bool IsLICMCandidate(MachineInstr &I);
177
Bill Wendling041b3f82007-12-08 23:58:46 +0000178 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000179 /// invariant. I.e., all virtual register operands are defined outside of
180 /// the loop, physical registers aren't accessed (explicitly or implicitly),
181 /// and the instruction is hoistable.
Andrew Trick9f17cf62012-02-08 21:23:00 +0000182 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000183 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000184
Evan Chengd67705f2011-04-11 21:09:18 +0000185 /// HasAnyPHIUse - Return true if the specified register is used by any
186 /// phi node.
187 bool HasAnyPHIUse(unsigned Reg) const;
188
Evan Cheng23128422010-10-19 18:58:51 +0000189 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
190 /// and an use in the current loop, return true if the target considered
191 /// it 'high'.
Evan Chengc8141df2010-10-26 02:08:50 +0000192 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
193 unsigned Reg) const;
194
195 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Cheng0e673912010-10-14 01:16:09 +0000196
Evan Cheng134982d2010-10-20 22:03:58 +0000197 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
198 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000199 /// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000200 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
201
202 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
203 /// the current block and update their register pressures to reflect the
204 /// effect of hoisting MI from the current block to the preheader.
205 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000206
Evan Cheng45e94d62009-02-04 09:19:56 +0000207 /// IsProfitableToHoist - Return true if it is potentially profitable to
208 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000209 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000210
Devang Patel2e350472011-10-11 18:09:58 +0000211 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
212 /// If not then a load from this mbb may not be safe to hoist.
213 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
214
Pete Cooperacde91e2011-12-22 02:05:40 +0000215 void EnterScope(MachineBasicBlock *MBB);
216
217 void ExitScope(MachineBasicBlock *MBB);
218
219 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
220 /// dominator tree node if its a leaf or all of its children are done. Walk
221 /// up the dominator tree to destroy ancestors which are now done.
222 void ExitScopeIfDone(MachineDomTreeNode *Node,
223 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
224 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
225
226 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
227 /// blocks dominated by the specified header block, and that are in the
228 /// current loop) in depth first order w.r.t the DominatorTree. This allows
229 /// us to visit definitions before uses, allowing us to hoist a loop body in
230 /// one pass without iteration.
Bill Wendling0f940c92007-12-07 21:42:31 +0000231 ///
Pete Cooperacde91e2011-12-22 02:05:40 +0000232 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
233 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendling0f940c92007-12-07 21:42:31 +0000234
Evan Cheng61560e22011-09-01 01:45:00 +0000235 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
236 /// index, return the ID and cost of its representative register class by
237 /// reference.
238 void getRegisterClassIDAndCost(const MachineInstr *MI,
239 unsigned Reg, unsigned OpIdx,
240 unsigned &RCId, unsigned &RCCost) const;
241
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000242 /// InitRegPressure - Find all virtual register references that are liveout
243 /// of the preheader to initialize the starting "register pressure". Note
244 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000245 void InitRegPressure(MachineBasicBlock *BB);
246
Evan Cheng134982d2010-10-20 22:03:58 +0000247 /// UpdateRegPressure - Update estimate of register pressure after the
248 /// specified instruction.
249 void UpdateRegPressure(const MachineInstr *MI);
Evan Cheng0e673912010-10-14 01:16:09 +0000250
Dan Gohman5c952302009-10-29 17:47:20 +0000251 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
252 /// the load itself could be hoisted. Return the unfolded and hoistable
253 /// load, or null if the load couldn't be unfolded or if it wouldn't
254 /// be hoistable.
255 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
256
Evan Cheng78e5c112009-11-07 03:52:02 +0000257 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
258 /// duplicate of MI. Return this instruction if it's found.
259 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
260 std::vector<const MachineInstr*> &PrevMIs);
261
Evan Cheng9fb744e2009-11-05 00:51:13 +0000262 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
263 /// the preheader that compute the same value. If it's found, do a RAU on
264 /// with the definition of the existing instruction rather than hoisting
265 /// the instruction to the preheader.
266 bool EliminateCSE(MachineInstr *MI,
267 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
268
Evan Cheng7efba852011-10-12 00:09:14 +0000269 /// MayCSE - Return true if the given instruction will be CSE'd if it's
270 /// hoisted out of the loop.
271 bool MayCSE(MachineInstr *MI);
272
Bill Wendling0f940c92007-12-07 21:42:31 +0000273 /// Hoist - When an instruction is found to only use loop invariant operands
274 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000275 /// It returns true if the instruction is hoisted.
276 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000277
278 /// InitCSEMap - Initialize the CSE map with instructions that are in the
279 /// current loop preheader that may become duplicates of instructions that
280 /// are hoisted out of the loop.
281 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000282
283 /// getCurPreheader - Get the preheader for the current loop, splitting
284 /// a critical edge if needed.
285 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000286 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000287} // end anonymous namespace
288
Dan Gohman844731a2008-05-13 00:00:25 +0000289char MachineLICM::ID = 0;
Andrew Trick1dd8c852012-02-08 21:23:13 +0000290char &llvm::MachineLICMID = MachineLICM::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000291INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
292 "Machine Loop Invariant Code Motion", false, false)
293INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
294INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
295INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
296INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000297 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000298
Dan Gohman853d3fb2010-06-22 17:25:57 +0000299/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
300/// loop that has a unique predecessor.
301static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000302 // Check whether this loop even has a unique predecessor.
303 if (!CurLoop->getLoopPredecessor())
304 return false;
305 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000306 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000307 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000308 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000309 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000310 return true;
311}
312
Bill Wendling0f940c92007-12-07 21:42:31 +0000313bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000314 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000315 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000316 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000317 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000318 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000319 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000320 MRI = &MF.getRegInfo();
321 InstrItins = TM->getInstrItineraryData();
Bill Wendling0f940c92007-12-07 21:42:31 +0000322
Andrew Trick9d41bd52012-02-08 21:23:03 +0000323 PreRegAlloc = MRI->isSSA();
324
Jakob Stoklund Olesenfd3d4cf2012-02-11 00:40:36 +0000325 if (PreRegAlloc)
326 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
327 else
328 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
329 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
330
Evan Cheng0e673912010-10-14 01:16:09 +0000331 if (PreRegAlloc) {
332 // Estimate register pressure during pre-regalloc pass.
333 unsigned NumRC = TRI->getNumRegClasses();
334 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000335 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000336 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000337 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
338 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichbe2119e2011-03-07 21:56:36 +0000339 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Cheng0e673912010-10-14 01:16:09 +0000340 }
341
Bill Wendling0f940c92007-12-07 21:42:31 +0000342 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000343 MLI = &getAnalysis<MachineLoopInfo>();
344 DT = &getAnalysis<MachineDominatorTree>();
345 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000346
Dan Gohmanaa742602010-07-09 18:49:45 +0000347 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
348 while (!Worklist.empty()) {
349 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000350 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000351
Evan Cheng4038f9c2010-04-08 01:03:47 +0000352 // If this is done before regalloc, only visit outer-most preheader-sporting
353 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000354 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
355 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000356 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000357 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000358
Evan Chengd94671a2010-04-07 00:41:17 +0000359 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000360 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000361 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000362 // CSEMap is initialized for loop header when the first instruction is
363 // being hoisted.
364 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000365 FirstInLoop = true;
Pete Cooperacde91e2011-12-22 02:05:40 +0000366 HoistOutOfLoop(N);
Evan Chengd94671a2010-04-07 00:41:17 +0000367 CSEMap.clear();
368 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000369 }
370
371 return Changed;
372}
373
Evan Cheng4038f9c2010-04-08 01:03:47 +0000374/// InstructionStoresToFI - Return true if instruction stores to the
375/// specified frame.
376static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
377 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
378 oe = MI->memoperands_end(); o != oe; ++o) {
379 if (!(*o)->isStore() || !(*o)->getValue())
380 continue;
381 if (const FixedStackPseudoSourceValue *Value =
382 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
383 if (Value->getFrameIndex() == FI)
384 return true;
385 }
386 }
387 return false;
388}
389
390/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
391/// gather register def and frame object update information.
392void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000393 BitVector &PhysRegDefs,
394 BitVector &PhysRegClobbers,
Evan Cheng4038f9c2010-04-08 01:03:47 +0000395 SmallSet<int, 32> &StoredFIs,
396 SmallVector<CandidateInfo, 32> &Candidates) {
397 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000398 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000399 unsigned Def = 0;
400 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
401 const MachineOperand &MO = MI->getOperand(i);
402 if (MO.isFI()) {
403 // Remember if the instruction stores to the frame index.
404 int FI = MO.getIndex();
405 if (!StoredFIs.count(FI) &&
406 MFI->isSpillSlotObjectIndex(FI) &&
407 InstructionStoresToFI(MI, FI))
408 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000409 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000410 continue;
411 }
412
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000413 // We can't hoist an instruction defining a physreg that is clobbered in
414 // the loop.
415 if (MO.isRegMask()) {
Jakob Stoklund Olesen478a8a02012-02-02 23:52:57 +0000416 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000417 continue;
418 }
419
Evan Cheng4038f9c2010-04-08 01:03:47 +0000420 if (!MO.isReg())
421 continue;
422 unsigned Reg = MO.getReg();
423 if (!Reg)
424 continue;
425 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
426 "Not expecting virtual register!");
427
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000428 if (!MO.isDef()) {
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000429 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000430 // If it's using a non-loop-invariant register, then it's obviously not
431 // safe to hoist.
432 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000433 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000434 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000435
436 if (MO.isImplicit()) {
Craig Toppere4fd9072012-03-04 10:43:23 +0000437 for (const uint16_t *AS = TRI->getOverlaps(Reg); *AS; ++AS)
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000438 PhysRegClobbers.set(*AS);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000439 if (!MO.isDead())
440 // Non-dead implicit def? This cannot be hoisted.
441 RuledOut = true;
442 // No need to check if a dead implicit def is also defined by
443 // another instruction.
444 continue;
445 }
446
447 // FIXME: For now, avoid instructions with multiple defs, unless
448 // it's a dead implicit def.
449 if (Def)
450 RuledOut = true;
451 else
452 Def = Reg;
453
454 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000455 // register, then this is not safe. Two defs is indicated by setting a
456 // PhysRegClobbers bit.
Craig Toppere4fd9072012-03-04 10:43:23 +0000457 for (const uint16_t *AS = TRI->getOverlaps(Reg); *AS; ++AS) {
Jakob Stoklund Olesend0848a62012-01-23 21:01:15 +0000458 if (PhysRegDefs.test(*AS))
459 PhysRegClobbers.set(*AS);
460 if (PhysRegClobbers.test(*AS))
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000461 // MI defined register is seen defined by another instruction in
462 // the loop, it cannot be a LICM candidate.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000463 RuledOut = true;
Jakob Stoklund Olesend0848a62012-01-23 21:01:15 +0000464 PhysRegDefs.set(*AS);
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000465 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000466 }
467
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000468 // Only consider reloads for now and remats which do not have register
469 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000470 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000471 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000472 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000473 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
474 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000475 }
476}
477
478/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
479/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000480void MachineLICM::HoistRegionPostRA() {
Evan Chengd6c23552012-03-27 01:50:58 +0000481 MachineBasicBlock *Preheader = getCurPreheader();
482 if (!Preheader)
483 return;
484
Evan Chengd94671a2010-04-07 00:41:17 +0000485 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000486 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
487 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Chengd94671a2010-04-07 00:41:17 +0000488
Evan Cheng4038f9c2010-04-08 01:03:47 +0000489 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000490 SmallSet<int, 32> StoredFIs;
491
492 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000493 // collect potential LICM candidates.
494 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
495 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
496 MachineBasicBlock *BB = Blocks[i];
Bill Wendlinga2e87912011-10-12 02:58:01 +0000497
498 // If the header of the loop containing this basic block is a landing pad,
499 // then don't try to hoist instructions out of this loop.
500 const MachineLoop *ML = MLI->getLoopFor(BB);
501 if (ML && ML->getHeader()->isLandingPad()) continue;
502
Evan Chengd94671a2010-04-07 00:41:17 +0000503 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000504 // FIXME: That means a reload that're reused in successor block(s) will not
505 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000506 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000507 E = BB->livein_end(); I != E; ++I) {
508 unsigned Reg = *I;
Craig Toppere4fd9072012-03-04 10:43:23 +0000509 for (const uint16_t *AS = TRI->getOverlaps(Reg); *AS; ++AS)
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000510 PhysRegDefs.set(*AS);
Evan Chengd94671a2010-04-07 00:41:17 +0000511 }
512
Evan Chengfad62872011-10-11 23:48:44 +0000513 SpeculationState = SpeculateUnknown;
Evan Chengd94671a2010-04-07 00:41:17 +0000514 for (MachineBasicBlock::iterator
515 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000516 MachineInstr *MI = &*MII;
Jakob Stoklund Olesena3c4ca92012-01-20 22:27:12 +0000517 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000518 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000519 }
Evan Chengd94671a2010-04-07 00:41:17 +0000520
Evan Chengd6c23552012-03-27 01:50:58 +0000521 // Gather the registers read / clobbered by the terminator.
522 BitVector TermRegs(NumRegs);
523 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
524 if (TI != Preheader->end()) {
525 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
526 const MachineOperand &MO = TI->getOperand(i);
527 if (!MO.isReg())
528 continue;
529 unsigned Reg = MO.getReg();
530 if (!Reg)
531 continue;
532 for (const uint16_t *AS = TRI->getOverlaps(Reg); *AS; ++AS)
533 TermRegs.set(*AS);
534 }
535 }
536
Evan Chengd94671a2010-04-07 00:41:17 +0000537 // Now evaluate whether the potential candidates qualify.
538 // 1. Check if the candidate defined register is defined by another
539 // instruction in the loop.
540 // 2. If the candidate is a load from stack slot (always true for now),
541 // check if the slot is stored anywhere in the loop.
Evan Chengd6c23552012-03-27 01:50:58 +0000542 // 3. Make sure candidate def should not clobber
543 // registers read by the terminator. Similarly its def should not be
544 // clobbered by the terminator.
Evan Chengd94671a2010-04-07 00:41:17 +0000545 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000546 if (Candidates[i].FI != INT_MIN &&
547 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000548 continue;
549
Evan Chengd6c23552012-03-27 01:50:58 +0000550 unsigned Def = Candidates[i].Def;
551 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000552 bool Safe = true;
553 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000554 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
555 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000556 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000557 continue;
Evan Chengd6c23552012-03-27 01:50:58 +0000558 unsigned Reg = MO.getReg();
559 if (PhysRegDefs.test(Reg) ||
560 PhysRegClobbers.test(Reg)) {
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000561 // If it's using a non-loop-invariant register, then it's obviously
562 // not safe to hoist.
563 Safe = false;
564 break;
565 }
566 }
567 if (Safe)
568 HoistPostRA(MI, Candidates[i].Def);
569 }
Evan Chengd94671a2010-04-07 00:41:17 +0000570 }
571}
572
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000573/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
574/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000575void MachineLICM::AddToLiveIns(unsigned Reg) {
576 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000577 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
578 MachineBasicBlock *BB = Blocks[i];
579 if (!BB->isLiveIn(Reg))
580 BB->addLiveIn(Reg);
581 for (MachineBasicBlock::iterator
582 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
583 MachineInstr *MI = &*MII;
584 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
585 MachineOperand &MO = MI->getOperand(i);
586 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
587 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
588 MO.setIsKill(false);
589 }
590 }
591 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000592}
593
594/// HoistPostRA - When an instruction is found to only use loop invariant
595/// operands that is safe to hoist, this instruction is called to do the
596/// dirty work.
597void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000598 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000599
Evan Chengd94671a2010-04-07 00:41:17 +0000600 // Now move the instructions to the predecessor, inserting it before any
601 // terminator instructions.
Jakob Stoklund Olesen39f66602012-01-23 21:01:11 +0000602 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
603 << MI->getParent()->getNumber() << ": " << *MI);
Evan Chengd94671a2010-04-07 00:41:17 +0000604
605 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000606 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000607 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000608
Andrew Trick9f17cf62012-02-08 21:23:00 +0000609 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000610 // loop invariant must be kept live throughout the whole loop. This is
611 // important to ensure later passes do not scavenge the def register.
612 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000613
614 ++NumPostRAHoisted;
615 Changed = true;
616}
617
Devang Patel2e350472011-10-11 18:09:58 +0000618// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
619// If not then a load from this mbb may not be safe to hoist.
620bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengfad62872011-10-11 23:48:44 +0000621 if (SpeculationState != SpeculateUnknown)
622 return SpeculationState == SpeculateFalse;
Andrew Trick9f17cf62012-02-08 21:23:00 +0000623
Devang Patel2e350472011-10-11 18:09:58 +0000624 if (BB != CurLoop->getHeader()) {
625 // Check loop exiting blocks.
626 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
627 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
628 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
629 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Nick Lewyckyea3abd52011-10-13 01:09:50 +0000630 SpeculationState = SpeculateTrue;
631 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000632 }
633 }
634
Evan Chengfad62872011-10-11 23:48:44 +0000635 SpeculationState = SpeculateFalse;
636 return true;
Devang Patel2e350472011-10-11 18:09:58 +0000637}
638
Pete Cooperacde91e2011-12-22 02:05:40 +0000639void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
640 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Bill Wendling0f940c92007-12-07 21:42:31 +0000641
Pete Cooperacde91e2011-12-22 02:05:40 +0000642 // Remember livein register pressure.
643 BackTrace.push_back(RegPressure);
644}
Bill Wendlinga2e87912011-10-12 02:58:01 +0000645
Pete Cooperacde91e2011-12-22 02:05:40 +0000646void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
647 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
648 BackTrace.pop_back();
649}
Bill Wendling0f940c92007-12-07 21:42:31 +0000650
Pete Cooperacde91e2011-12-22 02:05:40 +0000651/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
652/// dominator tree node if its a leaf or all of its children are done. Walk
653/// up the dominator tree to destroy ancestors which are now done.
654void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Cheng75fda5d2012-01-10 22:27:32 +0000655 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
656 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooperacde91e2011-12-22 02:05:40 +0000657 if (OpenChildren[Node])
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000658 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000659
Pete Cooperacde91e2011-12-22 02:05:40 +0000660 // Pop scope.
661 ExitScope(Node->getBlock());
662
663 // Now traverse upwards to pop ancestors whose offsprings are all done.
664 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
665 unsigned Left = --OpenChildren[Parent];
666 if (Left != 0)
667 break;
668 ExitScope(Parent->getBlock());
669 Node = Parent;
670 }
671}
672
673/// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
674/// blocks dominated by the specified header block, and that are in the
675/// current loop) in depth first order w.r.t the DominatorTree. This allows
676/// us to visit definitions before uses, allowing us to hoist a loop body in
677/// one pass without iteration.
678///
679void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
680 SmallVector<MachineDomTreeNode*, 32> Scopes;
681 SmallVector<MachineDomTreeNode*, 8> WorkList;
682 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
683 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
684
685 // Perform a DFS walk to determine the order of visit.
686 WorkList.push_back(HeaderN);
687 do {
688 MachineDomTreeNode *Node = WorkList.pop_back_val();
689 assert(Node != 0 && "Null dominator tree node?");
690 MachineBasicBlock *BB = Node->getBlock();
691
692 // If the header of the loop containing this basic block is a landing pad,
693 // then don't try to hoist instructions out of this loop.
694 const MachineLoop *ML = MLI->getLoopFor(BB);
695 if (ML && ML->getHeader()->isLandingPad())
696 continue;
697
698 // If this subregion is not in the top level loop at all, exit.
699 if (!CurLoop->contains(BB))
700 continue;
701
702 Scopes.push_back(Node);
703 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
704 unsigned NumChildren = Children.size();
705
706 // Don't hoist things out of a large switch statement. This often causes
707 // code to be hoisted that wasn't going to be executed, and increases
708 // register pressure in a situation where it's likely to matter.
709 if (BB->succ_size() >= 25)
710 NumChildren = 0;
711
712 OpenChildren[Node] = NumChildren;
713 // Add children in reverse order as then the next popped worklist node is
714 // the first child of this node. This means we ultimately traverse the
715 // DOM tree in exactly the same order as if we'd recursed.
716 for (int i = (int)NumChildren-1; i >= 0; --i) {
717 MachineDomTreeNode *Child = Children[i];
718 ParentMap[Child] = Node;
719 WorkList.push_back(Child);
720 }
721 } while (!WorkList.empty());
722
723 if (Scopes.size() != 0) {
724 MachineBasicBlock *Preheader = getCurPreheader();
725 if (!Preheader)
726 return;
727
Evan Cheng134982d2010-10-20 22:03:58 +0000728 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000729 RegSeen.clear();
730 BackTrace.clear();
731 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000732 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000733
Pete Cooperacde91e2011-12-22 02:05:40 +0000734 // Now perform LICM.
735 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
736 MachineDomTreeNode *Node = Scopes[i];
737 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng23128422010-10-19 18:58:51 +0000738
Pete Cooperacde91e2011-12-22 02:05:40 +0000739 MachineBasicBlock *Preheader = getCurPreheader();
740 if (!Preheader)
741 continue;
742
743 EnterScope(MBB);
744
745 // Process the block
746 SpeculationState = SpeculateUnknown;
747 for (MachineBasicBlock::iterator
748 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
749 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
750 MachineInstr *MI = &*MII;
751 if (!Hoist(MI, Preheader))
752 UpdateRegPressure(MI);
753 MII = NextMII;
754 }
755
756 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
757 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohmanc475c362009-01-15 22:01:38 +0000758 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000759}
760
Evan Cheng134982d2010-10-20 22:03:58 +0000761static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
762 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
763}
764
Evan Cheng61560e22011-09-01 01:45:00 +0000765/// getRegisterClassIDAndCost - For a given MI, register, and the operand
766/// index, return the ID and cost of its representative register class.
767void
768MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
769 unsigned Reg, unsigned OpIdx,
770 unsigned &RCId, unsigned &RCCost) const {
771 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
772 EVT VT = *RC->vt_begin();
Owen Anderson99aa14f2011-11-16 01:02:57 +0000773 if (VT == MVT::Untyped) {
Evan Cheng61560e22011-09-01 01:45:00 +0000774 RCId = RC->getID();
775 RCCost = 1;
776 } else {
777 RCId = TLI->getRepRegClassFor(VT)->getID();
778 RCCost = TLI->getRepRegClassCostFor(VT);
779 }
780}
Andrew Trick9f17cf62012-02-08 21:23:00 +0000781
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000782/// InitRegPressure - Find all virtual register references that are liveout of
783/// the preheader to initialize the starting "register pressure". Note this
784/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000785void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000786 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000787
Evan Cheng134982d2010-10-20 22:03:58 +0000788 // If the preheader has only a single predecessor and it ends with a
789 // fallthrough or an unconditional branch, then scan its predecessor for live
790 // defs as well. This happens whenever the preheader is created by splitting
791 // the critical edge from the loop predecessor to the loop header.
792 if (BB->pred_size() == 1) {
793 MachineBasicBlock *TBB = 0, *FBB = 0;
794 SmallVector<MachineOperand, 4> Cond;
795 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
796 InitRegPressure(*BB->pred_begin());
797 }
798
Evan Cheng0e673912010-10-14 01:16:09 +0000799 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
800 MII != E; ++MII) {
801 MachineInstr *MI = &*MII;
802 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
803 const MachineOperand &MO = MI->getOperand(i);
804 if (!MO.isReg() || MO.isImplicit())
805 continue;
806 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000807 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000808 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000809
Andrew Trickdc986d22010-10-19 02:50:50 +0000810 bool isNew = RegSeen.insert(Reg);
Evan Cheng61560e22011-09-01 01:45:00 +0000811 unsigned RCId, RCCost;
812 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000813 if (MO.isDef())
Evan Cheng61560e22011-09-01 01:45:00 +0000814 RegPressure[RCId] += RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000815 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000816 bool isKill = isOperandKill(MO, MRI);
817 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000818 // Haven't seen this, it must be a livein.
Evan Cheng61560e22011-09-01 01:45:00 +0000819 RegPressure[RCId] += RCCost;
Evan Cheng134982d2010-10-20 22:03:58 +0000820 else if (!isNew && isKill)
Evan Cheng61560e22011-09-01 01:45:00 +0000821 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000822 }
Evan Cheng0e673912010-10-14 01:16:09 +0000823 }
824 }
825}
826
Evan Cheng134982d2010-10-20 22:03:58 +0000827/// UpdateRegPressure - Update estimate of register pressure after the
828/// specified instruction.
829void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
830 if (MI->isImplicitDef())
831 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000832
Evan Cheng134982d2010-10-20 22:03:58 +0000833 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000834 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
835 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000836 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000837 continue;
838 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000839 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000840 continue;
841
Andrew Trickdc986d22010-10-19 02:50:50 +0000842 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000843 if (MO.isDef())
844 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000845 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng61560e22011-09-01 01:45:00 +0000846 unsigned RCId, RCCost;
847 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000848 if (RCCost > RegPressure[RCId])
849 RegPressure[RCId] = 0;
850 else
Evan Cheng23128422010-10-19 18:58:51 +0000851 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000852 }
Evan Cheng0e673912010-10-14 01:16:09 +0000853 }
Evan Cheng0e673912010-10-14 01:16:09 +0000854
Evan Cheng61560e22011-09-01 01:45:00 +0000855 unsigned Idx = 0;
Evan Cheng23128422010-10-19 18:58:51 +0000856 while (!Defs.empty()) {
857 unsigned Reg = Defs.pop_back_val();
Evan Cheng61560e22011-09-01 01:45:00 +0000858 unsigned RCId, RCCost;
859 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Cheng0e673912010-10-14 01:16:09 +0000860 RegPressure[RCId] += RCCost;
Evan Cheng61560e22011-09-01 01:45:00 +0000861 ++Idx;
Evan Cheng0e673912010-10-14 01:16:09 +0000862 }
863}
864
Andrew Trick9f17cf62012-02-08 21:23:00 +0000865/// isLoadFromGOTOrConstantPool - Return true if this machine instruction
Devang Patel06e16bb2011-10-20 17:42:23 +0000866/// loads from global offset table or constant pool.
867static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000868 assert (MI.mayLoad() && "Expected MI that loads!");
Devang Patel6c15fec2011-10-17 17:35:01 +0000869 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
Andrew Trick9f17cf62012-02-08 21:23:00 +0000870 E = MI.memoperands_end(); I != E; ++I) {
Devang Patel6c15fec2011-10-17 17:35:01 +0000871 if (const Value *V = (*I)->getValue()) {
872 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
Devang Patel06e16bb2011-10-20 17:42:23 +0000873 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
Andrew Trick9f17cf62012-02-08 21:23:00 +0000874 return true;
Devang Patel6c15fec2011-10-17 17:35:01 +0000875 }
876 }
877 return false;
878}
879
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000880/// IsLICMCandidate - Returns true if the instruction may be a suitable
881/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
882/// not safe to hoist it.
883bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000884 // Check if it's safe to move the instruction.
885 bool DontMoveAcrossStore = true;
886 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000887 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000888
889 // If it is load then check if it is guaranteed to execute by making sure that
890 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patele6de9f32011-10-20 17:31:18 +0000891 // the loop which does not execute this load, so we can't hoist it. Loads
892 // from constant memory are not safe to speculate all the time, for example
893 // indexed load from a jump table.
Devang Patel2e350472011-10-11 18:09:58 +0000894 // Stores and side effects are already checked by isSafeToMove.
Andrew Trick9f17cf62012-02-08 21:23:00 +0000895 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
Devang Patel6c15fec2011-10-17 17:35:01 +0000896 !IsGuaranteedToExecute(I.getParent()))
Devang Patel2e350472011-10-11 18:09:58 +0000897 return false;
898
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000899 return true;
900}
901
902/// IsLoopInvariantInst - Returns true if the instruction is loop
903/// invariant. I.e., all virtual register operands are defined outside of the
904/// loop, physical registers aren't accessed explicitly, and there are no side
905/// effects that aren't captured by the operands or other flags.
Andrew Trick9f17cf62012-02-08 21:23:00 +0000906///
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000907bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
908 if (!IsLICMCandidate(I))
909 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000910
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000911 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000912 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
913 const MachineOperand &MO = I.getOperand(i);
914
Dan Gohmand735b802008-10-03 15:45:36 +0000915 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000916 continue;
917
Dan Gohmanc475c362009-01-15 22:01:38 +0000918 unsigned Reg = MO.getReg();
919 if (Reg == 0) continue;
920
921 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000922 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000923 if (MO.isUse()) {
924 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000925 // and we can freely move its uses. Alternatively, if it's allocatable,
926 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesenc035c942012-01-16 22:34:08 +0000927 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000928 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000929 // Otherwise it's safe to move.
930 continue;
931 } else if (!MO.isDead()) {
932 // A def that isn't dead. We can't move it.
933 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000934 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
935 // If the reg is live into the loop, we can't hoist an instruction
936 // which would clobber it.
937 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000938 }
939 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000940
941 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000942 continue;
943
Evan Cheng0e673912010-10-14 01:16:09 +0000944 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000945 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000946
947 // If the loop contains the definition of an operand, then the instruction
948 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000949 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000950 return false;
951 }
952
953 // If we got this far, the instruction is loop invariant!
954 return true;
955}
956
Evan Chengaf6949d2009-02-05 08:45:46 +0000957
Evan Chengd67705f2011-04-11 21:09:18 +0000958/// HasAnyPHIUse - Return true if the specified register is used by any
959/// phi node.
960bool MachineLICM::HasAnyPHIUse(unsigned Reg) const {
Evan Cheng0e673912010-10-14 01:16:09 +0000961 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
962 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000963 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000964 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000965 return true;
Evan Chengd67705f2011-04-11 21:09:18 +0000966 // Look pass copies as well.
967 if (UseMI->isCopy()) {
968 unsigned Def = UseMI->getOperand(0).getReg();
969 if (TargetRegisterInfo::isVirtualRegister(Def) &&
970 HasAnyPHIUse(Def))
971 return true;
972 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000973 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000974 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000975}
976
Evan Cheng23128422010-10-19 18:58:51 +0000977/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
978/// and an use in the current loop, return true if the target considered
979/// it 'high'.
980bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +0000981 unsigned DefIdx, unsigned Reg) const {
982 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000983 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000984
Evan Cheng0e673912010-10-14 01:16:09 +0000985 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
986 E = MRI->use_nodbg_end(); I != E; ++I) {
987 MachineInstr *UseMI = &*I;
Evan Chengc8141df2010-10-26 02:08:50 +0000988 if (UseMI->isCopyLike())
989 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000990 if (!CurLoop->contains(UseMI->getParent()))
991 continue;
992 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
993 const MachineOperand &MO = UseMI->getOperand(i);
994 if (!MO.isReg() || !MO.isUse())
995 continue;
996 unsigned MOReg = MO.getReg();
997 if (MOReg != Reg)
998 continue;
999
Evan Cheng23128422010-10-19 18:58:51 +00001000 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
1001 return true;
Evan Cheng0e673912010-10-14 01:16:09 +00001002 }
1003
Evan Cheng23128422010-10-19 18:58:51 +00001004 // Only look at the first in loop use.
1005 break;
Evan Cheng0e673912010-10-14 01:16:09 +00001006 }
1007
Evan Cheng23128422010-10-19 18:58:51 +00001008 return false;
Evan Cheng0e673912010-10-14 01:16:09 +00001009}
1010
Evan Chengc8141df2010-10-26 02:08:50 +00001011/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1012/// the operand latency between its def and a use is one or less.
1013bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001014 if (MI.isAsCheapAsAMove() || MI.isCopyLike())
Evan Chengc8141df2010-10-26 02:08:50 +00001015 return true;
1016 if (!InstrItins || InstrItins->isEmpty())
1017 return false;
1018
1019 bool isCheap = false;
1020 unsigned NumDefs = MI.getDesc().getNumDefs();
1021 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1022 MachineOperand &DefMO = MI.getOperand(i);
1023 if (!DefMO.isReg() || !DefMO.isDef())
1024 continue;
1025 --NumDefs;
1026 unsigned Reg = DefMO.getReg();
1027 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1028 continue;
1029
1030 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1031 return false;
1032 isCheap = true;
1033 }
1034
1035 return isCheap;
1036}
1037
Evan Cheng134982d2010-10-20 22:03:58 +00001038/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001039/// if hoisting an instruction of the given cost matrix can cause high
1040/// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +00001041bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
1042 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1043 CI != CE; ++CI) {
Andrew Trick9f17cf62012-02-08 21:23:00 +00001044 if (CI->second <= 0)
Evan Cheng134982d2010-10-20 22:03:58 +00001045 continue;
1046
1047 unsigned RCId = CI->first;
Pete Cooper3cfecf52011-12-22 02:13:25 +00001048 unsigned Limit = RegLimit[RCId];
1049 int Cost = CI->second;
Evan Cheng134982d2010-10-20 22:03:58 +00001050 for (unsigned i = BackTrace.size(); i != 0; --i) {
1051 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Pete Cooper3cfecf52011-12-22 02:13:25 +00001052 if (RP[RCId] + Cost >= Limit)
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001053 return true;
1054 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001055 }
1056
1057 return false;
1058}
1059
Evan Cheng134982d2010-10-20 22:03:58 +00001060/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1061/// current block and update their register pressures to reflect the effect
1062/// of hoisting MI from the current block to the preheader.
1063void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1064 if (MI->isImplicitDef())
1065 return;
1066
1067 // First compute the 'cost' of the instruction, i.e. its contribution
1068 // to register pressure.
1069 DenseMap<unsigned, int> Cost;
1070 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1071 const MachineOperand &MO = MI->getOperand(i);
1072 if (!MO.isReg() || MO.isImplicit())
1073 continue;
1074 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +00001075 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng134982d2010-10-20 22:03:58 +00001076 continue;
1077
Evan Cheng61560e22011-09-01 01:45:00 +00001078 unsigned RCId, RCCost;
1079 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +00001080 if (MO.isDef()) {
1081 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1082 if (CI != Cost.end())
1083 CI->second += RCCost;
1084 else
1085 Cost.insert(std::make_pair(RCId, RCCost));
1086 } else if (isOperandKill(MO, MRI)) {
1087 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1088 if (CI != Cost.end())
1089 CI->second -= RCCost;
1090 else
1091 Cost.insert(std::make_pair(RCId, -RCCost));
1092 }
1093 }
1094
1095 // Update register pressure of blocks from loop header to current block.
1096 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
1097 SmallVector<unsigned, 8> &RP = BackTrace[i];
1098 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1099 CI != CE; ++CI) {
1100 unsigned RCId = CI->first;
1101 RP[RCId] += CI->second;
1102 }
1103 }
1104}
1105
Evan Cheng45e94d62009-02-04 09:19:56 +00001106/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1107/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +00001108bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +00001109 if (MI.isImplicitDef())
1110 return true;
1111
Evan Cheng23128422010-10-19 18:58:51 +00001112 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
1113 // will increase register pressure. It's probably not worth it if the
1114 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +00001115 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
1116 // these tend to help performance in low register pressure situation. The
1117 // trade off is it may cause spill in high pressure situation. It will end up
1118 // adding a store in the loop preheader. But the reload is no more expensive.
1119 // The side benefit is these loads are frequently CSE'ed.
Evan Chengc8141df2010-10-26 02:08:50 +00001120 if (IsCheapInstruction(MI)) {
Evan Cheng23128422010-10-19 18:58:51 +00001121 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +00001122 return false;
1123 } else {
Evan Cheng23128422010-10-19 18:58:51 +00001124 // Estimate register pressure to determine whether to LICM the instruction.
Andrew Trick9f17cf62012-02-08 21:23:00 +00001125 // In low register pressure situation, we can be more aggressive about
Evan Cheng0e673912010-10-14 01:16:09 +00001126 // hoisting. Also, favors hoisting long latency instructions even in
1127 // moderately high pressure situation.
Dan Gohmanfca0b102010-11-11 18:08:43 +00001128 // FIXME: If there are long latency loop-invariant instructions inside the
1129 // loop at this point, why didn't the optimizer's LICM hoist them?
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001130 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +00001131 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1132 const MachineOperand &MO = MI.getOperand(i);
1133 if (!MO.isReg() || MO.isImplicit())
1134 continue;
1135 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +00001136 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +00001137 continue;
Evan Cheng61560e22011-09-01 01:45:00 +00001138
1139 unsigned RCId, RCCost;
1140 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001141 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +00001142 if (HasHighOperandLatency(MI, i, Reg)) {
1143 ++NumHighLatency;
1144 return true;
Evan Cheng0e673912010-10-14 01:16:09 +00001145 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001146
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001147 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001148 if (CI != Cost.end())
1149 CI->second += RCCost;
1150 else
1151 Cost.insert(std::make_pair(RCId, RCCost));
Evan Cheng134982d2010-10-20 22:03:58 +00001152 } else if (isOperandKill(MO, MRI)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001153 // Is a virtual register use is a kill, hoisting it out of the loop
1154 // may actually reduce register pressure or be register pressure
Evan Cheng134982d2010-10-20 22:03:58 +00001155 // neutral.
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001156 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1157 if (CI != Cost.end())
1158 CI->second -= RCCost;
1159 else
1160 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +00001161 }
1162 }
1163
Evan Cheng134982d2010-10-20 22:03:58 +00001164 // Visit BBs from header to current BB, if hoisting this doesn't cause
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001165 // high register pressure, then it's safe to proceed.
Evan Cheng134982d2010-10-20 22:03:58 +00001166 if (!CanCauseHighRegPressure(Cost)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001167 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +00001168 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001169 }
Evan Cheng0e673912010-10-14 01:16:09 +00001170
Evan Cheng7007e4c2011-10-12 21:33:49 +00001171 // Do not "speculate" in high register pressure situation. If an
Evan Chengfad62872011-10-11 23:48:44 +00001172 // instruction is not guaranteed to be executed in the loop, it's best to be
1173 // conservative.
Evan Cheng7007e4c2011-10-12 21:33:49 +00001174 if (AvoidSpeculation &&
1175 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI)))
1176 return false;
1177
Chad Rosier921c9bd2012-02-28 00:23:01 +00001178 // High register pressure situation, only hoist if the instruction is going
1179 // to be remat'ed.
Evan Cheng7007e4c2011-10-12 21:33:49 +00001180 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1181 !MI.isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001182 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001183 }
Evan Cheng45e94d62009-02-04 09:19:56 +00001184
Evan Chengd67705f2011-04-11 21:09:18 +00001185 // If result(s) of this instruction is used by PHIs outside of the loop, then
1186 // don't hoist it if the instruction because it will introduce an extra copy.
Evan Cheng45e94d62009-02-04 09:19:56 +00001187 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1188 const MachineOperand &MO = MI.getOperand(i);
1189 if (!MO.isReg() || !MO.isDef())
1190 continue;
Evan Chengd67705f2011-04-11 21:09:18 +00001191 if (HasAnyPHIUse(MO.getReg()))
Evan Chengaf6949d2009-02-05 08:45:46 +00001192 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +00001193 }
Evan Chengaf6949d2009-02-05 08:45:46 +00001194
1195 return true;
1196}
1197
Dan Gohman5c952302009-10-29 17:47:20 +00001198MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001199 // Don't unfold simple loads.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001200 if (MI->canFoldAsLoad())
Evan Chenge95f3192010-10-08 18:59:19 +00001201 return 0;
1202
Dan Gohman5c952302009-10-29 17:47:20 +00001203 // If not, we may be able to unfold a load and hoist that.
1204 // First test whether the instruction is loading from an amenable
1205 // memory location.
Evan Cheng9fe20092011-01-20 08:34:58 +00001206 if (!MI->isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001207 return 0;
1208
Dan Gohman5c952302009-10-29 17:47:20 +00001209 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001210 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001211 unsigned NewOpc =
1212 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1213 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001214 /*UnfoldStore=*/false,
1215 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001216 if (NewOpc == 0) return 0;
Evan Chenge837dea2011-06-28 19:10:37 +00001217 const MCInstrDesc &MID = TII->get(NewOpc);
1218 if (MID.getNumDefs() != 1) return 0;
1219 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001220 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001221 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001222
1223 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001224 SmallVector<MachineInstr *, 2> NewMIs;
1225 bool Success =
1226 TII->unfoldMemoryOperand(MF, MI, Reg,
1227 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1228 NewMIs);
1229 (void)Success;
1230 assert(Success &&
1231 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1232 "succeeded!");
1233 assert(NewMIs.size() == 2 &&
1234 "Unfolded a load into multiple instructions!");
1235 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng7c2a4a32011-12-06 22:12:01 +00001236 MachineBasicBlock::iterator Pos = MI;
1237 MBB->insert(Pos, NewMIs[0]);
1238 MBB->insert(Pos, NewMIs[1]);
Dan Gohman5c952302009-10-29 17:47:20 +00001239 // If unfolding produced a load that wasn't loop-invariant or profitable to
1240 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001241 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001242 NewMIs[0]->eraseFromParent();
1243 NewMIs[1]->eraseFromParent();
1244 return 0;
1245 }
Evan Cheng134982d2010-10-20 22:03:58 +00001246
1247 // Update register pressure for the unfolded instruction.
1248 UpdateRegPressure(NewMIs[1]);
1249
Dan Gohman5c952302009-10-29 17:47:20 +00001250 // Otherwise we successfully unfolded a load that we can hoist.
1251 MI->eraseFromParent();
1252 return NewMIs[0];
1253}
1254
Evan Cheng777c6b72009-11-03 21:40:02 +00001255void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1256 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1257 const MachineInstr *MI = &*I;
Evan Cheng9fe20092011-01-20 08:34:58 +00001258 unsigned Opcode = MI->getOpcode();
1259 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1260 CI = CSEMap.find(Opcode);
1261 if (CI != CSEMap.end())
1262 CI->second.push_back(MI);
1263 else {
1264 std::vector<const MachineInstr*> CSEMIs;
1265 CSEMIs.push_back(MI);
1266 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Cheng777c6b72009-11-03 21:40:02 +00001267 }
1268 }
1269}
1270
Evan Cheng78e5c112009-11-07 03:52:02 +00001271const MachineInstr*
1272MachineLICM::LookForDuplicate(const MachineInstr *MI,
1273 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001274 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1275 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng9fe20092011-01-20 08:34:58 +00001276 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001277 return PrevMI;
1278 }
1279 return 0;
1280}
1281
1282bool MachineLICM::EliminateCSE(MachineInstr *MI,
1283 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001284 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1285 // the undef property onto uses.
1286 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001287 return false;
1288
1289 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001290 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001291
1292 // Replace virtual registers defined by MI by their counterparts defined
1293 // by Dup.
Evan Cheng1025cce2011-10-17 19:50:12 +00001294 SmallVector<unsigned, 2> Defs;
Evan Cheng78e5c112009-11-07 03:52:02 +00001295 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1296 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001297
1298 // Physical registers may not differ here.
1299 assert((!MO.isReg() || MO.getReg() == 0 ||
1300 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1301 MO.getReg() == Dup->getOperand(i).getReg()) &&
1302 "Instructions with different phys regs are not identical!");
1303
1304 if (MO.isReg() && MO.isDef() &&
Evan Cheng1025cce2011-10-17 19:50:12 +00001305 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1306 Defs.push_back(i);
1307 }
1308
1309 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1310 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1311 unsigned Idx = Defs[i];
1312 unsigned Reg = MI->getOperand(Idx).getReg();
1313 unsigned DupReg = Dup->getOperand(Idx).getReg();
1314 OrigRCs.push_back(MRI->getRegClass(DupReg));
1315
1316 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1317 // Restore old RCs if more than one defs.
1318 for (unsigned j = 0; j != i; ++j)
1319 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1320 return false;
Dan Gohmane6cd7572010-05-13 20:34:42 +00001321 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001322 }
Evan Cheng1025cce2011-10-17 19:50:12 +00001323
1324 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1325 unsigned Idx = Defs[i];
1326 unsigned Reg = MI->getOperand(Idx).getReg();
1327 unsigned DupReg = Dup->getOperand(Idx).getReg();
1328 MRI->replaceRegWith(Reg, DupReg);
1329 MRI->clearKillFlags(DupReg);
1330 }
1331
Evan Cheng78e5c112009-11-07 03:52:02 +00001332 MI->eraseFromParent();
1333 ++NumCSEed;
1334 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001335 }
1336 return false;
1337}
1338
Evan Cheng7efba852011-10-12 00:09:14 +00001339/// MayCSE - Return true if the given instruction will be CSE'd if it's
1340/// hoisted out of the loop.
1341bool MachineLICM::MayCSE(MachineInstr *MI) {
1342 unsigned Opcode = MI->getOpcode();
1343 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1344 CI = CSEMap.find(Opcode);
1345 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1346 // the undef property onto uses.
1347 if (CI == CSEMap.end() || MI->isImplicitDef())
1348 return false;
1349
1350 return LookForDuplicate(MI, CI->second) != 0;
1351}
1352
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001353/// Hoist - When an instruction is found to use only loop invariant operands
1354/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001355///
Evan Cheng134982d2010-10-20 22:03:58 +00001356bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001357 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001358 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001359 // If not, try unfolding a hoistable load.
1360 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001361 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001362 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001363
Dan Gohmanc475c362009-01-15 22:01:38 +00001364 // Now move the instructions to the predecessor, inserting it before any
1365 // terminator instructions.
1366 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001367 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001368 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001369 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001370 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001371 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001372 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001373 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001374 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001375 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001376
Evan Cheng777c6b72009-11-03 21:40:02 +00001377 // If this is the first instruction being hoisted to the preheader,
1378 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001379 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001380 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001381 FirstInLoop = false;
1382 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001383
Evan Chengaf6949d2009-02-05 08:45:46 +00001384 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001385 unsigned Opcode = MI->getOpcode();
1386 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1387 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001388 if (!EliminateCSE(MI, CI)) {
1389 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001390 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001391
Evan Cheng134982d2010-10-20 22:03:58 +00001392 // Update register pressure for BBs from header to this block.
1393 UpdateBackTraceRegPressure(MI);
1394
Dan Gohmane6cd7572010-05-13 20:34:42 +00001395 // Clear the kill flags of any register this instruction defines,
1396 // since they may need to be live throughout the entire loop
1397 // rather than just live for part of it.
1398 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1399 MachineOperand &MO = MI->getOperand(i);
1400 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001401 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001402 }
1403
Evan Chengaf6949d2009-02-05 08:45:46 +00001404 // Add to the CSE map.
1405 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001406 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001407 else {
1408 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001409 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001410 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001411 }
1412 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001413
Dan Gohmanc475c362009-01-15 22:01:38 +00001414 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001415 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001416
1417 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001418}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001419
1420MachineBasicBlock *MachineLICM::getCurPreheader() {
1421 // Determine the block to which to hoist instructions. If we can't find a
1422 // suitable loop predecessor, we can't do any hoisting.
1423
1424 // If we've tried to get a preheader and failed, don't try again.
1425 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1426 return 0;
1427
1428 if (!CurPreheader) {
1429 CurPreheader = CurLoop->getLoopPreheader();
1430 if (!CurPreheader) {
1431 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1432 if (!Pred) {
1433 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1434 return 0;
1435 }
1436
1437 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1438 if (!CurPreheader) {
1439 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1440 return 0;
1441 }
1442 }
1443 }
1444 return CurPreheader;
1445}