blob: 889406a4869758939218a702936bfc9a71a49fd5 [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
Evan Chengd94671a2010-04-07 00:41:17 +0000346 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000347 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000348 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000349 // CSEMap is initialized for loop header when the first instruction is
350 // being hoisted.
351 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000352 FirstInLoop = true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000353 HoistRegion(N, true);
Evan Chengd94671a2010-04-07 00:41:17 +0000354 CSEMap.clear();
355 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000356 }
357
358 return Changed;
359}
360
Evan Cheng4038f9c2010-04-08 01:03:47 +0000361/// InstructionStoresToFI - Return true if instruction stores to the
362/// specified frame.
363static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
364 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
365 oe = MI->memoperands_end(); o != oe; ++o) {
366 if (!(*o)->isStore() || !(*o)->getValue())
367 continue;
368 if (const FixedStackPseudoSourceValue *Value =
369 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
370 if (Value->getFrameIndex() == FI)
371 return true;
372 }
373 }
374 return false;
375}
376
377/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
378/// gather register def and frame object update information.
379void MachineLICM::ProcessMI(MachineInstr *MI,
380 unsigned *PhysRegDefs,
381 SmallSet<int, 32> &StoredFIs,
382 SmallVector<CandidateInfo, 32> &Candidates) {
383 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000384 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000385 unsigned Def = 0;
386 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
387 const MachineOperand &MO = MI->getOperand(i);
388 if (MO.isFI()) {
389 // Remember if the instruction stores to the frame index.
390 int FI = MO.getIndex();
391 if (!StoredFIs.count(FI) &&
392 MFI->isSpillSlotObjectIndex(FI) &&
393 InstructionStoresToFI(MI, FI))
394 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000395 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000396 continue;
397 }
398
399 if (!MO.isReg())
400 continue;
401 unsigned Reg = MO.getReg();
402 if (!Reg)
403 continue;
404 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
405 "Not expecting virtual register!");
406
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000407 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000408 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000409 // If it's using a non-loop-invariant register, then it's obviously not
410 // safe to hoist.
411 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000412 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000413 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000414
415 if (MO.isImplicit()) {
416 ++PhysRegDefs[Reg];
417 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
418 ++PhysRegDefs[*AS];
419 if (!MO.isDead())
420 // Non-dead implicit def? This cannot be hoisted.
421 RuledOut = true;
422 // No need to check if a dead implicit def is also defined by
423 // another instruction.
424 continue;
425 }
426
427 // FIXME: For now, avoid instructions with multiple defs, unless
428 // it's a dead implicit def.
429 if (Def)
430 RuledOut = true;
431 else
432 Def = Reg;
433
434 // If we have already seen another instruction that defines the same
435 // register, then this is not safe.
436 if (++PhysRegDefs[Reg] > 1)
437 // MI defined register is seen defined by another instruction in
438 // the loop, it cannot be a LICM candidate.
439 RuledOut = true;
440 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
441 if (++PhysRegDefs[*AS] > 1)
442 RuledOut = true;
443 }
444
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000445 // Only consider reloads for now and remats which do not have register
446 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000447 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000448 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000449 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000450 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
451 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000452 }
453}
454
455/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
456/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000457void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000458 unsigned NumRegs = TRI->getNumRegs();
459 unsigned *PhysRegDefs = new unsigned[NumRegs];
460 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
461
Evan Cheng4038f9c2010-04-08 01:03:47 +0000462 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000463 SmallSet<int, 32> StoredFIs;
464
465 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000466 // collect potential LICM candidates.
467 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
468 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
469 MachineBasicBlock *BB = Blocks[i];
Bill Wendlinga2e87912011-10-12 02:58:01 +0000470
471 // If the header of the loop containing this basic block is a landing pad,
472 // then don't try to hoist instructions out of this loop.
473 const MachineLoop *ML = MLI->getLoopFor(BB);
474 if (ML && ML->getHeader()->isLandingPad()) continue;
475
Evan Chengd94671a2010-04-07 00:41:17 +0000476 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000477 // FIXME: That means a reload that're reused in successor block(s) will not
478 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000479 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000480 E = BB->livein_end(); I != E; ++I) {
481 unsigned Reg = *I;
482 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000483 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
484 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000485 }
486
Evan Chengfad62872011-10-11 23:48:44 +0000487 SpeculationState = SpeculateUnknown;
Evan Chengd94671a2010-04-07 00:41:17 +0000488 for (MachineBasicBlock::iterator
489 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000490 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000491 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000492 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000493 }
Evan Chengd94671a2010-04-07 00:41:17 +0000494
495 // Now evaluate whether the potential candidates qualify.
496 // 1. Check if the candidate defined register is defined by another
497 // instruction in the loop.
498 // 2. If the candidate is a load from stack slot (always true for now),
499 // check if the slot is stored anywhere in the loop.
500 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000501 if (Candidates[i].FI != INT_MIN &&
502 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000503 continue;
504
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000505 if (PhysRegDefs[Candidates[i].Def] == 1) {
506 bool Safe = true;
507 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000508 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
509 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000510 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000511 continue;
512 if (PhysRegDefs[MO.getReg()]) {
513 // If it's using a non-loop-invariant register, then it's obviously
514 // not safe to hoist.
515 Safe = false;
516 break;
517 }
518 }
519 if (Safe)
520 HoistPostRA(MI, Candidates[i].Def);
521 }
Evan Chengd94671a2010-04-07 00:41:17 +0000522 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000523
524 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000525}
526
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000527/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
528/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000529void MachineLICM::AddToLiveIns(unsigned Reg) {
530 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000531 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
532 MachineBasicBlock *BB = Blocks[i];
533 if (!BB->isLiveIn(Reg))
534 BB->addLiveIn(Reg);
535 for (MachineBasicBlock::iterator
536 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
537 MachineInstr *MI = &*MII;
538 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
539 MachineOperand &MO = MI->getOperand(i);
540 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
541 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
542 MO.setIsKill(false);
543 }
544 }
545 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000546}
547
548/// HoistPostRA - When an instruction is found to only use loop invariant
549/// operands that is safe to hoist, this instruction is called to do the
550/// dirty work.
551void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000552 MachineBasicBlock *Preheader = getCurPreheader();
553 if (!Preheader) return;
554
Evan Chengd94671a2010-04-07 00:41:17 +0000555 // Now move the instructions to the predecessor, inserting it before any
556 // terminator instructions.
557 DEBUG({
558 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000559 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000560 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000561 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000562 if (MI->getParent()->getBasicBlock())
563 dbgs() << " from MachineBasicBlock "
564 << MI->getParent()->getName();
565 dbgs() << "\n";
566 });
567
568 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000569 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000570 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000571
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000572 // Add register to livein list to all the BBs in the current loop since a
573 // loop invariant must be kept live throughout the whole loop. This is
574 // important to ensure later passes do not scavenge the def register.
575 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000576
577 ++NumPostRAHoisted;
578 Changed = true;
579}
580
Devang Patel2e350472011-10-11 18:09:58 +0000581// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
582// If not then a load from this mbb may not be safe to hoist.
583bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengfad62872011-10-11 23:48:44 +0000584 if (SpeculationState != SpeculateUnknown)
585 return SpeculationState == SpeculateFalse;
586
Devang Patel2e350472011-10-11 18:09:58 +0000587 if (BB != CurLoop->getHeader()) {
588 // Check loop exiting blocks.
589 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
590 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
591 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
592 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Evan Chengfad62872011-10-11 23:48:44 +0000593 SpeculationState = SpeculateTrue;
594 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000595 }
596 }
597
Evan Chengfad62872011-10-11 23:48:44 +0000598 SpeculationState = SpeculateFalse;
599 return true;
Devang Patel2e350472011-10-11 18:09:58 +0000600}
601
Bill Wendling0f940c92007-12-07 21:42:31 +0000602/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
603/// dominated by the specified block, and that are in the current loop) in depth
604/// first order w.r.t the DominatorTree. This allows us to visit definitions
605/// before uses, allowing us to hoist a loop body in one pass without iteration.
606///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000607void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000608 assert(N != 0 && "Null dominator tree node?");
609 MachineBasicBlock *BB = N->getBlock();
610
Bill Wendlinga2e87912011-10-12 02:58:01 +0000611 // If the header of the loop containing this basic block is a landing pad,
612 // then don't try to hoist instructions out of this loop.
613 const MachineLoop *ML = MLI->getLoopFor(BB);
614 if (ML && ML->getHeader()->isLandingPad()) return;
615
Bill Wendling0f940c92007-12-07 21:42:31 +0000616 // If this subregion is not in the top level loop at all, exit.
617 if (!CurLoop->contains(BB)) return;
618
Evan Cheng0e673912010-10-14 01:16:09 +0000619 MachineBasicBlock *Preheader = getCurPreheader();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000620 if (!Preheader)
621 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000622
Evan Cheng23128422010-10-19 18:58:51 +0000623 if (IsHeader) {
Evan Cheng134982d2010-10-20 22:03:58 +0000624 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000625 RegSeen.clear();
626 BackTrace.clear();
627 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000628 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000629
Evan Cheng23128422010-10-19 18:58:51 +0000630 // Remember livein register pressure.
631 BackTrace.push_back(RegPressure);
632
Evan Chengfad62872011-10-11 23:48:44 +0000633 SpeculationState = SpeculateUnknown;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000634 for (MachineBasicBlock::iterator
635 MII = BB->begin(), E = BB->end(); MII != E; ) {
636 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
637 MachineInstr *MI = &*MII;
Evan Cheng134982d2010-10-20 22:03:58 +0000638 if (!Hoist(MI, Preheader))
639 UpdateRegPressure(MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000640 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000641 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000642
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000643 // Don't hoist things out of a large switch statement. This often causes
644 // code to be hoisted that wasn't going to be executed, and increases
645 // register pressure in a situation where it's likely to matter.
Dale Johannesen21d35c12010-07-20 21:29:12 +0000646 if (BB->succ_size() < 25) {
647 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000648 for (unsigned I = 0, E = Children.size(); I != E; ++I)
649 HoistRegion(Children[I]);
Dale Johannesen21d35c12010-07-20 21:29:12 +0000650 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000651
Evan Cheng23128422010-10-19 18:58:51 +0000652 BackTrace.pop_back();
Bill Wendling0f940c92007-12-07 21:42:31 +0000653}
654
Evan Cheng134982d2010-10-20 22:03:58 +0000655static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
656 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
657}
658
Evan Cheng61560e22011-09-01 01:45:00 +0000659/// getRegisterClassIDAndCost - For a given MI, register, and the operand
660/// index, return the ID and cost of its representative register class.
661void
662MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
663 unsigned Reg, unsigned OpIdx,
664 unsigned &RCId, unsigned &RCCost) const {
665 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
666 EVT VT = *RC->vt_begin();
667 if (VT == MVT::untyped) {
668 RCId = RC->getID();
669 RCCost = 1;
670 } else {
671 RCId = TLI->getRepRegClassFor(VT)->getID();
672 RCCost = TLI->getRepRegClassCostFor(VT);
673 }
674}
675
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000676/// InitRegPressure - Find all virtual register references that are liveout of
677/// the preheader to initialize the starting "register pressure". Note this
678/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000679void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000680 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000681
Evan Cheng134982d2010-10-20 22:03:58 +0000682 // If the preheader has only a single predecessor and it ends with a
683 // fallthrough or an unconditional branch, then scan its predecessor for live
684 // defs as well. This happens whenever the preheader is created by splitting
685 // the critical edge from the loop predecessor to the loop header.
686 if (BB->pred_size() == 1) {
687 MachineBasicBlock *TBB = 0, *FBB = 0;
688 SmallVector<MachineOperand, 4> Cond;
689 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
690 InitRegPressure(*BB->pred_begin());
691 }
692
Evan Cheng0e673912010-10-14 01:16:09 +0000693 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
694 MII != E; ++MII) {
695 MachineInstr *MI = &*MII;
696 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
697 const MachineOperand &MO = MI->getOperand(i);
698 if (!MO.isReg() || MO.isImplicit())
699 continue;
700 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000701 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000702 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000703
Andrew Trickdc986d22010-10-19 02:50:50 +0000704 bool isNew = RegSeen.insert(Reg);
Evan Cheng61560e22011-09-01 01:45:00 +0000705 unsigned RCId, RCCost;
706 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000707 if (MO.isDef())
Evan Cheng61560e22011-09-01 01:45:00 +0000708 RegPressure[RCId] += RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000709 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000710 bool isKill = isOperandKill(MO, MRI);
711 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000712 // Haven't seen this, it must be a livein.
Evan Cheng61560e22011-09-01 01:45:00 +0000713 RegPressure[RCId] += RCCost;
Evan Cheng134982d2010-10-20 22:03:58 +0000714 else if (!isNew && isKill)
Evan Cheng61560e22011-09-01 01:45:00 +0000715 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000716 }
Evan Cheng0e673912010-10-14 01:16:09 +0000717 }
718 }
719}
720
Evan Cheng134982d2010-10-20 22:03:58 +0000721/// UpdateRegPressure - Update estimate of register pressure after the
722/// specified instruction.
723void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
724 if (MI->isImplicitDef())
725 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000726
Evan Cheng134982d2010-10-20 22:03:58 +0000727 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000728 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
729 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000730 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000731 continue;
732 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000733 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000734 continue;
735
Andrew Trickdc986d22010-10-19 02:50:50 +0000736 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000737 if (MO.isDef())
738 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000739 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng61560e22011-09-01 01:45:00 +0000740 unsigned RCId, RCCost;
741 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000742 if (RCCost > RegPressure[RCId])
743 RegPressure[RCId] = 0;
744 else
Evan Cheng23128422010-10-19 18:58:51 +0000745 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000746 }
Evan Cheng0e673912010-10-14 01:16:09 +0000747 }
Evan Cheng0e673912010-10-14 01:16:09 +0000748
Evan Cheng61560e22011-09-01 01:45:00 +0000749 unsigned Idx = 0;
Evan Cheng23128422010-10-19 18:58:51 +0000750 while (!Defs.empty()) {
751 unsigned Reg = Defs.pop_back_val();
Evan Cheng61560e22011-09-01 01:45:00 +0000752 unsigned RCId, RCCost;
753 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Cheng0e673912010-10-14 01:16:09 +0000754 RegPressure[RCId] += RCCost;
Evan Cheng61560e22011-09-01 01:45:00 +0000755 ++Idx;
Evan Cheng0e673912010-10-14 01:16:09 +0000756 }
757}
758
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000759/// IsLICMCandidate - Returns true if the instruction may be a suitable
760/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
761/// not safe to hoist it.
762bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000763 // Check if it's safe to move the instruction.
764 bool DontMoveAcrossStore = true;
765 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000766 return false;
Devang Patel2e350472011-10-11 18:09:58 +0000767
768 // If it is load then check if it is guaranteed to execute by making sure that
769 // it dominates all exiting blocks. If it doesn't, then there is a path out of
770 // the loop which does not execute this load, so we can't hoist it.
771 // Stores and side effects are already checked by isSafeToMove.
772 if (I.getDesc().mayLoad() && !IsGuaranteedToExecute(I.getParent()))
773 return false;
774
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000775 return true;
776}
777
778/// IsLoopInvariantInst - Returns true if the instruction is loop
779/// invariant. I.e., all virtual register operands are defined outside of the
780/// loop, physical registers aren't accessed explicitly, and there are no side
781/// effects that aren't captured by the operands or other flags.
782///
783bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
784 if (!IsLICMCandidate(I))
785 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000786
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000787 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000788 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
789 const MachineOperand &MO = I.getOperand(i);
790
Dan Gohmand735b802008-10-03 15:45:36 +0000791 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000792 continue;
793
Dan Gohmanc475c362009-01-15 22:01:38 +0000794 unsigned Reg = MO.getReg();
795 if (Reg == 0) continue;
796
797 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000798 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000799 if (MO.isUse()) {
800 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000801 // and we can freely move its uses. Alternatively, if it's allocatable,
802 // it could get allocated to something with a def during allocation.
Evan Cheng0e673912010-10-14 01:16:09 +0000803 if (!MRI->def_empty(Reg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000804 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000805 if (AllocatableSet.test(Reg))
806 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000807 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000808 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
809 unsigned AliasReg = *Alias;
Evan Cheng0e673912010-10-14 01:16:09 +0000810 if (!MRI->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000811 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000812 if (AllocatableSet.test(AliasReg))
813 return false;
814 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000815 // Otherwise it's safe to move.
816 continue;
817 } else if (!MO.isDead()) {
818 // A def that isn't dead. We can't move it.
819 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000820 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
821 // If the reg is live into the loop, we can't hoist an instruction
822 // which would clobber it.
823 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000824 }
825 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000826
827 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000828 continue;
829
Evan Cheng0e673912010-10-14 01:16:09 +0000830 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000831 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000832
833 // If the loop contains the definition of an operand, then the instruction
834 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000835 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000836 return false;
837 }
838
839 // If we got this far, the instruction is loop invariant!
840 return true;
841}
842
Evan Chengaf6949d2009-02-05 08:45:46 +0000843
Evan Chengd67705f2011-04-11 21:09:18 +0000844/// HasAnyPHIUse - Return true if the specified register is used by any
845/// phi node.
846bool MachineLICM::HasAnyPHIUse(unsigned Reg) const {
Evan Cheng0e673912010-10-14 01:16:09 +0000847 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
848 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000849 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000850 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000851 return true;
Evan Chengd67705f2011-04-11 21:09:18 +0000852 // Look pass copies as well.
853 if (UseMI->isCopy()) {
854 unsigned Def = UseMI->getOperand(0).getReg();
855 if (TargetRegisterInfo::isVirtualRegister(Def) &&
856 HasAnyPHIUse(Def))
857 return true;
858 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000859 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000860 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000861}
862
Evan Cheng23128422010-10-19 18:58:51 +0000863/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
864/// and an use in the current loop, return true if the target considered
865/// it 'high'.
866bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +0000867 unsigned DefIdx, unsigned Reg) const {
868 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000869 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000870
Evan Cheng0e673912010-10-14 01:16:09 +0000871 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
872 E = MRI->use_nodbg_end(); I != E; ++I) {
873 MachineInstr *UseMI = &*I;
Evan Chengc8141df2010-10-26 02:08:50 +0000874 if (UseMI->isCopyLike())
875 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000876 if (!CurLoop->contains(UseMI->getParent()))
877 continue;
878 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
879 const MachineOperand &MO = UseMI->getOperand(i);
880 if (!MO.isReg() || !MO.isUse())
881 continue;
882 unsigned MOReg = MO.getReg();
883 if (MOReg != Reg)
884 continue;
885
Evan Cheng23128422010-10-19 18:58:51 +0000886 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
887 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000888 }
889
Evan Cheng23128422010-10-19 18:58:51 +0000890 // Only look at the first in loop use.
891 break;
Evan Cheng0e673912010-10-14 01:16:09 +0000892 }
893
Evan Cheng23128422010-10-19 18:58:51 +0000894 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000895}
896
Evan Chengc8141df2010-10-26 02:08:50 +0000897/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
898/// the operand latency between its def and a use is one or less.
899bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
900 if (MI.getDesc().isAsCheapAsAMove() || MI.isCopyLike())
901 return true;
902 if (!InstrItins || InstrItins->isEmpty())
903 return false;
904
905 bool isCheap = false;
906 unsigned NumDefs = MI.getDesc().getNumDefs();
907 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
908 MachineOperand &DefMO = MI.getOperand(i);
909 if (!DefMO.isReg() || !DefMO.isDef())
910 continue;
911 --NumDefs;
912 unsigned Reg = DefMO.getReg();
913 if (TargetRegisterInfo::isPhysicalRegister(Reg))
914 continue;
915
916 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
917 return false;
918 isCheap = true;
919 }
920
921 return isCheap;
922}
923
Evan Cheng134982d2010-10-20 22:03:58 +0000924/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000925/// if hoisting an instruction of the given cost matrix can cause high
926/// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000927bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
928 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
929 CI != CE; ++CI) {
930 if (CI->second <= 0)
931 continue;
932
933 unsigned RCId = CI->first;
934 for (unsigned i = BackTrace.size(); i != 0; --i) {
935 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000936 if (RP[RCId] + CI->second >= RegLimit[RCId])
937 return true;
938 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000939 }
940
941 return false;
942}
943
Evan Cheng134982d2010-10-20 22:03:58 +0000944/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
945/// current block and update their register pressures to reflect the effect
946/// of hoisting MI from the current block to the preheader.
947void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
948 if (MI->isImplicitDef())
949 return;
950
951 // First compute the 'cost' of the instruction, i.e. its contribution
952 // to register pressure.
953 DenseMap<unsigned, int> Cost;
954 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
955 const MachineOperand &MO = MI->getOperand(i);
956 if (!MO.isReg() || MO.isImplicit())
957 continue;
958 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000959 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng134982d2010-10-20 22:03:58 +0000960 continue;
961
Evan Cheng61560e22011-09-01 01:45:00 +0000962 unsigned RCId, RCCost;
963 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng134982d2010-10-20 22:03:58 +0000964 if (MO.isDef()) {
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 } else if (isOperandKill(MO, MRI)) {
971 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
972 if (CI != Cost.end())
973 CI->second -= RCCost;
974 else
975 Cost.insert(std::make_pair(RCId, -RCCost));
976 }
977 }
978
979 // Update register pressure of blocks from loop header to current block.
980 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
981 SmallVector<unsigned, 8> &RP = BackTrace[i];
982 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
983 CI != CE; ++CI) {
984 unsigned RCId = CI->first;
985 RP[RCId] += CI->second;
986 }
987 }
988}
989
Evan Cheng45e94d62009-02-04 09:19:56 +0000990/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
991/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000992bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +0000993 if (MI.isImplicitDef())
994 return true;
995
Evan Cheng23128422010-10-19 18:58:51 +0000996 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
997 // will increase register pressure. It's probably not worth it if the
998 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000999 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
1000 // these tend to help performance in low register pressure situation. The
1001 // trade off is it may cause spill in high pressure situation. It will end up
1002 // adding a store in the loop preheader. But the reload is no more expensive.
1003 // The side benefit is these loads are frequently CSE'ed.
Evan Chengc8141df2010-10-26 02:08:50 +00001004 if (IsCheapInstruction(MI)) {
Evan Cheng23128422010-10-19 18:58:51 +00001005 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +00001006 return false;
1007 } else {
Evan Cheng23128422010-10-19 18:58:51 +00001008 // Estimate register pressure to determine whether to LICM the instruction.
Evan Cheng0e673912010-10-14 01:16:09 +00001009 // In low register pressure situation, we can be more aggressive about
1010 // hoisting. Also, favors hoisting long latency instructions even in
1011 // moderately high pressure situation.
Dan Gohmanfca0b102010-11-11 18:08:43 +00001012 // FIXME: If there are long latency loop-invariant instructions inside the
1013 // loop at this point, why didn't the optimizer's LICM hoist them?
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001014 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +00001015 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1016 const MachineOperand &MO = MI.getOperand(i);
1017 if (!MO.isReg() || MO.isImplicit())
1018 continue;
1019 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +00001020 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +00001021 continue;
Evan Cheng61560e22011-09-01 01:45:00 +00001022
1023 unsigned RCId, RCCost;
1024 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001025 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +00001026 if (HasHighOperandLatency(MI, i, Reg)) {
1027 ++NumHighLatency;
1028 return true;
Evan Cheng0e673912010-10-14 01:16:09 +00001029 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001030
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001031 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001032 if (CI != Cost.end())
1033 CI->second += RCCost;
1034 else
1035 Cost.insert(std::make_pair(RCId, RCCost));
Evan Cheng134982d2010-10-20 22:03:58 +00001036 } else if (isOperandKill(MO, MRI)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001037 // Is a virtual register use is a kill, hoisting it out of the loop
1038 // may actually reduce register pressure or be register pressure
Evan Cheng134982d2010-10-20 22:03:58 +00001039 // neutral.
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001040 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1041 if (CI != Cost.end())
1042 CI->second -= RCCost;
1043 else
1044 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +00001045 }
1046 }
1047
Evan Cheng134982d2010-10-20 22:03:58 +00001048 // Visit BBs from header to current BB, if hoisting this doesn't cause
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001049 // high register pressure, then it's safe to proceed.
Evan Cheng134982d2010-10-20 22:03:58 +00001050 if (!CanCauseHighRegPressure(Cost)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001051 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +00001052 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +00001053 }
Evan Cheng0e673912010-10-14 01:16:09 +00001054
1055 // High register pressure situation, only hoist if the instruction is going to
1056 // be remat'ed.
Evan Chengfad62872011-10-11 23:48:44 +00001057 // Also, do not "speculate" in high register pressure situation. If an
1058 // instruction is not guaranteed to be executed in the loop, it's best to be
1059 // conservative.
Evan Cheng7efba852011-10-12 00:09:14 +00001060 if ((!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI)) ||
Evan Chengfad62872011-10-11 23:48:44 +00001061 (!TII->isTriviallyReMaterializable(&MI, AA) &&
1062 !MI.isInvariantLoad(AA)))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001063 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +00001064 }
Evan Cheng45e94d62009-02-04 09:19:56 +00001065
Evan Chengd67705f2011-04-11 21:09:18 +00001066 // If result(s) of this instruction is used by PHIs outside of the loop, then
1067 // don't hoist it if the instruction because it will introduce an extra copy.
Evan Cheng45e94d62009-02-04 09:19:56 +00001068 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1069 const MachineOperand &MO = MI.getOperand(i);
1070 if (!MO.isReg() || !MO.isDef())
1071 continue;
Evan Chengd67705f2011-04-11 21:09:18 +00001072 if (HasAnyPHIUse(MO.getReg()))
Evan Chengaf6949d2009-02-05 08:45:46 +00001073 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +00001074 }
Evan Chengaf6949d2009-02-05 08:45:46 +00001075
1076 return true;
1077}
1078
Dan Gohman5c952302009-10-29 17:47:20 +00001079MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001080 // Don't unfold simple loads.
1081 if (MI->getDesc().canFoldAsLoad())
1082 return 0;
1083
Dan Gohman5c952302009-10-29 17:47:20 +00001084 // If not, we may be able to unfold a load and hoist that.
1085 // First test whether the instruction is loading from an amenable
1086 // memory location.
Evan Cheng9fe20092011-01-20 08:34:58 +00001087 if (!MI->isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001088 return 0;
1089
Dan Gohman5c952302009-10-29 17:47:20 +00001090 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001091 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001092 unsigned NewOpc =
1093 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1094 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001095 /*UnfoldStore=*/false,
1096 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001097 if (NewOpc == 0) return 0;
Evan Chenge837dea2011-06-28 19:10:37 +00001098 const MCInstrDesc &MID = TII->get(NewOpc);
1099 if (MID.getNumDefs() != 1) return 0;
1100 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001101 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001102 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001103
1104 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001105 SmallVector<MachineInstr *, 2> NewMIs;
1106 bool Success =
1107 TII->unfoldMemoryOperand(MF, MI, Reg,
1108 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1109 NewMIs);
1110 (void)Success;
1111 assert(Success &&
1112 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1113 "succeeded!");
1114 assert(NewMIs.size() == 2 &&
1115 "Unfolded a load into multiple instructions!");
1116 MachineBasicBlock *MBB = MI->getParent();
1117 MBB->insert(MI, NewMIs[0]);
1118 MBB->insert(MI, NewMIs[1]);
1119 // If unfolding produced a load that wasn't loop-invariant or profitable to
1120 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001121 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001122 NewMIs[0]->eraseFromParent();
1123 NewMIs[1]->eraseFromParent();
1124 return 0;
1125 }
Evan Cheng134982d2010-10-20 22:03:58 +00001126
1127 // Update register pressure for the unfolded instruction.
1128 UpdateRegPressure(NewMIs[1]);
1129
Dan Gohman5c952302009-10-29 17:47:20 +00001130 // Otherwise we successfully unfolded a load that we can hoist.
1131 MI->eraseFromParent();
1132 return NewMIs[0];
1133}
1134
Evan Cheng777c6b72009-11-03 21:40:02 +00001135void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1136 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1137 const MachineInstr *MI = &*I;
Evan Cheng9fe20092011-01-20 08:34:58 +00001138 unsigned Opcode = MI->getOpcode();
1139 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1140 CI = CSEMap.find(Opcode);
1141 if (CI != CSEMap.end())
1142 CI->second.push_back(MI);
1143 else {
1144 std::vector<const MachineInstr*> CSEMIs;
1145 CSEMIs.push_back(MI);
1146 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Cheng777c6b72009-11-03 21:40:02 +00001147 }
1148 }
1149}
1150
Evan Cheng78e5c112009-11-07 03:52:02 +00001151const MachineInstr*
1152MachineLICM::LookForDuplicate(const MachineInstr *MI,
1153 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001154 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1155 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng9fe20092011-01-20 08:34:58 +00001156 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001157 return PrevMI;
1158 }
1159 return 0;
1160}
1161
1162bool MachineLICM::EliminateCSE(MachineInstr *MI,
1163 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001164 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1165 // the undef property onto uses.
1166 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001167 return false;
1168
1169 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001170 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001171
1172 // Replace virtual registers defined by MI by their counterparts defined
1173 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +00001174 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1175 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001176
1177 // Physical registers may not differ here.
1178 assert((!MO.isReg() || MO.getReg() == 0 ||
1179 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1180 MO.getReg() == Dup->getOperand(i).getReg()) &&
1181 "Instructions with different phys regs are not identical!");
1182
1183 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +00001184 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng0e673912010-10-14 01:16:09 +00001185 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1186 MRI->clearKillFlags(Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001187 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001188 }
Evan Cheng78e5c112009-11-07 03:52:02 +00001189 MI->eraseFromParent();
1190 ++NumCSEed;
1191 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001192 }
1193 return false;
1194}
1195
Evan Cheng7efba852011-10-12 00:09:14 +00001196/// MayCSE - Return true if the given instruction will be CSE'd if it's
1197/// hoisted out of the loop.
1198bool MachineLICM::MayCSE(MachineInstr *MI) {
1199 unsigned Opcode = MI->getOpcode();
1200 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1201 CI = CSEMap.find(Opcode);
1202 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1203 // the undef property onto uses.
1204 if (CI == CSEMap.end() || MI->isImplicitDef())
1205 return false;
1206
1207 return LookForDuplicate(MI, CI->second) != 0;
1208}
1209
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001210/// Hoist - When an instruction is found to use only loop invariant operands
1211/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001212///
Evan Cheng134982d2010-10-20 22:03:58 +00001213bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001214 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001215 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001216 // If not, try unfolding a hoistable load.
1217 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001218 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001219 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001220
Dan Gohmanc475c362009-01-15 22:01:38 +00001221 // Now move the instructions to the predecessor, inserting it before any
1222 // terminator instructions.
1223 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001224 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001225 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001226 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001227 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001228 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001229 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001230 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001231 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001232 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001233
Evan Cheng777c6b72009-11-03 21:40:02 +00001234 // If this is the first instruction being hoisted to the preheader,
1235 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001236 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001237 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001238 FirstInLoop = false;
1239 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001240
Evan Chengaf6949d2009-02-05 08:45:46 +00001241 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001242 unsigned Opcode = MI->getOpcode();
1243 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1244 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001245 if (!EliminateCSE(MI, CI)) {
1246 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001247 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001248
Evan Cheng134982d2010-10-20 22:03:58 +00001249 // Update register pressure for BBs from header to this block.
1250 UpdateBackTraceRegPressure(MI);
1251
Dan Gohmane6cd7572010-05-13 20:34:42 +00001252 // Clear the kill flags of any register this instruction defines,
1253 // since they may need to be live throughout the entire loop
1254 // rather than just live for part of it.
1255 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1256 MachineOperand &MO = MI->getOperand(i);
1257 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001258 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001259 }
1260
Evan Chengaf6949d2009-02-05 08:45:46 +00001261 // Add to the CSE map.
1262 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001263 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001264 else {
1265 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001266 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001267 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001268 }
1269 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001270
Dan Gohmanc475c362009-01-15 22:01:38 +00001271 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001272 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001273
1274 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001275}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001276
1277MachineBasicBlock *MachineLICM::getCurPreheader() {
1278 // Determine the block to which to hoist instructions. If we can't find a
1279 // suitable loop predecessor, we can't do any hoisting.
1280
1281 // If we've tried to get a preheader and failed, don't try again.
1282 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1283 return 0;
1284
1285 if (!CurPreheader) {
1286 CurPreheader = CurLoop->getLoopPreheader();
1287 if (!CurPreheader) {
1288 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1289 if (!Pred) {
1290 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1291 return 0;
1292 }
1293
1294 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1295 if (!CurPreheader) {
1296 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1297 return 0;
1298 }
1299 }
1300 }
1301 return CurPreheader;
1302}