blob: 77ea4f37f8580451b61cfec18f433e11f55240a7 [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 {
Evan Chengd94671a2010-04-07 00:41:17 +000063 bool PreRegAlloc;
64
Bill Wendling9258cd32008-01-02 19:32:43 +000065 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000066 const TargetInstrInfo *TII;
Evan Cheng0e673912010-10-14 01:16:09 +000067 const TargetLowering *TLI;
Dan Gohmana8fb3362009-09-25 23:58:45 +000068 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000069 const MachineFrameInfo *MFI;
Evan Cheng0e673912010-10-14 01:16:09 +000070 MachineRegisterInfo *MRI;
71 const InstrItineraryData *InstrItins;
Bill Wendling12ebf142007-12-11 19:40:06 +000072
Bill Wendling0f940c92007-12-07 21:42:31 +000073 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000074 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +000075 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000076 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000077
Bill Wendling0f940c92007-12-07 21:42:31 +000078 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000079 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +000080 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000081 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000082 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000083
Evan Cheng0e673912010-10-14 01:16:09 +000084 // Track 'estimated' register pressure.
Evan Cheng03a9fdf2010-10-16 02:20:26 +000085 SmallSet<unsigned, 32> RegSeen;
Evan Cheng0e673912010-10-14 01:16:09 +000086 SmallVector<unsigned, 8> RegPressure;
Evan Cheng03a9fdf2010-10-16 02:20:26 +000087
88 // Register pressure "limit" per register class. If the pressure
89 // is higher than the limit, then it's considered high.
Evan Cheng0e673912010-10-14 01:16:09 +000090 SmallVector<unsigned, 8> RegLimit;
91
Evan Cheng03a9fdf2010-10-16 02:20:26 +000092 // Register pressure on path leading from loop preheader to current BB.
93 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
94
Dale Johannesenc46a5f22010-07-29 17:45:24 +000095 // For each opcode, keep a list of potential CSE instructions.
Evan Cheng777c6b72009-11-03 21:40:02 +000096 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000097
Evan Chengfad62872011-10-11 23:48:44 +000098 enum {
99 SpeculateFalse = 0,
100 SpeculateTrue = 1,
101 SpeculateUnknown = 2
102 };
103
Devang Patel2e350472011-10-11 18:09:58 +0000104 // If a MBB does not dominate loop exiting blocks then it may not safe
105 // to hoist loads from this block.
Evan Chengfad62872011-10-11 23:48:44 +0000106 // Tri-state: 0 - false, 1 - true, 2 - unknown
107 unsigned SpeculationState;
Devang Patel2e350472011-10-11 18:09:58 +0000108
Bill Wendling0f940c92007-12-07 21:42:31 +0000109 public:
110 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +0000111 MachineLICM() :
Owen Anderson081c34b2010-10-19 17:21:58 +0000112 MachineFunctionPass(ID), PreRegAlloc(true) {
113 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
114 }
Evan Chengd94671a2010-04-07 00:41:17 +0000115
116 explicit MachineLICM(bool PreRA) :
Owen Anderson081c34b2010-10-19 17:21:58 +0000117 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
118 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
119 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000120
121 virtual bool runOnMachineFunction(MachineFunction &MF);
122
Dan Gohman72241702008-12-18 01:37:56 +0000123 const char *getPassName() const { return "Machine Instruction LICM"; }
124
Bill Wendling0f940c92007-12-07 21:42:31 +0000125 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Bill Wendling0f940c92007-12-07 21:42:31 +0000126 AU.addRequired<MachineLoopInfo>();
127 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000128 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000129 AU.addPreserved<MachineLoopInfo>();
130 AU.addPreserved<MachineDominatorTree>();
131 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000132 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000133
134 virtual void releaseMemory() {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000135 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000136 RegPressure.clear();
137 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000138 BackTrace.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000139 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
140 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
141 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000142 CSEMap.clear();
143 }
144
Bill Wendling0f940c92007-12-07 21:42:31 +0000145 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000146 /// CandidateInfo - Keep track of information about hoisting candidates.
147 struct CandidateInfo {
148 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000149 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000150 int FI;
151 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
152 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000153 };
154
155 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
156 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000157 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000158
159 /// HoistPostRA - When an instruction is found to only use loop invariant
160 /// operands that is safe to hoist, this instruction is called to do the
161 /// dirty work.
162 void HoistPostRA(MachineInstr *MI, unsigned Def);
163
164 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
165 /// gather register def and frame object update information.
166 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
167 SmallSet<int, 32> &StoredFIs,
168 SmallVector<CandidateInfo, 32> &Candidates);
169
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000170 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
171 /// current loop.
172 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000173
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000174 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000175 /// candidate for LICM. e.g. If the instruction is a call, then it's
176 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000177 bool IsLICMCandidate(MachineInstr &I);
178
Bill Wendling041b3f82007-12-08 23:58:46 +0000179 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000180 /// invariant. I.e., all virtual register operands are defined outside of
181 /// the loop, physical registers aren't accessed (explicitly or implicitly),
182 /// and the instruction is hoistable.
183 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000184 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000185
Evan Chengd67705f2011-04-11 21:09:18 +0000186 /// HasAnyPHIUse - Return true if the specified register is used by any
187 /// phi node.
188 bool HasAnyPHIUse(unsigned Reg) const;
189
Evan Cheng23128422010-10-19 18:58:51 +0000190 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
191 /// and an use in the current loop, return true if the target considered
192 /// it 'high'.
Evan Chengc8141df2010-10-26 02:08:50 +0000193 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
194 unsigned Reg) const;
195
196 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Cheng0e673912010-10-14 01:16:09 +0000197
Evan Cheng134982d2010-10-20 22:03:58 +0000198 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
199 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000200 /// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000201 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
202
203 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
204 /// the current block and update their register pressures to reflect the
205 /// effect of hoisting MI from the current block to the preheader.
206 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000207
Evan Cheng45e94d62009-02-04 09:19:56 +0000208 /// IsProfitableToHoist - Return true if it is potentially profitable to
209 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000210 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000211
Devang Patel2e350472011-10-11 18:09:58 +0000212 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
213 /// If not then a load from this mbb may not be safe to hoist.
214 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
215
Pete Cooperacde91e2011-12-22 02:05:40 +0000216 void EnterScope(MachineBasicBlock *MBB);
217
218 void ExitScope(MachineBasicBlock *MBB);
219
220 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
221 /// dominator tree node if its a leaf or all of its children are done. Walk
222 /// up the dominator tree to destroy ancestors which are now done.
223 void ExitScopeIfDone(MachineDomTreeNode *Node,
224 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
225 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
226
227 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
228 /// blocks dominated by the specified header block, and that are in the
229 /// current loop) in depth first order w.r.t the DominatorTree. This allows
230 /// us to visit definitions before uses, allowing us to hoist a loop body in
231 /// one pass without iteration.
Bill Wendling0f940c92007-12-07 21:42:31 +0000232 ///
Pete Cooperacde91e2011-12-22 02:05:40 +0000233 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
234 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendling0f940c92007-12-07 21:42:31 +0000235
Evan Cheng61560e22011-09-01 01:45:00 +0000236 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
237 /// index, return the ID and cost of its representative register class by
238 /// reference.
239 void getRegisterClassIDAndCost(const MachineInstr *MI,
240 unsigned Reg, unsigned OpIdx,
241 unsigned &RCId, unsigned &RCCost) const;
242
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000243 /// InitRegPressure - Find all virtual register references that are liveout
244 /// of the preheader to initialize the starting "register pressure". Note
245 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000246 void InitRegPressure(MachineBasicBlock *BB);
247
Evan Cheng134982d2010-10-20 22:03:58 +0000248 /// UpdateRegPressure - Update estimate of register pressure after the
249 /// specified instruction.
250 void UpdateRegPressure(const MachineInstr *MI);
Evan Cheng0e673912010-10-14 01:16:09 +0000251
Dan Gohman5c952302009-10-29 17:47:20 +0000252 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
253 /// the load itself could be hoisted. Return the unfolded and hoistable
254 /// load, or null if the load couldn't be unfolded or if it wouldn't
255 /// be hoistable.
256 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
257
Evan Cheng78e5c112009-11-07 03:52:02 +0000258 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
259 /// duplicate of MI. Return this instruction if it's found.
260 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
261 std::vector<const MachineInstr*> &PrevMIs);
262
Evan Cheng9fb744e2009-11-05 00:51:13 +0000263 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
264 /// the preheader that compute the same value. If it's found, do a RAU on
265 /// with the definition of the existing instruction rather than hoisting
266 /// the instruction to the preheader.
267 bool EliminateCSE(MachineInstr *MI,
268 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
269
Evan Cheng7efba852011-10-12 00:09:14 +0000270 /// MayCSE - Return true if the given instruction will be CSE'd if it's
271 /// hoisted out of the loop.
272 bool MayCSE(MachineInstr *MI);
273
Bill Wendling0f940c92007-12-07 21:42:31 +0000274 /// Hoist - When an instruction is found to only use loop invariant operands
275 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000276 /// It returns true if the instruction is hoisted.
277 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000278
279 /// InitCSEMap - Initialize the CSE map with instructions that are in the
280 /// current loop preheader that may become duplicates of instructions that
281 /// are hoisted out of the loop.
282 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000283
284 /// getCurPreheader - Get the preheader for the current loop, splitting
285 /// a critical edge if needed.
286 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000287 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000288} // end anonymous namespace
289
Dan Gohman844731a2008-05-13 00:00:25 +0000290char MachineLICM::ID = 0;
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
Evan Chengd94671a2010-04-07 00:41:17 +0000299FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
300 return new MachineLICM(PreRegAlloc);
301}
Bill Wendling0f940c92007-12-07 21:42:31 +0000302
Dan Gohman853d3fb2010-06-22 17:25:57 +0000303/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
304/// loop that has a unique predecessor.
305static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000306 // Check whether this loop even has a unique predecessor.
307 if (!CurLoop->getLoopPredecessor())
308 return false;
309 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000310 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000311 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000312 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000313 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000314 return true;
315}
316
Bill Wendling0f940c92007-12-07 21:42:31 +0000317bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000318 if (PreRegAlloc)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000319 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Evan Chengd94671a2010-04-07 00:41:17 +0000320 else
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000321 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
322 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000323
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000324 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000325 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000326 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000327 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000328 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000329 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000330 MRI = &MF.getRegInfo();
331 InstrItins = TM->getInstrItineraryData();
Bill Wendling0f940c92007-12-07 21:42:31 +0000332
Evan Cheng0e673912010-10-14 01:16:09 +0000333 if (PreRegAlloc) {
334 // Estimate register pressure during pre-regalloc pass.
335 unsigned NumRC = TRI->getNumRegClasses();
336 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000337 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000338 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000339 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
340 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichbe2119e2011-03-07 21:56:36 +0000341 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Cheng0e673912010-10-14 01:16:09 +0000342 }
343
Bill Wendling0f940c92007-12-07 21:42:31 +0000344 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000345 MLI = &getAnalysis<MachineLoopInfo>();
346 DT = &getAnalysis<MachineDominatorTree>();
347 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000348
Dan Gohmanaa742602010-07-09 18:49:45 +0000349 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
350 while (!Worklist.empty()) {
351 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000352 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000353
Evan Cheng4038f9c2010-04-08 01:03:47 +0000354 // If this is done before regalloc, only visit outer-most preheader-sporting
355 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000356 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
357 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000358 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000359 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000360
Evan Chengd94671a2010-04-07 00:41:17 +0000361 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000362 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000363 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000364 // CSEMap is initialized for loop header when the first instruction is
365 // being hoisted.
366 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000367 FirstInLoop = true;
Pete Cooperacde91e2011-12-22 02:05:40 +0000368 HoistOutOfLoop(N);
Evan Chengd94671a2010-04-07 00:41:17 +0000369 CSEMap.clear();
370 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000371 }
372
373 return Changed;
374}
375
Evan Cheng4038f9c2010-04-08 01:03:47 +0000376/// InstructionStoresToFI - Return true if instruction stores to the
377/// specified frame.
378static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
379 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
380 oe = MI->memoperands_end(); o != oe; ++o) {
381 if (!(*o)->isStore() || !(*o)->getValue())
382 continue;
383 if (const FixedStackPseudoSourceValue *Value =
384 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
385 if (Value->getFrameIndex() == FI)
386 return true;
387 }
388 }
389 return false;
390}
391
392/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
393/// gather register def and frame object update information.
394void MachineLICM::ProcessMI(MachineInstr *MI,
395 unsigned *PhysRegDefs,
396 SmallSet<int, 32> &StoredFIs,
397 SmallVector<CandidateInfo, 32> &Candidates) {
398 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000399 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000400 unsigned Def = 0;
401 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
402 const MachineOperand &MO = MI->getOperand(i);
403 if (MO.isFI()) {
404 // Remember if the instruction stores to the frame index.
405 int FI = MO.getIndex();
406 if (!StoredFIs.count(FI) &&
407 MFI->isSpillSlotObjectIndex(FI) &&
408 InstructionStoresToFI(MI, FI))
409 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000410 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000411 continue;
412 }
413
414 if (!MO.isReg())
415 continue;
416 unsigned Reg = MO.getReg();
417 if (!Reg)
418 continue;
419 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
420 "Not expecting virtual register!");
421
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000422 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000423 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000424 // If it's using a non-loop-invariant register, then it's obviously not
425 // safe to hoist.
426 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000427 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000428 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000429
430 if (MO.isImplicit()) {
431 ++PhysRegDefs[Reg];
432 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
433 ++PhysRegDefs[*AS];
434 if (!MO.isDead())
435 // Non-dead implicit def? This cannot be hoisted.
436 RuledOut = true;
437 // No need to check if a dead implicit def is also defined by
438 // another instruction.
439 continue;
440 }
441
442 // FIXME: For now, avoid instructions with multiple defs, unless
443 // it's a dead implicit def.
444 if (Def)
445 RuledOut = true;
446 else
447 Def = Reg;
448
449 // If we have already seen another instruction that defines the same
450 // register, then this is not safe.
451 if (++PhysRegDefs[Reg] > 1)
452 // MI defined register is seen defined by another instruction in
453 // the loop, it cannot be a LICM candidate.
454 RuledOut = true;
455 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
456 if (++PhysRegDefs[*AS] > 1)
457 RuledOut = true;
458 }
459
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000460 // Only consider reloads for now and remats which do not have register
461 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000462 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000463 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000464 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000465 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
466 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000467 }
468}
469
470/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
471/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000472void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000473 unsigned NumRegs = TRI->getNumRegs();
474 unsigned *PhysRegDefs = new unsigned[NumRegs];
475 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
476
Evan Cheng4038f9c2010-04-08 01:03:47 +0000477 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000478 SmallSet<int, 32> StoredFIs;
479
480 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000481 // collect potential LICM candidates.
482 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
483 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
484 MachineBasicBlock *BB = Blocks[i];
Bill Wendlinga2e87912011-10-12 02:58:01 +0000485
486 // If the header of the loop containing this basic block is a landing pad,
487 // then don't try to hoist instructions out of this loop.
488 const MachineLoop *ML = MLI->getLoopFor(BB);
489 if (ML && ML->getHeader()->isLandingPad()) continue;
490
Evan Chengd94671a2010-04-07 00:41:17 +0000491 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000492 // FIXME: That means a reload that're reused in successor block(s) will not
493 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000494 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000495 E = BB->livein_end(); I != E; ++I) {
496 unsigned Reg = *I;
497 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000498 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
499 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000500 }
501
Evan Chengfad62872011-10-11 23:48:44 +0000502 SpeculationState = SpeculateUnknown;
Evan Chengd94671a2010-04-07 00:41:17 +0000503 for (MachineBasicBlock::iterator
504 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000505 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000506 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000507 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000508 }
Evan Chengd94671a2010-04-07 00:41:17 +0000509
510 // Now evaluate whether the potential candidates qualify.
511 // 1. Check if the candidate defined register is defined by another
512 // instruction in the loop.
513 // 2. If the candidate is a load from stack slot (always true for now),
514 // check if the slot is stored anywhere in the loop.
515 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000516 if (Candidates[i].FI != INT_MIN &&
517 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000518 continue;
519
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000520 if (PhysRegDefs[Candidates[i].Def] == 1) {
521 bool Safe = true;
522 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000523 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
524 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000525 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000526 continue;
527 if (PhysRegDefs[MO.getReg()]) {
528 // If it's using a non-loop-invariant register, then it's obviously
529 // not safe to hoist.
530 Safe = false;
531 break;
532 }
533 }
534 if (Safe)
535 HoistPostRA(MI, Candidates[i].Def);
536 }
Evan Chengd94671a2010-04-07 00:41:17 +0000537 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000538
539 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000540}
541
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000542/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
543/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000544void MachineLICM::AddToLiveIns(unsigned Reg) {
545 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000546 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
547 MachineBasicBlock *BB = Blocks[i];
548 if (!BB->isLiveIn(Reg))
549 BB->addLiveIn(Reg);
550 for (MachineBasicBlock::iterator
551 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
552 MachineInstr *MI = &*MII;
553 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
554 MachineOperand &MO = MI->getOperand(i);
555 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
556 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
557 MO.setIsKill(false);
558 }
559 }
560 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000561}
562
563/// HoistPostRA - When an instruction is found to only use loop invariant
564/// operands that is safe to hoist, this instruction is called to do the
565/// dirty work.
566void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000567 MachineBasicBlock *Preheader = getCurPreheader();
568 if (!Preheader) return;
569
Evan Chengd94671a2010-04-07 00:41:17 +0000570 // Now move the instructions to the predecessor, inserting it before any
571 // terminator instructions.
572 DEBUG({
573 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000574 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000575 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000576 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000577 if (MI->getParent()->getBasicBlock())
578 dbgs() << " from MachineBasicBlock "
579 << MI->getParent()->getName();
580 dbgs() << "\n";
581 });
582
583 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000584 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000585 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000586
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000587 // Add register to livein list to all the BBs in the current loop since a
588 // loop invariant must be kept live throughout the whole loop. This is
589 // important to ensure later passes do not scavenge the def register.
590 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000591
592 ++NumPostRAHoisted;
593 Changed = true;
594}
595
Devang Patel2e350472011-10-11 18:09:58 +0000596// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
597// If not then a load from this mbb may not be safe to hoist.
598bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengfad62872011-10-11 23:48:44 +0000599 if (SpeculationState != SpeculateUnknown)
600 return SpeculationState == SpeculateFalse;
601
Devang Patel2e350472011-10-11 18:09:58 +0000602 if (BB != CurLoop->getHeader()) {
603 // Check loop exiting blocks.
604 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
605 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
606 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
607 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Nick Lewyckyea3abd52011-10-13 01:09:50 +0000608 SpeculationState = SpeculateTrue;
609 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000610 }
611 }
612
Evan Chengfad62872011-10-11 23:48:44 +0000613 SpeculationState = SpeculateFalse;
614 return true;
Devang Patel2e350472011-10-11 18:09:58 +0000615}
616
Pete Cooperacde91e2011-12-22 02:05:40 +0000617void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
618 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Bill Wendling0f940c92007-12-07 21:42:31 +0000619
Pete Cooperacde91e2011-12-22 02:05:40 +0000620 // Remember livein register pressure.
621 BackTrace.push_back(RegPressure);
622}
Bill Wendlinga2e87912011-10-12 02:58:01 +0000623
Pete Cooperacde91e2011-12-22 02:05:40 +0000624void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
625 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
626 BackTrace.pop_back();
627}
Bill Wendling0f940c92007-12-07 21:42:31 +0000628
Pete Cooperacde91e2011-12-22 02:05:40 +0000629/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
630/// dominator tree node if its a leaf or all of its children are done. Walk
631/// up the dominator tree to destroy ancestors which are now done.
632void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Cheng75fda5d2012-01-10 22:27:32 +0000633 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
634 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooperacde91e2011-12-22 02:05:40 +0000635 if (OpenChildren[Node])
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000636 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000637
Pete Cooperacde91e2011-12-22 02:05:40 +0000638 // Pop scope.
639 ExitScope(Node->getBlock());
640
641 // Now traverse upwards to pop ancestors whose offsprings are all done.
642 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
643 unsigned Left = --OpenChildren[Parent];
644 if (Left != 0)
645 break;
646 ExitScope(Parent->getBlock());
647 Node = Parent;
648 }
649}
650
651/// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
652/// blocks dominated by the specified header block, and that are in the
653/// current loop) in depth first order w.r.t the DominatorTree. This allows
654/// us to visit definitions before uses, allowing us to hoist a loop body in
655/// one pass without iteration.
656///
657void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
658 SmallVector<MachineDomTreeNode*, 32> Scopes;
659 SmallVector<MachineDomTreeNode*, 8> WorkList;
660 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
661 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
662
663 // Perform a DFS walk to determine the order of visit.
664 WorkList.push_back(HeaderN);
665 do {
666 MachineDomTreeNode *Node = WorkList.pop_back_val();
667 assert(Node != 0 && "Null dominator tree node?");
668 MachineBasicBlock *BB = Node->getBlock();
669
670 // If the header of the loop containing this basic block is a landing pad,
671 // then don't try to hoist instructions out of this loop.
672 const MachineLoop *ML = MLI->getLoopFor(BB);
673 if (ML && ML->getHeader()->isLandingPad())
674 continue;
675
676 // If this subregion is not in the top level loop at all, exit.
677 if (!CurLoop->contains(BB))
678 continue;
679
680 Scopes.push_back(Node);
681 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
682 unsigned NumChildren = Children.size();
683
684 // Don't hoist things out of a large switch statement. This often causes
685 // code to be hoisted that wasn't going to be executed, and increases
686 // register pressure in a situation where it's likely to matter.
687 if (BB->succ_size() >= 25)
688 NumChildren = 0;
689
690 OpenChildren[Node] = NumChildren;
691 // Add children in reverse order as then the next popped worklist node is
692 // the first child of this node. This means we ultimately traverse the
693 // DOM tree in exactly the same order as if we'd recursed.
694 for (int i = (int)NumChildren-1; i >= 0; --i) {
695 MachineDomTreeNode *Child = Children[i];
696 ParentMap[Child] = Node;
697 WorkList.push_back(Child);
698 }
699 } while (!WorkList.empty());
700
701 if (Scopes.size() != 0) {
702 MachineBasicBlock *Preheader = getCurPreheader();
703 if (!Preheader)
704 return;
705
Evan Cheng134982d2010-10-20 22:03:58 +0000706 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000707 RegSeen.clear();
708 BackTrace.clear();
709 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000710 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000711
Pete Cooperacde91e2011-12-22 02:05:40 +0000712 // Now perform LICM.
713 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
714 MachineDomTreeNode *Node = Scopes[i];
715 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng23128422010-10-19 18:58:51 +0000716
Pete Cooperacde91e2011-12-22 02:05:40 +0000717 MachineBasicBlock *Preheader = getCurPreheader();
718 if (!Preheader)
719 continue;
720
721 EnterScope(MBB);
722
723 // Process the block
724 SpeculationState = SpeculateUnknown;
725 for (MachineBasicBlock::iterator
726 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
727 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
728 MachineInstr *MI = &*MII;
729 if (!Hoist(MI, Preheader))
730 UpdateRegPressure(MI);
731 MII = NextMII;
732 }
733
734 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
735 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohmanc475c362009-01-15 22:01:38 +0000736 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000737}
738
Evan Cheng134982d2010-10-20 22:03:58 +0000739static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
740 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
741}
742
Evan Cheng61560e22011-09-01 01:45:00 +0000743/// getRegisterClassIDAndCost - For a given MI, register, and the operand
744/// index, return the ID and cost of its representative register class.
745void
746MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
747 unsigned Reg, unsigned OpIdx,
748 unsigned &RCId, unsigned &RCCost) const {
749 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
750 EVT VT = *RC->vt_begin();
Owen Anderson99aa14f2011-11-16 01:02:57 +0000751 if (VT == MVT::Untyped) {
Evan Cheng61560e22011-09-01 01:45:00 +0000752 RCId = RC->getID();
753 RCCost = 1;
754 } else {
755 RCId = TLI->getRepRegClassFor(VT)->getID();
756 RCCost = TLI->getRepRegClassCostFor(VT);
757 }
758}
759
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000760/// InitRegPressure - Find all virtual register references that are liveout of
761/// the preheader to initialize the starting "register pressure". Note this
762/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000763void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000764 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000765
Evan Cheng134982d2010-10-20 22:03:58 +0000766 // If the preheader has only a single predecessor and it ends with a
767 // fallthrough or an unconditional branch, then scan its predecessor for live
768 // defs as well. This happens whenever the preheader is created by splitting
769 // the critical edge from the loop predecessor to the loop header.
770 if (BB->pred_size() == 1) {
771 MachineBasicBlock *TBB = 0, *FBB = 0;
772 SmallVector<MachineOperand, 4> Cond;
773 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
774 InitRegPressure(*BB->pred_begin());
775 }
776
Evan Cheng0e673912010-10-14 01:16:09 +0000777 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
778 MII != E; ++MII) {
779 MachineInstr *MI = &*MII;
780 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
781 const MachineOperand &MO = MI->getOperand(i);
782 if (!MO.isReg() || MO.isImplicit())
783 continue;
784 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000785 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000786 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000787
Andrew Trickdc986d22010-10-19 02:50:50 +0000788 bool isNew = RegSeen.insert(Reg);
Evan Cheng61560e22011-09-01 01:45:00 +0000789 unsigned RCId, RCCost;
790 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000791 if (MO.isDef())
Evan Cheng61560e22011-09-01 01:45:00 +0000792 RegPressure[RCId] += RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000793 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000794 bool isKill = isOperandKill(MO, MRI);
795 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000796 // Haven't seen this, it must be a livein.
Evan Cheng61560e22011-09-01 01:45:00 +0000797 RegPressure[RCId] += RCCost;
Evan Cheng134982d2010-10-20 22:03:58 +0000798 else if (!isNew && isKill)
Evan Cheng61560e22011-09-01 01:45:00 +0000799 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000800 }
Evan Cheng0e673912010-10-14 01:16:09 +0000801 }
802 }
803}
804
Evan Cheng134982d2010-10-20 22:03:58 +0000805/// UpdateRegPressure - Update estimate of register pressure after the
806/// specified instruction.
807void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
808 if (MI->isImplicitDef())
809 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000810
Evan Cheng134982d2010-10-20 22:03:58 +0000811 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000812 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
813 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000814 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000815 continue;
816 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000817 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000818 continue;
819
Andrew Trickdc986d22010-10-19 02:50:50 +0000820 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000821 if (MO.isDef())
822 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000823 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng61560e22011-09-01 01:45:00 +0000824 unsigned RCId, RCCost;
825 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000826 if (RCCost > RegPressure[RCId])
827 RegPressure[RCId] = 0;
828 else
Evan Cheng23128422010-10-19 18:58:51 +0000829 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000830 }
Evan Cheng0e673912010-10-14 01:16:09 +0000831 }
Evan Cheng0e673912010-10-14 01:16:09 +0000832
Evan Cheng61560e22011-09-01 01:45:00 +0000833 unsigned Idx = 0;
Evan Cheng23128422010-10-19 18:58:51 +0000834 while (!Defs.empty()) {
835 unsigned Reg = Defs.pop_back_val();
Evan Cheng61560e22011-09-01 01:45:00 +0000836 unsigned RCId, RCCost;
837 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Cheng0e673912010-10-14 01:16:09 +0000838 RegPressure[RCId] += RCCost;
Evan Cheng61560e22011-09-01 01:45:00 +0000839 ++Idx;
Evan Cheng0e673912010-10-14 01:16:09 +0000840 }
841}
842
Devang Patel06e16bb2011-10-20 17:42:23 +0000843/// isLoadFromGOTOrConstantPool - Return true if this machine instruction
844/// loads from global offset table or constant pool.
845static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000846 assert (MI.mayLoad() && "Expected MI that loads!");
Devang Patel6c15fec2011-10-17 17:35:01 +0000847 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
848 E = MI.memoperands_end(); I != E; ++I) {
849 if (const Value *V = (*I)->getValue()) {
850 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
Devang Patel06e16bb2011-10-20 17:42:23 +0000851 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
Devang Patel6c15fec2011-10-17 17:35:01 +0000852 return true;
853 }
854 }
855 return false;
856}
857
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000858/// IsLICMCandidate - Returns true if the instruction may be a suitable
859/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
860/// not safe to hoist it.
861bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000862 // Check if it's safe to move the instruction.
863 bool DontMoveAcrossStore = true;
864 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000865 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000866
867 // If it is load then check if it is guaranteed to execute by making sure that
868 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patele6de9f32011-10-20 17:31:18 +0000869 // the loop which does not execute this load, so we can't hoist it. Loads
870 // from constant memory are not safe to speculate all the time, for example
871 // indexed load from a jump table.
Devang Patel2e350472011-10-11 18:09:58 +0000872 // Stores and side effects are already checked by isSafeToMove.
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000873 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
Devang Patel6c15fec2011-10-17 17:35:01 +0000874 !IsGuaranteedToExecute(I.getParent()))
Devang Patel2e350472011-10-11 18:09:58 +0000875 return false;
876
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000877 return true;
878}
879
880/// IsLoopInvariantInst - Returns true if the instruction is loop
881/// invariant. I.e., all virtual register operands are defined outside of the
882/// loop, physical registers aren't accessed explicitly, and there are no side
883/// effects that aren't captured by the operands or other flags.
884///
885bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
886 if (!IsLICMCandidate(I))
887 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000888
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000889 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000890 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
891 const MachineOperand &MO = I.getOperand(i);
892
Dan Gohmand735b802008-10-03 15:45:36 +0000893 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000894 continue;
895
Dan Gohmanc475c362009-01-15 22:01:38 +0000896 unsigned Reg = MO.getReg();
897 if (Reg == 0) continue;
898
899 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000900 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000901 if (MO.isUse()) {
902 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000903 // and we can freely move its uses. Alternatively, if it's allocatable,
904 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesenc035c942012-01-16 22:34:08 +0000905 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000906 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000907 // Otherwise it's safe to move.
908 continue;
909 } else if (!MO.isDead()) {
910 // A def that isn't dead. We can't move it.
911 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000912 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
913 // If the reg is live into the loop, we can't hoist an instruction
914 // which would clobber it.
915 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000916 }
917 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000918
919 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000920 continue;
921
Evan Cheng0e673912010-10-14 01:16:09 +0000922 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000923 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000924
925 // If the loop contains the definition of an operand, then the instruction
926 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000927 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000928 return false;
929 }
930
931 // If we got this far, the instruction is loop invariant!
932 return true;
933}
934
Evan Chengaf6949d2009-02-05 08:45:46 +0000935
Evan Chengd67705f2011-04-11 21:09:18 +0000936/// HasAnyPHIUse - Return true if the specified register is used by any
937/// phi node.
938bool MachineLICM::HasAnyPHIUse(unsigned Reg) const {
Evan Cheng0e673912010-10-14 01:16:09 +0000939 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
940 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000941 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000942 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000943 return true;
Evan Chengd67705f2011-04-11 21:09:18 +0000944 // Look pass copies as well.
945 if (UseMI->isCopy()) {
946 unsigned Def = UseMI->getOperand(0).getReg();
947 if (TargetRegisterInfo::isVirtualRegister(Def) &&
948 HasAnyPHIUse(Def))
949 return true;
950 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000951 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000952 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000953}
954
Evan Cheng23128422010-10-19 18:58:51 +0000955/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
956/// and an use in the current loop, return true if the target considered
957/// it 'high'.
958bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +0000959 unsigned DefIdx, unsigned Reg) const {
960 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000961 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000962
Evan Cheng0e673912010-10-14 01:16:09 +0000963 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
964 E = MRI->use_nodbg_end(); I != E; ++I) {
965 MachineInstr *UseMI = &*I;
Evan Chengc8141df2010-10-26 02:08:50 +0000966 if (UseMI->isCopyLike())
967 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000968 if (!CurLoop->contains(UseMI->getParent()))
969 continue;
970 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
971 const MachineOperand &MO = UseMI->getOperand(i);
972 if (!MO.isReg() || !MO.isUse())
973 continue;
974 unsigned MOReg = MO.getReg();
975 if (MOReg != Reg)
976 continue;
977
Evan Cheng23128422010-10-19 18:58:51 +0000978 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
979 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000980 }
981
Evan Cheng23128422010-10-19 18:58:51 +0000982 // Only look at the first in loop use.
983 break;
Evan Cheng0e673912010-10-14 01:16:09 +0000984 }
985
Evan Cheng23128422010-10-19 18:58:51 +0000986 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000987}
988
Evan Chengc8141df2010-10-26 02:08:50 +0000989/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
990/// the operand latency between its def and a use is one or less.
991bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000992 if (MI.isAsCheapAsAMove() || MI.isCopyLike())
Evan Chengc8141df2010-10-26 02:08:50 +0000993 return true;
994 if (!InstrItins || InstrItins->isEmpty())
995 return false;
996
997 bool isCheap = false;
998 unsigned NumDefs = MI.getDesc().getNumDefs();
999 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1000 MachineOperand &DefMO = MI.getOperand(i);
1001 if (!DefMO.isReg() || !DefMO.isDef())
1002 continue;
1003 --NumDefs;
1004 unsigned Reg = DefMO.getReg();
1005 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1006 continue;
1007
1008 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1009 return false;
1010 isCheap = true;
1011 }
1012
1013 return isCheap;
1014}
1015
Evan Cheng134982d2010-10-20 22:03:58 +00001016/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001017/// if hoisting an instruction of the given cost matrix can cause high
1018/// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +00001019bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
1020 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1021 CI != CE; ++CI) {
1022 if (CI->second <= 0)
1023 continue;
1024
1025 unsigned RCId = CI->first;
Pete Cooper3cfecf52011-12-22 02:13:25 +00001026 unsigned Limit = RegLimit[RCId];
1027 int Cost = CI->second;
Evan Cheng134982d2010-10-20 22:03:58 +00001028 for (unsigned i = BackTrace.size(); i != 0; --i) {
1029 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Pete Cooper3cfecf52011-12-22 02:13:25 +00001030 if (RP[RCId] + Cost >= Limit)
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001031 return true;
1032 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001033 }
1034
1035 return false;
1036}
1037
Evan Cheng134982d2010-10-20 22:03:58 +00001038/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1039/// current block and update their register pressures to reflect the effect
1040/// of hoisting MI from the current block to the preheader.
1041void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1042 if (MI->isImplicitDef())
1043 return;
1044
1045 // First compute the 'cost' of the instruction, i.e. its contribution
1046 // to register pressure.
1047 DenseMap<unsigned, int> Cost;
1048 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1049 const MachineOperand &MO = MI->getOperand(i);
1050 if (!MO.isReg() || MO.isImplicit())
1051 continue;
1052 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +00001053 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng134982d2010-10-20 22:03:58 +00001054 continue;
1055
Evan Cheng61560e22011-09-01 01:45:00 +00001056 unsigned RCId, RCCost;
1057 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +00001058 if (MO.isDef()) {
1059 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1060 if (CI != Cost.end())
1061 CI->second += RCCost;
1062 else
1063 Cost.insert(std::make_pair(RCId, RCCost));
1064 } else if (isOperandKill(MO, MRI)) {
1065 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1066 if (CI != Cost.end())
1067 CI->second -= RCCost;
1068 else
1069 Cost.insert(std::make_pair(RCId, -RCCost));
1070 }
1071 }
1072
1073 // Update register pressure of blocks from loop header to current block.
1074 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
1075 SmallVector<unsigned, 8> &RP = BackTrace[i];
1076 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1077 CI != CE; ++CI) {
1078 unsigned RCId = CI->first;
1079 RP[RCId] += CI->second;
1080 }
1081 }
1082}
1083
Evan Cheng45e94d62009-02-04 09:19:56 +00001084/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1085/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +00001086bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +00001087 if (MI.isImplicitDef())
1088 return true;
1089
Evan Cheng23128422010-10-19 18:58:51 +00001090 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
1091 // will increase register pressure. It's probably not worth it if the
1092 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +00001093 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
1094 // these tend to help performance in low register pressure situation. The
1095 // trade off is it may cause spill in high pressure situation. It will end up
1096 // adding a store in the loop preheader. But the reload is no more expensive.
1097 // The side benefit is these loads are frequently CSE'ed.
Evan Chengc8141df2010-10-26 02:08:50 +00001098 if (IsCheapInstruction(MI)) {
Evan Cheng23128422010-10-19 18:58:51 +00001099 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +00001100 return false;
1101 } else {
Evan Cheng23128422010-10-19 18:58:51 +00001102 // Estimate register pressure to determine whether to LICM the instruction.
Evan Cheng0e673912010-10-14 01:16:09 +00001103 // In low register pressure situation, we can be more aggressive about
1104 // hoisting. Also, favors hoisting long latency instructions even in
1105 // moderately high pressure situation.
Dan Gohmanfca0b102010-11-11 18:08:43 +00001106 // FIXME: If there are long latency loop-invariant instructions inside the
1107 // loop at this point, why didn't the optimizer's LICM hoist them?
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001108 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +00001109 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1110 const MachineOperand &MO = MI.getOperand(i);
1111 if (!MO.isReg() || MO.isImplicit())
1112 continue;
1113 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +00001114 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +00001115 continue;
Evan Cheng61560e22011-09-01 01:45:00 +00001116
1117 unsigned RCId, RCCost;
1118 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001119 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +00001120 if (HasHighOperandLatency(MI, i, Reg)) {
1121 ++NumHighLatency;
1122 return true;
Evan Cheng0e673912010-10-14 01:16:09 +00001123 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001124
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001125 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001126 if (CI != Cost.end())
1127 CI->second += RCCost;
1128 else
1129 Cost.insert(std::make_pair(RCId, RCCost));
Evan Cheng134982d2010-10-20 22:03:58 +00001130 } else if (isOperandKill(MO, MRI)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001131 // Is a virtual register use is a kill, hoisting it out of the loop
1132 // may actually reduce register pressure or be register pressure
Evan Cheng134982d2010-10-20 22:03:58 +00001133 // neutral.
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001134 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1135 if (CI != Cost.end())
1136 CI->second -= RCCost;
1137 else
1138 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +00001139 }
1140 }
1141
Evan Cheng134982d2010-10-20 22:03:58 +00001142 // Visit BBs from header to current BB, if hoisting this doesn't cause
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001143 // high register pressure, then it's safe to proceed.
Evan Cheng134982d2010-10-20 22:03:58 +00001144 if (!CanCauseHighRegPressure(Cost)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001145 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +00001146 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001147 }
Evan Cheng0e673912010-10-14 01:16:09 +00001148
Evan Cheng7007e4c2011-10-12 21:33:49 +00001149 // Do not "speculate" in high register pressure situation. If an
Evan Chengfad62872011-10-11 23:48:44 +00001150 // instruction is not guaranteed to be executed in the loop, it's best to be
1151 // conservative.
Evan Cheng7007e4c2011-10-12 21:33:49 +00001152 if (AvoidSpeculation &&
1153 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI)))
1154 return false;
1155
1156 // High register pressure situation, only hoist if the instruction is going to
1157 // be remat'ed.
1158 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1159 !MI.isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001160 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001161 }
Evan Cheng45e94d62009-02-04 09:19:56 +00001162
Evan Chengd67705f2011-04-11 21:09:18 +00001163 // If result(s) of this instruction is used by PHIs outside of the loop, then
1164 // don't hoist it if the instruction because it will introduce an extra copy.
Evan Cheng45e94d62009-02-04 09:19:56 +00001165 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1166 const MachineOperand &MO = MI.getOperand(i);
1167 if (!MO.isReg() || !MO.isDef())
1168 continue;
Evan Chengd67705f2011-04-11 21:09:18 +00001169 if (HasAnyPHIUse(MO.getReg()))
Evan Chengaf6949d2009-02-05 08:45:46 +00001170 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +00001171 }
Evan Chengaf6949d2009-02-05 08:45:46 +00001172
1173 return true;
1174}
1175
Dan Gohman5c952302009-10-29 17:47:20 +00001176MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001177 // Don't unfold simple loads.
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001178 if (MI->canFoldAsLoad())
Evan Chenge95f3192010-10-08 18:59:19 +00001179 return 0;
1180
Dan Gohman5c952302009-10-29 17:47:20 +00001181 // If not, we may be able to unfold a load and hoist that.
1182 // First test whether the instruction is loading from an amenable
1183 // memory location.
Evan Cheng9fe20092011-01-20 08:34:58 +00001184 if (!MI->isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001185 return 0;
1186
Dan Gohman5c952302009-10-29 17:47:20 +00001187 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001188 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001189 unsigned NewOpc =
1190 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1191 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001192 /*UnfoldStore=*/false,
1193 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001194 if (NewOpc == 0) return 0;
Evan Chenge837dea2011-06-28 19:10:37 +00001195 const MCInstrDesc &MID = TII->get(NewOpc);
1196 if (MID.getNumDefs() != 1) return 0;
1197 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001198 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001199 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001200
1201 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001202 SmallVector<MachineInstr *, 2> NewMIs;
1203 bool Success =
1204 TII->unfoldMemoryOperand(MF, MI, Reg,
1205 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1206 NewMIs);
1207 (void)Success;
1208 assert(Success &&
1209 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1210 "succeeded!");
1211 assert(NewMIs.size() == 2 &&
1212 "Unfolded a load into multiple instructions!");
1213 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng7c2a4a32011-12-06 22:12:01 +00001214 MachineBasicBlock::iterator Pos = MI;
1215 MBB->insert(Pos, NewMIs[0]);
1216 MBB->insert(Pos, NewMIs[1]);
Dan Gohman5c952302009-10-29 17:47:20 +00001217 // If unfolding produced a load that wasn't loop-invariant or profitable to
1218 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001219 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001220 NewMIs[0]->eraseFromParent();
1221 NewMIs[1]->eraseFromParent();
1222 return 0;
1223 }
Evan Cheng134982d2010-10-20 22:03:58 +00001224
1225 // Update register pressure for the unfolded instruction.
1226 UpdateRegPressure(NewMIs[1]);
1227
Dan Gohman5c952302009-10-29 17:47:20 +00001228 // Otherwise we successfully unfolded a load that we can hoist.
1229 MI->eraseFromParent();
1230 return NewMIs[0];
1231}
1232
Evan Cheng777c6b72009-11-03 21:40:02 +00001233void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1234 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1235 const MachineInstr *MI = &*I;
Evan Cheng9fe20092011-01-20 08:34:58 +00001236 unsigned Opcode = MI->getOpcode();
1237 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1238 CI = CSEMap.find(Opcode);
1239 if (CI != CSEMap.end())
1240 CI->second.push_back(MI);
1241 else {
1242 std::vector<const MachineInstr*> CSEMIs;
1243 CSEMIs.push_back(MI);
1244 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Cheng777c6b72009-11-03 21:40:02 +00001245 }
1246 }
1247}
1248
Evan Cheng78e5c112009-11-07 03:52:02 +00001249const MachineInstr*
1250MachineLICM::LookForDuplicate(const MachineInstr *MI,
1251 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001252 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1253 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng9fe20092011-01-20 08:34:58 +00001254 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001255 return PrevMI;
1256 }
1257 return 0;
1258}
1259
1260bool MachineLICM::EliminateCSE(MachineInstr *MI,
1261 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001262 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1263 // the undef property onto uses.
1264 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001265 return false;
1266
1267 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001268 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001269
1270 // Replace virtual registers defined by MI by their counterparts defined
1271 // by Dup.
Evan Cheng1025cce2011-10-17 19:50:12 +00001272 SmallVector<unsigned, 2> Defs;
Evan Cheng78e5c112009-11-07 03:52:02 +00001273 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1274 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001275
1276 // Physical registers may not differ here.
1277 assert((!MO.isReg() || MO.getReg() == 0 ||
1278 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1279 MO.getReg() == Dup->getOperand(i).getReg()) &&
1280 "Instructions with different phys regs are not identical!");
1281
1282 if (MO.isReg() && MO.isDef() &&
Evan Cheng1025cce2011-10-17 19:50:12 +00001283 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1284 Defs.push_back(i);
1285 }
1286
1287 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1288 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1289 unsigned Idx = Defs[i];
1290 unsigned Reg = MI->getOperand(Idx).getReg();
1291 unsigned DupReg = Dup->getOperand(Idx).getReg();
1292 OrigRCs.push_back(MRI->getRegClass(DupReg));
1293
1294 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1295 // Restore old RCs if more than one defs.
1296 for (unsigned j = 0; j != i; ++j)
1297 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1298 return false;
Dan Gohmane6cd7572010-05-13 20:34:42 +00001299 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001300 }
Evan Cheng1025cce2011-10-17 19:50:12 +00001301
1302 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1303 unsigned Idx = Defs[i];
1304 unsigned Reg = MI->getOperand(Idx).getReg();
1305 unsigned DupReg = Dup->getOperand(Idx).getReg();
1306 MRI->replaceRegWith(Reg, DupReg);
1307 MRI->clearKillFlags(DupReg);
1308 }
1309
Evan Cheng78e5c112009-11-07 03:52:02 +00001310 MI->eraseFromParent();
1311 ++NumCSEed;
1312 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001313 }
1314 return false;
1315}
1316
Evan Cheng7efba852011-10-12 00:09:14 +00001317/// MayCSE - Return true if the given instruction will be CSE'd if it's
1318/// hoisted out of the loop.
1319bool MachineLICM::MayCSE(MachineInstr *MI) {
1320 unsigned Opcode = MI->getOpcode();
1321 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1322 CI = CSEMap.find(Opcode);
1323 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1324 // the undef property onto uses.
1325 if (CI == CSEMap.end() || MI->isImplicitDef())
1326 return false;
1327
1328 return LookForDuplicate(MI, CI->second) != 0;
1329}
1330
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001331/// Hoist - When an instruction is found to use only loop invariant operands
1332/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001333///
Evan Cheng134982d2010-10-20 22:03:58 +00001334bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001335 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001336 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001337 // If not, try unfolding a hoistable load.
1338 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001339 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001340 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001341
Dan Gohmanc475c362009-01-15 22:01:38 +00001342 // Now move the instructions to the predecessor, inserting it before any
1343 // terminator instructions.
1344 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001345 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001346 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001347 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001348 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001349 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001350 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001351 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001352 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001353 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001354
Evan Cheng777c6b72009-11-03 21:40:02 +00001355 // If this is the first instruction being hoisted to the preheader,
1356 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001357 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001358 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001359 FirstInLoop = false;
1360 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001361
Evan Chengaf6949d2009-02-05 08:45:46 +00001362 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001363 unsigned Opcode = MI->getOpcode();
1364 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1365 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001366 if (!EliminateCSE(MI, CI)) {
1367 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001368 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001369
Evan Cheng134982d2010-10-20 22:03:58 +00001370 // Update register pressure for BBs from header to this block.
1371 UpdateBackTraceRegPressure(MI);
1372
Dan Gohmane6cd7572010-05-13 20:34:42 +00001373 // Clear the kill flags of any register this instruction defines,
1374 // since they may need to be live throughout the entire loop
1375 // rather than just live for part of it.
1376 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1377 MachineOperand &MO = MI->getOperand(i);
1378 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001379 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001380 }
1381
Evan Chengaf6949d2009-02-05 08:45:46 +00001382 // Add to the CSE map.
1383 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001384 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001385 else {
1386 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001387 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001388 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001389 }
1390 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001391
Dan Gohmanc475c362009-01-15 22:01:38 +00001392 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001393 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001394
1395 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001396}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001397
1398MachineBasicBlock *MachineLICM::getCurPreheader() {
1399 // Determine the block to which to hoist instructions. If we can't find a
1400 // suitable loop predecessor, we can't do any hoisting.
1401
1402 // If we've tried to get a preheader and failed, don't try again.
1403 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1404 return 0;
1405
1406 if (!CurPreheader) {
1407 CurPreheader = CurLoop->getLoopPreheader();
1408 if (!CurPreheader) {
1409 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1410 if (!Pred) {
1411 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1412 return 0;
1413 }
1414
1415 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1416 if (!CurPreheader) {
1417 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1418 return 0;
1419 }
1420 }
1421 }
1422 return CurPreheader;
1423}