blob: 6116281d59866edae893d203ea12dd0c50c41202 [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"
Chris Lattnerac695822008-01-04 06:41:45 +000040#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000041#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000042using namespace llvm;
43
Evan Cheng03a9fdf2010-10-16 02:20:26 +000044STATISTIC(NumHoisted,
45 "Number of machine instructions hoisted out of loops");
46STATISTIC(NumLowRP,
47 "Number of instructions hoisted in low reg pressure situation");
48STATISTIC(NumHighLatency,
49 "Number of high latency instructions hoisted");
50STATISTIC(NumCSEed,
51 "Number of hoisted machine instructions CSEed");
Evan Chengd94671a2010-04-07 00:41:17 +000052STATISTIC(NumPostRAHoisted,
53 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendlingb48519c2007-12-08 01:47:01 +000054
Bill Wendling0f940c92007-12-07 21:42:31 +000055namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000056 class MachineLICM : public MachineFunctionPass {
Evan Chengd94671a2010-04-07 00:41:17 +000057 bool PreRegAlloc;
58
Bill Wendling9258cd32008-01-02 19:32:43 +000059 const TargetMachine *TM;
Bill Wendlingefe2be72007-12-11 23:27:51 +000060 const TargetInstrInfo *TII;
Evan Cheng0e673912010-10-14 01:16:09 +000061 const TargetLowering *TLI;
Dan Gohmana8fb3362009-09-25 23:58:45 +000062 const TargetRegisterInfo *TRI;
Evan Chengd94671a2010-04-07 00:41:17 +000063 const MachineFrameInfo *MFI;
Evan Cheng0e673912010-10-14 01:16:09 +000064 MachineRegisterInfo *MRI;
65 const InstrItineraryData *InstrItins;
Bill Wendling12ebf142007-12-11 19:40:06 +000066
Bill Wendling0f940c92007-12-07 21:42:31 +000067 // Various analyses that we use...
Dan Gohmane33f44c2009-10-07 17:38:06 +000068 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng4038f9c2010-04-08 01:03:47 +000069 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000070 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendling0f940c92007-12-07 21:42:31 +000071
Bill Wendling0f940c92007-12-07 21:42:31 +000072 // State that is updated as we process loops
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000073 bool Changed; // True if a loop is changed.
Evan Cheng82e0a1a2010-05-29 00:06:36 +000074 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +000075 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohmanc475c362009-01-15 22:01:38 +000076 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Chengaf6949d2009-02-05 08:45:46 +000077
Evan Chengd94671a2010-04-07 00:41:17 +000078 BitVector AllocatableSet;
79
Evan Cheng0e673912010-10-14 01:16:09 +000080 // Track 'estimated' register pressure.
Evan Cheng03a9fdf2010-10-16 02:20:26 +000081 SmallSet<unsigned, 32> RegSeen;
Evan Cheng0e673912010-10-14 01:16:09 +000082 SmallVector<unsigned, 8> RegPressure;
Evan Cheng03a9fdf2010-10-16 02:20:26 +000083
84 // Register pressure "limit" per register class. If the pressure
85 // is higher than the limit, then it's considered high.
Evan Cheng0e673912010-10-14 01:16:09 +000086 SmallVector<unsigned, 8> RegLimit;
87
Evan Cheng03a9fdf2010-10-16 02:20:26 +000088 // Register pressure on path leading from loop preheader to current BB.
89 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
90
Dale Johannesenc46a5f22010-07-29 17:45:24 +000091 // For each opcode, keep a list of potential CSE instructions.
Evan Cheng777c6b72009-11-03 21:40:02 +000092 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Chengd94671a2010-04-07 00:41:17 +000093
Evan Chengfad62872011-10-11 23:48:44 +000094 enum {
95 SpeculateFalse = 0,
96 SpeculateTrue = 1,
97 SpeculateUnknown = 2
98 };
99
Devang Patel2e350472011-10-11 18:09:58 +0000100 // If a MBB does not dominate loop exiting blocks then it may not safe
101 // to hoist loads from this block.
Evan Chengfad62872011-10-11 23:48:44 +0000102 // Tri-state: 0 - false, 1 - true, 2 - unknown
103 unsigned SpeculationState;
Devang Patel2e350472011-10-11 18:09:58 +0000104
Bill Wendling0f940c92007-12-07 21:42:31 +0000105 public:
106 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +0000107 MachineLICM() :
Owen Anderson081c34b2010-10-19 17:21:58 +0000108 MachineFunctionPass(ID), PreRegAlloc(true) {
109 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
110 }
Evan Chengd94671a2010-04-07 00:41:17 +0000111
112 explicit MachineLICM(bool PreRA) :
Owen Anderson081c34b2010-10-19 17:21:58 +0000113 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
114 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
115 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000116
117 virtual bool runOnMachineFunction(MachineFunction &MF);
118
Dan Gohman72241702008-12-18 01:37:56 +0000119 const char *getPassName() const { return "Machine Instruction LICM"; }
120
Bill Wendling0f940c92007-12-07 21:42:31 +0000121 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Bill Wendling0f940c92007-12-07 21:42:31 +0000122 AU.addRequired<MachineLoopInfo>();
123 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000124 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000125 AU.addPreserved<MachineLoopInfo>();
126 AU.addPreserved<MachineDominatorTree>();
127 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000128 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000129
130 virtual void releaseMemory() {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000131 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000132 RegPressure.clear();
133 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000134 BackTrace.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000135 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
136 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
137 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000138 CSEMap.clear();
139 }
140
Bill Wendling0f940c92007-12-07 21:42:31 +0000141 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000142 /// CandidateInfo - Keep track of information about hoisting candidates.
143 struct CandidateInfo {
144 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000145 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000146 int FI;
147 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
148 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000149 };
150
151 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
152 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000153 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000154
155 /// HoistPostRA - When an instruction is found to only use loop invariant
156 /// operands that is safe to hoist, this instruction is called to do the
157 /// dirty work.
158 void HoistPostRA(MachineInstr *MI, unsigned Def);
159
160 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
161 /// gather register def and frame object update information.
162 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
163 SmallSet<int, 32> &StoredFIs,
164 SmallVector<CandidateInfo, 32> &Candidates);
165
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000166 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
167 /// current loop.
168 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000169
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000170 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000171 /// candidate for LICM. e.g. If the instruction is a call, then it's
172 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000173 bool IsLICMCandidate(MachineInstr &I);
174
Bill Wendling041b3f82007-12-08 23:58:46 +0000175 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000176 /// invariant. I.e., all virtual register operands are defined outside of
177 /// the loop, physical registers aren't accessed (explicitly or implicitly),
178 /// and the instruction is hoistable.
179 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000180 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000181
Evan Chengd67705f2011-04-11 21:09:18 +0000182 /// HasAnyPHIUse - Return true if the specified register is used by any
183 /// phi node.
184 bool HasAnyPHIUse(unsigned Reg) const;
185
Evan Cheng23128422010-10-19 18:58:51 +0000186 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
187 /// and an use in the current loop, return true if the target considered
188 /// it 'high'.
Evan Chengc8141df2010-10-26 02:08:50 +0000189 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
190 unsigned Reg) const;
191
192 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Cheng0e673912010-10-14 01:16:09 +0000193
Evan Cheng134982d2010-10-20 22:03:58 +0000194 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
195 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000196 /// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000197 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
198
199 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
200 /// the current block and update their register pressures to reflect the
201 /// effect of hoisting MI from the current block to the preheader.
202 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000203
Evan Cheng45e94d62009-02-04 09:19:56 +0000204 /// IsProfitableToHoist - Return true if it is potentially profitable to
205 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000206 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000207
Devang Patel2e350472011-10-11 18:09:58 +0000208 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
209 /// If not then a load from this mbb may not be safe to hoist.
210 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
211
Bill Wendling0f940c92007-12-07 21:42:31 +0000212 /// HoistRegion - Walk the specified region of the CFG (defined by all
213 /// blocks dominated by the specified block, and that are in the current
214 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
215 /// visit definitions before uses, allowing us to hoist a loop body in one
216 /// pass without iteration.
217 ///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000218 void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
Bill Wendling0f940c92007-12-07 21:42:31 +0000219
Evan Cheng61560e22011-09-01 01:45:00 +0000220 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
221 /// index, return the ID and cost of its representative register class by
222 /// reference.
223 void getRegisterClassIDAndCost(const MachineInstr *MI,
224 unsigned Reg, unsigned OpIdx,
225 unsigned &RCId, unsigned &RCCost) const;
226
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000227 /// InitRegPressure - Find all virtual register references that are liveout
228 /// of the preheader to initialize the starting "register pressure". Note
229 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000230 void InitRegPressure(MachineBasicBlock *BB);
231
Evan Cheng134982d2010-10-20 22:03:58 +0000232 /// UpdateRegPressure - Update estimate of register pressure after the
233 /// specified instruction.
234 void UpdateRegPressure(const MachineInstr *MI);
Evan Cheng0e673912010-10-14 01:16:09 +0000235
Dan Gohman5c952302009-10-29 17:47:20 +0000236 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
237 /// the load itself could be hoisted. Return the unfolded and hoistable
238 /// load, or null if the load couldn't be unfolded or if it wouldn't
239 /// be hoistable.
240 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
241
Evan Cheng78e5c112009-11-07 03:52:02 +0000242 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
243 /// duplicate of MI. Return this instruction if it's found.
244 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
245 std::vector<const MachineInstr*> &PrevMIs);
246
Evan Cheng9fb744e2009-11-05 00:51:13 +0000247 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
248 /// the preheader that compute the same value. If it's found, do a RAU on
249 /// with the definition of the existing instruction rather than hoisting
250 /// the instruction to the preheader.
251 bool EliminateCSE(MachineInstr *MI,
252 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
253
Evan Cheng7efba852011-10-12 00:09:14 +0000254 /// MayCSE - Return true if the given instruction will be CSE'd if it's
255 /// hoisted out of the loop.
256 bool MayCSE(MachineInstr *MI);
257
Bill Wendling0f940c92007-12-07 21:42:31 +0000258 /// Hoist - When an instruction is found to only use loop invariant operands
259 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000260 /// It returns true if the instruction is hoisted.
261 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000262
263 /// InitCSEMap - Initialize the CSE map with instructions that are in the
264 /// current loop preheader that may become duplicates of instructions that
265 /// are hoisted out of the loop.
266 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000267
268 /// getCurPreheader - Get the preheader for the current loop, splitting
269 /// a critical edge if needed.
270 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000271 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000272} // end anonymous namespace
273
Dan Gohman844731a2008-05-13 00:00:25 +0000274char MachineLICM::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000275INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
276 "Machine Loop Invariant Code Motion", false, false)
277INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
278INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
279INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
280INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000281 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000282
Evan Chengd94671a2010-04-07 00:41:17 +0000283FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
284 return new MachineLICM(PreRegAlloc);
285}
Bill Wendling0f940c92007-12-07 21:42:31 +0000286
Dan Gohman853d3fb2010-06-22 17:25:57 +0000287/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
288/// loop that has a unique predecessor.
289static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000290 // Check whether this loop even has a unique predecessor.
291 if (!CurLoop->getLoopPredecessor())
292 return false;
293 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000294 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000295 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000296 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000297 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000298 return true;
299}
300
Bill Wendling0f940c92007-12-07 21:42:31 +0000301bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000302 if (PreRegAlloc)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000303 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Evan Chengd94671a2010-04-07 00:41:17 +0000304 else
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000305 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
306 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000307
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000308 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000309 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000310 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000311 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000312 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000313 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000314 MRI = &MF.getRegInfo();
315 InstrItins = TM->getInstrItineraryData();
Dan Gohman45094e32009-09-26 02:34:00 +0000316 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000317
Evan Cheng0e673912010-10-14 01:16:09 +0000318 if (PreRegAlloc) {
319 // Estimate register pressure during pre-regalloc pass.
320 unsigned NumRC = TRI->getNumRegClasses();
321 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000322 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000323 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000324 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
325 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichbe2119e2011-03-07 21:56:36 +0000326 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Cheng0e673912010-10-14 01:16:09 +0000327 }
328
Bill Wendling0f940c92007-12-07 21:42:31 +0000329 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000330 MLI = &getAnalysis<MachineLoopInfo>();
331 DT = &getAnalysis<MachineDominatorTree>();
332 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000333
Dan Gohmanaa742602010-07-09 18:49:45 +0000334 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
335 while (!Worklist.empty()) {
336 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000337 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000338
Evan Cheng4038f9c2010-04-08 01:03:47 +0000339 // If this is done before regalloc, only visit outer-most preheader-sporting
340 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000341 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
342 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000343 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000344 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000345
Bill Wendlingc83693f2011-10-11 22:42:31 +0000346 // If the header is a landing pad, then we don't want to hoist instructions
347 // out of it. This can happen with SjLj exception handling which has a
348 // dispatch table as the landing pad.
349 if (CurLoop->getHeader()->isLandingPad()) continue;
350
Evan Chengd94671a2010-04-07 00:41:17 +0000351 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000352 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000353 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000354 // CSEMap is initialized for loop header when the first instruction is
355 // being hoisted.
356 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000357 FirstInLoop = true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000358 HoistRegion(N, true);
Evan Chengd94671a2010-04-07 00:41:17 +0000359 CSEMap.clear();
360 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000361 }
362
363 return Changed;
364}
365
Evan Cheng4038f9c2010-04-08 01:03:47 +0000366/// InstructionStoresToFI - Return true if instruction stores to the
367/// specified frame.
368static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
369 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
370 oe = MI->memoperands_end(); o != oe; ++o) {
371 if (!(*o)->isStore() || !(*o)->getValue())
372 continue;
373 if (const FixedStackPseudoSourceValue *Value =
374 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
375 if (Value->getFrameIndex() == FI)
376 return true;
377 }
378 }
379 return false;
380}
381
382/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
383/// gather register def and frame object update information.
384void MachineLICM::ProcessMI(MachineInstr *MI,
385 unsigned *PhysRegDefs,
386 SmallSet<int, 32> &StoredFIs,
387 SmallVector<CandidateInfo, 32> &Candidates) {
388 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000389 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000390 unsigned Def = 0;
391 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
392 const MachineOperand &MO = MI->getOperand(i);
393 if (MO.isFI()) {
394 // Remember if the instruction stores to the frame index.
395 int FI = MO.getIndex();
396 if (!StoredFIs.count(FI) &&
397 MFI->isSpillSlotObjectIndex(FI) &&
398 InstructionStoresToFI(MI, FI))
399 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000400 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000401 continue;
402 }
403
404 if (!MO.isReg())
405 continue;
406 unsigned Reg = MO.getReg();
407 if (!Reg)
408 continue;
409 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
410 "Not expecting virtual register!");
411
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000412 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000413 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000414 // If it's using a non-loop-invariant register, then it's obviously not
415 // safe to hoist.
416 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000417 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000418 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000419
420 if (MO.isImplicit()) {
421 ++PhysRegDefs[Reg];
422 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
423 ++PhysRegDefs[*AS];
424 if (!MO.isDead())
425 // Non-dead implicit def? This cannot be hoisted.
426 RuledOut = true;
427 // No need to check if a dead implicit def is also defined by
428 // another instruction.
429 continue;
430 }
431
432 // FIXME: For now, avoid instructions with multiple defs, unless
433 // it's a dead implicit def.
434 if (Def)
435 RuledOut = true;
436 else
437 Def = Reg;
438
439 // If we have already seen another instruction that defines the same
440 // register, then this is not safe.
441 if (++PhysRegDefs[Reg] > 1)
442 // MI defined register is seen defined by another instruction in
443 // the loop, it cannot be a LICM candidate.
444 RuledOut = true;
445 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
446 if (++PhysRegDefs[*AS] > 1)
447 RuledOut = true;
448 }
449
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000450 // Only consider reloads for now and remats which do not have register
451 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000452 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000453 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000454 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000455 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
456 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000457 }
458}
459
460/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
461/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000462void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000463 unsigned NumRegs = TRI->getNumRegs();
464 unsigned *PhysRegDefs = new unsigned[NumRegs];
465 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
466
Evan Cheng4038f9c2010-04-08 01:03:47 +0000467 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000468 SmallSet<int, 32> StoredFIs;
469
470 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000471 // collect potential LICM candidates.
472 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
473 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
474 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000475 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000476 // FIXME: That means a reload that're reused in successor block(s) will not
477 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000478 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000479 E = BB->livein_end(); I != E; ++I) {
480 unsigned Reg = *I;
481 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000482 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
483 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000484 }
485
Evan Chengfad62872011-10-11 23:48:44 +0000486 SpeculationState = SpeculateUnknown;
Evan Chengd94671a2010-04-07 00:41:17 +0000487 for (MachineBasicBlock::iterator
488 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000489 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000490 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000491 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000492 }
Evan Chengd94671a2010-04-07 00:41:17 +0000493
494 // Now evaluate whether the potential candidates qualify.
495 // 1. Check if the candidate defined register is defined by another
496 // instruction in the loop.
497 // 2. If the candidate is a load from stack slot (always true for now),
498 // check if the slot is stored anywhere in the loop.
499 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000500 if (Candidates[i].FI != INT_MIN &&
501 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000502 continue;
503
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000504 if (PhysRegDefs[Candidates[i].Def] == 1) {
505 bool Safe = true;
506 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000507 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
508 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000509 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000510 continue;
511 if (PhysRegDefs[MO.getReg()]) {
512 // If it's using a non-loop-invariant register, then it's obviously
513 // not safe to hoist.
514 Safe = false;
515 break;
516 }
517 }
518 if (Safe)
519 HoistPostRA(MI, Candidates[i].Def);
520 }
Evan Chengd94671a2010-04-07 00:41:17 +0000521 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000522
523 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000524}
525
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000526/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
527/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000528void MachineLICM::AddToLiveIns(unsigned Reg) {
529 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000530 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
531 MachineBasicBlock *BB = Blocks[i];
532 if (!BB->isLiveIn(Reg))
533 BB->addLiveIn(Reg);
534 for (MachineBasicBlock::iterator
535 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
536 MachineInstr *MI = &*MII;
537 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
538 MachineOperand &MO = MI->getOperand(i);
539 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
540 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
541 MO.setIsKill(false);
542 }
543 }
544 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000545}
546
547/// HoistPostRA - When an instruction is found to only use loop invariant
548/// operands that is safe to hoist, this instruction is called to do the
549/// dirty work.
550void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000551 MachineBasicBlock *Preheader = getCurPreheader();
552 if (!Preheader) return;
553
Evan Chengd94671a2010-04-07 00:41:17 +0000554 // Now move the instructions to the predecessor, inserting it before any
555 // terminator instructions.
556 DEBUG({
557 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000558 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000559 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000560 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000561 if (MI->getParent()->getBasicBlock())
562 dbgs() << " from MachineBasicBlock "
563 << MI->getParent()->getName();
564 dbgs() << "\n";
565 });
566
567 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000568 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000569 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000570
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000571 // Add register to livein list to all the BBs in the current loop since a
572 // loop invariant must be kept live throughout the whole loop. This is
573 // important to ensure later passes do not scavenge the def register.
574 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000575
576 ++NumPostRAHoisted;
577 Changed = true;
578}
579
Devang Patel2e350472011-10-11 18:09:58 +0000580// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
581// If not then a load from this mbb may not be safe to hoist.
582bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengfad62872011-10-11 23:48:44 +0000583 if (SpeculationState != SpeculateUnknown)
584 return SpeculationState == SpeculateFalse;
585
Devang Patel2e350472011-10-11 18:09:58 +0000586 if (BB != CurLoop->getHeader()) {
587 // Check loop exiting blocks.
588 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
589 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
590 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
591 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Evan Chengfad62872011-10-11 23:48:44 +0000592 SpeculationState = SpeculateTrue;
593 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000594 }
595 }
596
Evan Chengfad62872011-10-11 23:48:44 +0000597 SpeculationState = SpeculateFalse;
598 return true;
Devang Patel2e350472011-10-11 18:09:58 +0000599}
600
Bill Wendling0f940c92007-12-07 21:42:31 +0000601/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
602/// dominated by the specified block, and that are in the current loop) in depth
603/// first order w.r.t the DominatorTree. This allows us to visit definitions
604/// before uses, allowing us to hoist a loop body in one pass without iteration.
605///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000606void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000607 assert(N != 0 && "Null dominator tree node?");
608 MachineBasicBlock *BB = N->getBlock();
609
610 // If this subregion is not in the top level loop at all, exit.
611 if (!CurLoop->contains(BB)) return;
612
Evan Cheng0e673912010-10-14 01:16:09 +0000613 MachineBasicBlock *Preheader = getCurPreheader();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000614 if (!Preheader)
615 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000616
Evan Cheng23128422010-10-19 18:58:51 +0000617 if (IsHeader) {
Evan Cheng134982d2010-10-20 22:03:58 +0000618 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000619 RegSeen.clear();
620 BackTrace.clear();
621 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000622 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000623
Evan Cheng23128422010-10-19 18:58:51 +0000624 // Remember livein register pressure.
625 BackTrace.push_back(RegPressure);
626
Evan Chengfad62872011-10-11 23:48:44 +0000627 SpeculationState = SpeculateUnknown;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000628 for (MachineBasicBlock::iterator
629 MII = BB->begin(), E = BB->end(); MII != E; ) {
630 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
631 MachineInstr *MI = &*MII;
Evan Cheng134982d2010-10-20 22:03:58 +0000632 if (!Hoist(MI, Preheader))
633 UpdateRegPressure(MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000634 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000635 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000636
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000637 // Don't hoist things out of a large switch statement. This often causes
638 // code to be hoisted that wasn't going to be executed, and increases
639 // register pressure in a situation where it's likely to matter.
Dale Johannesen21d35c12010-07-20 21:29:12 +0000640 if (BB->succ_size() < 25) {
641 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000642 for (unsigned I = 0, E = Children.size(); I != E; ++I)
643 HoistRegion(Children[I]);
Dale Johannesen21d35c12010-07-20 21:29:12 +0000644 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000645
Evan Cheng23128422010-10-19 18:58:51 +0000646 BackTrace.pop_back();
Bill Wendling0f940c92007-12-07 21:42:31 +0000647}
648
Evan Cheng134982d2010-10-20 22:03:58 +0000649static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
650 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
651}
652
Evan Cheng61560e22011-09-01 01:45:00 +0000653/// getRegisterClassIDAndCost - For a given MI, register, and the operand
654/// index, return the ID and cost of its representative register class.
655void
656MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
657 unsigned Reg, unsigned OpIdx,
658 unsigned &RCId, unsigned &RCCost) const {
659 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
660 EVT VT = *RC->vt_begin();
661 if (VT == MVT::untyped) {
662 RCId = RC->getID();
663 RCCost = 1;
664 } else {
665 RCId = TLI->getRepRegClassFor(VT)->getID();
666 RCCost = TLI->getRepRegClassCostFor(VT);
667 }
668}
669
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000670/// InitRegPressure - Find all virtual register references that are liveout of
671/// the preheader to initialize the starting "register pressure". Note this
672/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000673void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000674 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000675
Evan Cheng134982d2010-10-20 22:03:58 +0000676 // If the preheader has only a single predecessor and it ends with a
677 // fallthrough or an unconditional branch, then scan its predecessor for live
678 // defs as well. This happens whenever the preheader is created by splitting
679 // the critical edge from the loop predecessor to the loop header.
680 if (BB->pred_size() == 1) {
681 MachineBasicBlock *TBB = 0, *FBB = 0;
682 SmallVector<MachineOperand, 4> Cond;
683 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
684 InitRegPressure(*BB->pred_begin());
685 }
686
Evan Cheng0e673912010-10-14 01:16:09 +0000687 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
688 MII != E; ++MII) {
689 MachineInstr *MI = &*MII;
690 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
691 const MachineOperand &MO = MI->getOperand(i);
692 if (!MO.isReg() || MO.isImplicit())
693 continue;
694 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000695 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000696 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000697
Andrew Trickdc986d22010-10-19 02:50:50 +0000698 bool isNew = RegSeen.insert(Reg);
Evan Cheng61560e22011-09-01 01:45:00 +0000699 unsigned RCId, RCCost;
700 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000701 if (MO.isDef())
Evan Cheng61560e22011-09-01 01:45:00 +0000702 RegPressure[RCId] += RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000703 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000704 bool isKill = isOperandKill(MO, MRI);
705 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000706 // Haven't seen this, it must be a livein.
Evan Cheng61560e22011-09-01 01:45:00 +0000707 RegPressure[RCId] += RCCost;
Evan Cheng134982d2010-10-20 22:03:58 +0000708 else if (!isNew && isKill)
Evan Cheng61560e22011-09-01 01:45:00 +0000709 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000710 }
Evan Cheng0e673912010-10-14 01:16:09 +0000711 }
712 }
713}
714
Evan Cheng134982d2010-10-20 22:03:58 +0000715/// UpdateRegPressure - Update estimate of register pressure after the
716/// specified instruction.
717void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
718 if (MI->isImplicitDef())
719 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000720
Evan Cheng134982d2010-10-20 22:03:58 +0000721 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000722 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
723 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000724 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000725 continue;
726 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000727 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000728 continue;
729
Andrew Trickdc986d22010-10-19 02:50:50 +0000730 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000731 if (MO.isDef())
732 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000733 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng61560e22011-09-01 01:45:00 +0000734 unsigned RCId, RCCost;
735 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000736 if (RCCost > RegPressure[RCId])
737 RegPressure[RCId] = 0;
738 else
Evan Cheng23128422010-10-19 18:58:51 +0000739 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000740 }
Evan Cheng0e673912010-10-14 01:16:09 +0000741 }
Evan Cheng0e673912010-10-14 01:16:09 +0000742
Evan Cheng61560e22011-09-01 01:45:00 +0000743 unsigned Idx = 0;
Evan Cheng23128422010-10-19 18:58:51 +0000744 while (!Defs.empty()) {
745 unsigned Reg = Defs.pop_back_val();
Evan Cheng61560e22011-09-01 01:45:00 +0000746 unsigned RCId, RCCost;
747 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Cheng0e673912010-10-14 01:16:09 +0000748 RegPressure[RCId] += RCCost;
Evan Cheng61560e22011-09-01 01:45:00 +0000749 ++Idx;
Evan Cheng0e673912010-10-14 01:16:09 +0000750 }
751}
752
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000753/// IsLICMCandidate - Returns true if the instruction may be a suitable
754/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
755/// not safe to hoist it.
756bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000757 // Check if it's safe to move the instruction.
758 bool DontMoveAcrossStore = true;
759 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000760 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000761
762 // If it is load then check if it is guaranteed to execute by making sure that
763 // it dominates all exiting blocks. If it doesn't, then there is a path out of
764 // the loop which does not execute this load, so we can't hoist it.
765 // Stores and side effects are already checked by isSafeToMove.
766 if (I.getDesc().mayLoad() && !IsGuaranteedToExecute(I.getParent()))
767 return false;
768
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000769 return true;
770}
771
772/// IsLoopInvariantInst - Returns true if the instruction is loop
773/// invariant. I.e., all virtual register operands are defined outside of the
774/// loop, physical registers aren't accessed explicitly, and there are no side
775/// effects that aren't captured by the operands or other flags.
776///
777bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
778 if (!IsLICMCandidate(I))
779 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000780
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000781 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000782 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
783 const MachineOperand &MO = I.getOperand(i);
784
Dan Gohmand735b802008-10-03 15:45:36 +0000785 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000786 continue;
787
Dan Gohmanc475c362009-01-15 22:01:38 +0000788 unsigned Reg = MO.getReg();
789 if (Reg == 0) continue;
790
791 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000792 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000793 if (MO.isUse()) {
794 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000795 // and we can freely move its uses. Alternatively, if it's allocatable,
796 // it could get allocated to something with a def during allocation.
Evan Cheng0e673912010-10-14 01:16:09 +0000797 if (!MRI->def_empty(Reg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000798 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000799 if (AllocatableSet.test(Reg))
800 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000801 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000802 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
803 unsigned AliasReg = *Alias;
Evan Cheng0e673912010-10-14 01:16:09 +0000804 if (!MRI->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000805 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000806 if (AllocatableSet.test(AliasReg))
807 return false;
808 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000809 // Otherwise it's safe to move.
810 continue;
811 } else if (!MO.isDead()) {
812 // A def that isn't dead. We can't move it.
813 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000814 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
815 // If the reg is live into the loop, we can't hoist an instruction
816 // which would clobber it.
817 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000818 }
819 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000820
821 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000822 continue;
823
Evan Cheng0e673912010-10-14 01:16:09 +0000824 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000825 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000826
827 // If the loop contains the definition of an operand, then the instruction
828 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000829 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000830 return false;
831 }
832
833 // If we got this far, the instruction is loop invariant!
834 return true;
835}
836
Evan Chengaf6949d2009-02-05 08:45:46 +0000837
Evan Chengd67705f2011-04-11 21:09:18 +0000838/// HasAnyPHIUse - Return true if the specified register is used by any
839/// phi node.
840bool MachineLICM::HasAnyPHIUse(unsigned Reg) const {
Evan Cheng0e673912010-10-14 01:16:09 +0000841 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
842 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000843 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000844 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000845 return true;
Evan Chengd67705f2011-04-11 21:09:18 +0000846 // Look pass copies as well.
847 if (UseMI->isCopy()) {
848 unsigned Def = UseMI->getOperand(0).getReg();
849 if (TargetRegisterInfo::isVirtualRegister(Def) &&
850 HasAnyPHIUse(Def))
851 return true;
852 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000853 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000854 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000855}
856
Evan Cheng23128422010-10-19 18:58:51 +0000857/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
858/// and an use in the current loop, return true if the target considered
859/// it 'high'.
860bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +0000861 unsigned DefIdx, unsigned Reg) const {
862 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000863 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000864
Evan Cheng0e673912010-10-14 01:16:09 +0000865 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
866 E = MRI->use_nodbg_end(); I != E; ++I) {
867 MachineInstr *UseMI = &*I;
Evan Chengc8141df2010-10-26 02:08:50 +0000868 if (UseMI->isCopyLike())
869 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000870 if (!CurLoop->contains(UseMI->getParent()))
871 continue;
872 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
873 const MachineOperand &MO = UseMI->getOperand(i);
874 if (!MO.isReg() || !MO.isUse())
875 continue;
876 unsigned MOReg = MO.getReg();
877 if (MOReg != Reg)
878 continue;
879
Evan Cheng23128422010-10-19 18:58:51 +0000880 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
881 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000882 }
883
Evan Cheng23128422010-10-19 18:58:51 +0000884 // Only look at the first in loop use.
885 break;
Evan Cheng0e673912010-10-14 01:16:09 +0000886 }
887
Evan Cheng23128422010-10-19 18:58:51 +0000888 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000889}
890
Evan Chengc8141df2010-10-26 02:08:50 +0000891/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
892/// the operand latency between its def and a use is one or less.
893bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
894 if (MI.getDesc().isAsCheapAsAMove() || MI.isCopyLike())
895 return true;
896 if (!InstrItins || InstrItins->isEmpty())
897 return false;
898
899 bool isCheap = false;
900 unsigned NumDefs = MI.getDesc().getNumDefs();
901 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
902 MachineOperand &DefMO = MI.getOperand(i);
903 if (!DefMO.isReg() || !DefMO.isDef())
904 continue;
905 --NumDefs;
906 unsigned Reg = DefMO.getReg();
907 if (TargetRegisterInfo::isPhysicalRegister(Reg))
908 continue;
909
910 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
911 return false;
912 isCheap = true;
913 }
914
915 return isCheap;
916}
917
Evan Cheng134982d2010-10-20 22:03:58 +0000918/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000919/// if hoisting an instruction of the given cost matrix can cause high
920/// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000921bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
922 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
923 CI != CE; ++CI) {
924 if (CI->second <= 0)
925 continue;
926
927 unsigned RCId = CI->first;
928 for (unsigned i = BackTrace.size(); i != 0; --i) {
929 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000930 if (RP[RCId] + CI->second >= RegLimit[RCId])
931 return true;
932 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000933 }
934
935 return false;
936}
937
Evan Cheng134982d2010-10-20 22:03:58 +0000938/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
939/// current block and update their register pressures to reflect the effect
940/// of hoisting MI from the current block to the preheader.
941void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
942 if (MI->isImplicitDef())
943 return;
944
945 // First compute the 'cost' of the instruction, i.e. its contribution
946 // to register pressure.
947 DenseMap<unsigned, int> Cost;
948 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
949 const MachineOperand &MO = MI->getOperand(i);
950 if (!MO.isReg() || MO.isImplicit())
951 continue;
952 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000953 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng134982d2010-10-20 22:03:58 +0000954 continue;
955
Evan Cheng61560e22011-09-01 01:45:00 +0000956 unsigned RCId, RCCost;
957 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000958 if (MO.isDef()) {
959 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
960 if (CI != Cost.end())
961 CI->second += RCCost;
962 else
963 Cost.insert(std::make_pair(RCId, RCCost));
964 } else if (isOperandKill(MO, MRI)) {
965 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
966 if (CI != Cost.end())
967 CI->second -= RCCost;
968 else
969 Cost.insert(std::make_pair(RCId, -RCCost));
970 }
971 }
972
973 // Update register pressure of blocks from loop header to current block.
974 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
975 SmallVector<unsigned, 8> &RP = BackTrace[i];
976 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
977 CI != CE; ++CI) {
978 unsigned RCId = CI->first;
979 RP[RCId] += CI->second;
980 }
981 }
982}
983
Evan Cheng45e94d62009-02-04 09:19:56 +0000984/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
985/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000986bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +0000987 if (MI.isImplicitDef())
988 return true;
989
Evan Cheng23128422010-10-19 18:58:51 +0000990 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
991 // will increase register pressure. It's probably not worth it if the
992 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000993 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
994 // these tend to help performance in low register pressure situation. The
995 // trade off is it may cause spill in high pressure situation. It will end up
996 // adding a store in the loop preheader. But the reload is no more expensive.
997 // The side benefit is these loads are frequently CSE'ed.
Evan Chengc8141df2010-10-26 02:08:50 +0000998 if (IsCheapInstruction(MI)) {
Evan Cheng23128422010-10-19 18:58:51 +0000999 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +00001000 return false;
1001 } else {
Evan Cheng23128422010-10-19 18:58:51 +00001002 // Estimate register pressure to determine whether to LICM the instruction.
Evan Cheng0e673912010-10-14 01:16:09 +00001003 // In low register pressure situation, we can be more aggressive about
1004 // hoisting. Also, favors hoisting long latency instructions even in
1005 // moderately high pressure situation.
Dan Gohmanfca0b102010-11-11 18:08:43 +00001006 // FIXME: If there are long latency loop-invariant instructions inside the
1007 // loop at this point, why didn't the optimizer's LICM hoist them?
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001008 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +00001009 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1010 const MachineOperand &MO = MI.getOperand(i);
1011 if (!MO.isReg() || MO.isImplicit())
1012 continue;
1013 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +00001014 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +00001015 continue;
Evan Cheng61560e22011-09-01 01:45:00 +00001016
1017 unsigned RCId, RCCost;
1018 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001019 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +00001020 if (HasHighOperandLatency(MI, i, Reg)) {
1021 ++NumHighLatency;
1022 return true;
Evan Cheng0e673912010-10-14 01:16:09 +00001023 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001024
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001025 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001026 if (CI != Cost.end())
1027 CI->second += RCCost;
1028 else
1029 Cost.insert(std::make_pair(RCId, RCCost));
Evan Cheng134982d2010-10-20 22:03:58 +00001030 } else if (isOperandKill(MO, MRI)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001031 // Is a virtual register use is a kill, hoisting it out of the loop
1032 // may actually reduce register pressure or be register pressure
Evan Cheng134982d2010-10-20 22:03:58 +00001033 // neutral.
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001034 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1035 if (CI != Cost.end())
1036 CI->second -= RCCost;
1037 else
1038 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +00001039 }
1040 }
1041
Evan Cheng134982d2010-10-20 22:03:58 +00001042 // Visit BBs from header to current BB, if hoisting this doesn't cause
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001043 // high register pressure, then it's safe to proceed.
Evan Cheng134982d2010-10-20 22:03:58 +00001044 if (!CanCauseHighRegPressure(Cost)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001045 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +00001046 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001047 }
Evan Cheng0e673912010-10-14 01:16:09 +00001048
1049 // High register pressure situation, only hoist if the instruction is going to
1050 // be remat'ed.
Evan Chengfad62872011-10-11 23:48:44 +00001051 // Also, do not "speculate" in high register pressure situation. If an
1052 // instruction is not guaranteed to be executed in the loop, it's best to be
1053 // conservative.
Evan Cheng7efba852011-10-12 00:09:14 +00001054 if ((!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI)) ||
Evan Chengfad62872011-10-11 23:48:44 +00001055 (!TII->isTriviallyReMaterializable(&MI, AA) &&
1056 !MI.isInvariantLoad(AA)))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001057 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001058 }
Evan Cheng45e94d62009-02-04 09:19:56 +00001059
Evan Chengd67705f2011-04-11 21:09:18 +00001060 // If result(s) of this instruction is used by PHIs outside of the loop, then
1061 // don't hoist it if the instruction because it will introduce an extra copy.
Evan Cheng45e94d62009-02-04 09:19:56 +00001062 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1063 const MachineOperand &MO = MI.getOperand(i);
1064 if (!MO.isReg() || !MO.isDef())
1065 continue;
Evan Chengd67705f2011-04-11 21:09:18 +00001066 if (HasAnyPHIUse(MO.getReg()))
Evan Chengaf6949d2009-02-05 08:45:46 +00001067 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +00001068 }
Evan Chengaf6949d2009-02-05 08:45:46 +00001069
1070 return true;
1071}
1072
Dan Gohman5c952302009-10-29 17:47:20 +00001073MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001074 // Don't unfold simple loads.
1075 if (MI->getDesc().canFoldAsLoad())
1076 return 0;
1077
Dan Gohman5c952302009-10-29 17:47:20 +00001078 // If not, we may be able to unfold a load and hoist that.
1079 // First test whether the instruction is loading from an amenable
1080 // memory location.
Evan Cheng9fe20092011-01-20 08:34:58 +00001081 if (!MI->isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001082 return 0;
1083
Dan Gohman5c952302009-10-29 17:47:20 +00001084 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001085 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001086 unsigned NewOpc =
1087 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1088 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001089 /*UnfoldStore=*/false,
1090 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001091 if (NewOpc == 0) return 0;
Evan Chenge837dea2011-06-28 19:10:37 +00001092 const MCInstrDesc &MID = TII->get(NewOpc);
1093 if (MID.getNumDefs() != 1) return 0;
1094 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001095 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001096 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001097
1098 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001099 SmallVector<MachineInstr *, 2> NewMIs;
1100 bool Success =
1101 TII->unfoldMemoryOperand(MF, MI, Reg,
1102 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1103 NewMIs);
1104 (void)Success;
1105 assert(Success &&
1106 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1107 "succeeded!");
1108 assert(NewMIs.size() == 2 &&
1109 "Unfolded a load into multiple instructions!");
1110 MachineBasicBlock *MBB = MI->getParent();
1111 MBB->insert(MI, NewMIs[0]);
1112 MBB->insert(MI, NewMIs[1]);
1113 // If unfolding produced a load that wasn't loop-invariant or profitable to
1114 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001115 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001116 NewMIs[0]->eraseFromParent();
1117 NewMIs[1]->eraseFromParent();
1118 return 0;
1119 }
Evan Cheng134982d2010-10-20 22:03:58 +00001120
1121 // Update register pressure for the unfolded instruction.
1122 UpdateRegPressure(NewMIs[1]);
1123
Dan Gohman5c952302009-10-29 17:47:20 +00001124 // Otherwise we successfully unfolded a load that we can hoist.
1125 MI->eraseFromParent();
1126 return NewMIs[0];
1127}
1128
Evan Cheng777c6b72009-11-03 21:40:02 +00001129void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1130 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1131 const MachineInstr *MI = &*I;
Evan Cheng9fe20092011-01-20 08:34:58 +00001132 unsigned Opcode = MI->getOpcode();
1133 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1134 CI = CSEMap.find(Opcode);
1135 if (CI != CSEMap.end())
1136 CI->second.push_back(MI);
1137 else {
1138 std::vector<const MachineInstr*> CSEMIs;
1139 CSEMIs.push_back(MI);
1140 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Cheng777c6b72009-11-03 21:40:02 +00001141 }
1142 }
1143}
1144
Evan Cheng78e5c112009-11-07 03:52:02 +00001145const MachineInstr*
1146MachineLICM::LookForDuplicate(const MachineInstr *MI,
1147 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001148 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1149 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng9fe20092011-01-20 08:34:58 +00001150 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001151 return PrevMI;
1152 }
1153 return 0;
1154}
1155
1156bool MachineLICM::EliminateCSE(MachineInstr *MI,
1157 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001158 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1159 // the undef property onto uses.
1160 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001161 return false;
1162
1163 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001164 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001165
1166 // Replace virtual registers defined by MI by their counterparts defined
1167 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +00001168 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1169 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001170
1171 // Physical registers may not differ here.
1172 assert((!MO.isReg() || MO.getReg() == 0 ||
1173 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1174 MO.getReg() == Dup->getOperand(i).getReg()) &&
1175 "Instructions with different phys regs are not identical!");
1176
1177 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +00001178 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng0e673912010-10-14 01:16:09 +00001179 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1180 MRI->clearKillFlags(Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001181 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001182 }
Evan Cheng78e5c112009-11-07 03:52:02 +00001183 MI->eraseFromParent();
1184 ++NumCSEed;
1185 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001186 }
1187 return false;
1188}
1189
Evan Cheng7efba852011-10-12 00:09:14 +00001190/// MayCSE - Return true if the given instruction will be CSE'd if it's
1191/// hoisted out of the loop.
1192bool MachineLICM::MayCSE(MachineInstr *MI) {
1193 unsigned Opcode = MI->getOpcode();
1194 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1195 CI = CSEMap.find(Opcode);
1196 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1197 // the undef property onto uses.
1198 if (CI == CSEMap.end() || MI->isImplicitDef())
1199 return false;
1200
1201 return LookForDuplicate(MI, CI->second) != 0;
1202}
1203
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001204/// Hoist - When an instruction is found to use only loop invariant operands
1205/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001206///
Evan Cheng134982d2010-10-20 22:03:58 +00001207bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001208 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001209 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001210 // If not, try unfolding a hoistable load.
1211 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001212 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001213 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001214
Dan Gohmanc475c362009-01-15 22:01:38 +00001215 // Now move the instructions to the predecessor, inserting it before any
1216 // terminator instructions.
1217 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001218 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001219 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001220 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001221 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001222 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001223 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001224 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001225 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001226 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001227
Evan Cheng777c6b72009-11-03 21:40:02 +00001228 // If this is the first instruction being hoisted to the preheader,
1229 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001230 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001231 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001232 FirstInLoop = false;
1233 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001234
Evan Chengaf6949d2009-02-05 08:45:46 +00001235 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001236 unsigned Opcode = MI->getOpcode();
1237 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1238 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001239 if (!EliminateCSE(MI, CI)) {
1240 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001241 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001242
Evan Cheng134982d2010-10-20 22:03:58 +00001243 // Update register pressure for BBs from header to this block.
1244 UpdateBackTraceRegPressure(MI);
1245
Dan Gohmane6cd7572010-05-13 20:34:42 +00001246 // Clear the kill flags of any register this instruction defines,
1247 // since they may need to be live throughout the entire loop
1248 // rather than just live for part of it.
1249 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1250 MachineOperand &MO = MI->getOperand(i);
1251 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001252 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001253 }
1254
Evan Chengaf6949d2009-02-05 08:45:46 +00001255 // Add to the CSE map.
1256 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001257 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001258 else {
1259 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001260 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001261 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001262 }
1263 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001264
Dan Gohmanc475c362009-01-15 22:01:38 +00001265 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001266 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001267
1268 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001269}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001270
1271MachineBasicBlock *MachineLICM::getCurPreheader() {
1272 // Determine the block to which to hoist instructions. If we can't find a
1273 // suitable loop predecessor, we can't do any hoisting.
1274
1275 // If we've tried to get a preheader and failed, don't try again.
1276 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1277 return 0;
1278
1279 if (!CurPreheader) {
1280 CurPreheader = CurLoop->getLoopPreheader();
1281 if (!CurPreheader) {
1282 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1283 if (!Pred) {
1284 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1285 return 0;
1286 }
1287
1288 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1289 if (!CurPreheader) {
1290 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1291 return 0;
1292 }
1293 }
1294 }
1295 return CurPreheader;
1296}