blob: b315702eef8f31bd84e8e24381ae26ff75034129 [file] [log] [blame]
Bill Wendling0f940c92007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Bill Wendling0f940c92007-12-07 21:42:31 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass performs loop invariant code motion on machine instructions. We
11// attempt to remove as much code from the body of a loop as possible.
12//
Dan Gohmanc475c362009-01-15 22:01:38 +000013// This pass does not attempt to throttle itself to limit register pressure.
14// The register allocation phases are expected to perform rematerialization
15// to recover when register pressure is high.
16//
17// This pass is not intended to be a replacement or a complete alternative
18// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
19// constructs that are not exposed before lowering and instruction selection.
20//
Bill Wendling0f940c92007-12-07 21:42:31 +000021//===----------------------------------------------------------------------===//
22
23#define DEBUG_TYPE "machine-licm"
Chris Lattnerac695822008-01-04 06:41:45 +000024#include "llvm/CodeGen/Passes.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000025#include "llvm/CodeGen/MachineDominators.h"
Evan Chengd94671a2010-04-07 00:41:17 +000026#include "llvm/CodeGen/MachineFrameInfo.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000028#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling9258cd32008-01-02 19:32:43 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman589f1f52009-10-28 03:21:57 +000030#include "llvm/CodeGen/PseudoSourceValue.h"
Evan Cheng0e673912010-10-14 01:16:09 +000031#include "llvm/Target/TargetLowering.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000032#include "llvm/Target/TargetRegisterInfo.h"
Bill Wendlingefe2be72007-12-11 23:27:51 +000033#include "llvm/Target/TargetInstrInfo.h"
Evan Cheng0e673912010-10-14 01:16:09 +000034#include "llvm/Target/TargetInstrItineraries.h"
Bill Wendling0f940c92007-12-07 21:42:31 +000035#include "llvm/Target/TargetMachine.h"
Dan Gohmane33f44c2009-10-07 17:38:06 +000036#include "llvm/Analysis/AliasAnalysis.h"
Evan Chengaf6949d2009-02-05 08:45:46 +000037#include "llvm/ADT/DenseMap.h"
Evan Chengd94671a2010-04-07 00:41:17 +000038#include "llvm/ADT/SmallSet.h"
Chris Lattnerac695822008-01-04 06:41:45 +000039#include "llvm/ADT/Statistic.h"
Chris Lattnerac695822008-01-04 06:41:45 +000040#include "llvm/Support/Debug.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000041#include "llvm/Support/raw_ostream.h"
Bill Wendling0f940c92007-12-07 21:42:31 +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
Bill Wendling0f940c92007-12-07 21:42:31 +000094 public:
95 static char ID; // Pass identification, replacement for typeid
Evan Chengd94671a2010-04-07 00:41:17 +000096 MachineLICM() :
Owen Anderson081c34b2010-10-19 17:21:58 +000097 MachineFunctionPass(ID), PreRegAlloc(true) {
98 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
99 }
Evan Chengd94671a2010-04-07 00:41:17 +0000100
101 explicit MachineLICM(bool PreRA) :
Owen Anderson081c34b2010-10-19 17:21:58 +0000102 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
103 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
104 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000105
106 virtual bool runOnMachineFunction(MachineFunction &MF);
107
Dan Gohman72241702008-12-18 01:37:56 +0000108 const char *getPassName() const { return "Machine Instruction LICM"; }
109
Bill Wendling0f940c92007-12-07 21:42:31 +0000110 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Bill Wendling0f940c92007-12-07 21:42:31 +0000111 AU.addRequired<MachineLoopInfo>();
112 AU.addRequired<MachineDominatorTree>();
Dan Gohmane33f44c2009-10-07 17:38:06 +0000113 AU.addRequired<AliasAnalysis>();
Bill Wendlingd5da7042008-01-04 08:48:49 +0000114 AU.addPreserved<MachineLoopInfo>();
115 AU.addPreserved<MachineDominatorTree>();
116 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendling0f940c92007-12-07 21:42:31 +0000117 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000118
119 virtual void releaseMemory() {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000120 RegSeen.clear();
Evan Cheng0e673912010-10-14 01:16:09 +0000121 RegPressure.clear();
122 RegLimit.clear();
Evan Cheng23128422010-10-19 18:58:51 +0000123 BackTrace.clear();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000124 for (DenseMap<unsigned,std::vector<const MachineInstr*> >::iterator
125 CI = CSEMap.begin(), CE = CSEMap.end(); CI != CE; ++CI)
126 CI->second.clear();
Evan Chengaf6949d2009-02-05 08:45:46 +0000127 CSEMap.clear();
128 }
129
Bill Wendling0f940c92007-12-07 21:42:31 +0000130 private:
Evan Cheng4038f9c2010-04-08 01:03:47 +0000131 /// CandidateInfo - Keep track of information about hoisting candidates.
132 struct CandidateInfo {
133 MachineInstr *MI;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000134 unsigned Def;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000135 int FI;
136 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
137 : MI(mi), Def(def), FI(fi) {}
Evan Cheng4038f9c2010-04-08 01:03:47 +0000138 };
139
140 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
141 /// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000142 void HoistRegionPostRA();
Evan Cheng4038f9c2010-04-08 01:03:47 +0000143
144 /// HoistPostRA - When an instruction is found to only use loop invariant
145 /// operands that is safe to hoist, this instruction is called to do the
146 /// dirty work.
147 void HoistPostRA(MachineInstr *MI, unsigned Def);
148
149 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
150 /// gather register def and frame object update information.
151 void ProcessMI(MachineInstr *MI, unsigned *PhysRegDefs,
152 SmallSet<int, 32> &StoredFIs,
153 SmallVector<CandidateInfo, 32> &Candidates);
154
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000155 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
156 /// current loop.
157 void AddToLiveIns(unsigned Reg);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000158
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000159 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner77910802010-07-12 00:00:35 +0000160 /// candidate for LICM. e.g. If the instruction is a call, then it's
161 /// obviously not safe to hoist it.
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000162 bool IsLICMCandidate(MachineInstr &I);
163
Bill Wendling041b3f82007-12-08 23:58:46 +0000164 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendling0f940c92007-12-07 21:42:31 +0000165 /// invariant. I.e., all virtual register operands are defined outside of
166 /// the loop, physical registers aren't accessed (explicitly or implicitly),
167 /// and the instruction is hoistable.
168 ///
Bill Wendling041b3f82007-12-08 23:58:46 +0000169 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendling0f940c92007-12-07 21:42:31 +0000170
Evan Chengd67705f2011-04-11 21:09:18 +0000171 /// HasAnyPHIUse - Return true if the specified register is used by any
172 /// phi node.
173 bool HasAnyPHIUse(unsigned Reg) const;
174
Evan Cheng23128422010-10-19 18:58:51 +0000175 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
176 /// and an use in the current loop, return true if the target considered
177 /// it 'high'.
Evan Chengc8141df2010-10-26 02:08:50 +0000178 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
179 unsigned Reg) const;
180
181 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Cheng0e673912010-10-14 01:16:09 +0000182
Evan Cheng134982d2010-10-20 22:03:58 +0000183 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
184 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000185 /// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000186 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost);
187
188 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
189 /// the current block and update their register pressures to reflect the
190 /// effect of hoisting MI from the current block to the preheader.
191 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000192
Evan Cheng45e94d62009-02-04 09:19:56 +0000193 /// IsProfitableToHoist - Return true if it is potentially profitable to
194 /// hoist the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000195 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng45e94d62009-02-04 09:19:56 +0000196
Bill Wendling0f940c92007-12-07 21:42:31 +0000197 /// HoistRegion - Walk the specified region of the CFG (defined by all
198 /// blocks dominated by the specified block, and that are in the current
199 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
200 /// visit definitions before uses, allowing us to hoist a loop body in one
201 /// pass without iteration.
202 ///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000203 void HoistRegion(MachineDomTreeNode *N, bool IsHeader = false);
Bill Wendling0f940c92007-12-07 21:42:31 +0000204
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000205 /// InitRegPressure - Find all virtual register references that are liveout
206 /// of the preheader to initialize the starting "register pressure". Note
207 /// this does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000208 void InitRegPressure(MachineBasicBlock *BB);
209
Evan Cheng134982d2010-10-20 22:03:58 +0000210 /// UpdateRegPressure - Update estimate of register pressure after the
211 /// specified instruction.
212 void UpdateRegPressure(const MachineInstr *MI);
Evan Cheng0e673912010-10-14 01:16:09 +0000213
Dan Gohman5c952302009-10-29 17:47:20 +0000214 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
215 /// the load itself could be hoisted. Return the unfolded and hoistable
216 /// load, or null if the load couldn't be unfolded or if it wouldn't
217 /// be hoistable.
218 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
219
Evan Cheng78e5c112009-11-07 03:52:02 +0000220 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
221 /// duplicate of MI. Return this instruction if it's found.
222 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
223 std::vector<const MachineInstr*> &PrevMIs);
224
Evan Cheng9fb744e2009-11-05 00:51:13 +0000225 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
226 /// the preheader that compute the same value. If it's found, do a RAU on
227 /// with the definition of the existing instruction rather than hoisting
228 /// the instruction to the preheader.
229 bool EliminateCSE(MachineInstr *MI,
230 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
231
Bill Wendling0f940c92007-12-07 21:42:31 +0000232 /// Hoist - When an instruction is found to only use loop invariant operands
233 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng134982d2010-10-20 22:03:58 +0000234 /// It returns true if the instruction is hoisted.
235 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Cheng777c6b72009-11-03 21:40:02 +0000236
237 /// InitCSEMap - Initialize the CSE map with instructions that are in the
238 /// current loop preheader that may become duplicates of instructions that
239 /// are hoisted out of the loop.
240 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman853d3fb2010-06-22 17:25:57 +0000241
242 /// getCurPreheader - Get the preheader for the current loop, splitting
243 /// a critical edge if needed.
244 MachineBasicBlock *getCurPreheader();
Bill Wendling0f940c92007-12-07 21:42:31 +0000245 };
Bill Wendling0f940c92007-12-07 21:42:31 +0000246} // end anonymous namespace
247
Dan Gohman844731a2008-05-13 00:00:25 +0000248char MachineLICM::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000249INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
250 "Machine Loop Invariant Code Motion", false, false)
251INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
252INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
253INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
254INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersonce665bd2010-10-07 22:25:06 +0000255 "Machine Loop Invariant Code Motion", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000256
Evan Chengd94671a2010-04-07 00:41:17 +0000257FunctionPass *llvm::createMachineLICMPass(bool PreRegAlloc) {
258 return new MachineLICM(PreRegAlloc);
259}
Bill Wendling0f940c92007-12-07 21:42:31 +0000260
Dan Gohman853d3fb2010-06-22 17:25:57 +0000261/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
262/// loop that has a unique predecessor.
263static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohmanaa742602010-07-09 18:49:45 +0000264 // Check whether this loop even has a unique predecessor.
265 if (!CurLoop->getLoopPredecessor())
266 return false;
267 // Ok, now check to see if any of its outer loops do.
Dan Gohmanc475c362009-01-15 22:01:38 +0000268 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman853d3fb2010-06-22 17:25:57 +0000269 if (L->getLoopPredecessor())
Dan Gohmanc475c362009-01-15 22:01:38 +0000270 return false;
Dan Gohmanaa742602010-07-09 18:49:45 +0000271 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohmanc475c362009-01-15 22:01:38 +0000272 return true;
273}
274
Bill Wendling0f940c92007-12-07 21:42:31 +0000275bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Evan Chengd94671a2010-04-07 00:41:17 +0000276 if (PreRegAlloc)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000277 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Evan Chengd94671a2010-04-07 00:41:17 +0000278 else
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000279 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
280 DEBUG(dbgs() << MF.getFunction()->getName() << " ********\n");
Bill Wendlinga17ad592007-12-11 22:22:22 +0000281
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000282 Changed = FirstInLoop = false;
Bill Wendlingacb04ec2008-08-31 02:30:23 +0000283 TM = &MF.getTarget();
Bill Wendling9258cd32008-01-02 19:32:43 +0000284 TII = TM->getInstrInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000285 TLI = TM->getTargetLowering();
Dan Gohmana8fb3362009-09-25 23:58:45 +0000286 TRI = TM->getRegisterInfo();
Evan Chengd94671a2010-04-07 00:41:17 +0000287 MFI = MF.getFrameInfo();
Evan Cheng0e673912010-10-14 01:16:09 +0000288 MRI = &MF.getRegInfo();
289 InstrItins = TM->getInstrItineraryData();
Dan Gohman45094e32009-09-26 02:34:00 +0000290 AllocatableSet = TRI->getAllocatableSet(MF);
Bill Wendling0f940c92007-12-07 21:42:31 +0000291
Evan Cheng0e673912010-10-14 01:16:09 +0000292 if (PreRegAlloc) {
293 // Estimate register pressure during pre-regalloc pass.
294 unsigned NumRC = TRI->getNumRegClasses();
295 RegPressure.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000296 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000297 RegLimit.resize(NumRC);
Evan Cheng0e673912010-10-14 01:16:09 +0000298 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
299 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichbe2119e2011-03-07 21:56:36 +0000300 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Cheng0e673912010-10-14 01:16:09 +0000301 }
302
Bill Wendling0f940c92007-12-07 21:42:31 +0000303 // Get our Loop information...
Evan Cheng4038f9c2010-04-08 01:03:47 +0000304 MLI = &getAnalysis<MachineLoopInfo>();
305 DT = &getAnalysis<MachineDominatorTree>();
306 AA = &getAnalysis<AliasAnalysis>();
Bill Wendling0f940c92007-12-07 21:42:31 +0000307
Dan Gohmanaa742602010-07-09 18:49:45 +0000308 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
309 while (!Worklist.empty()) {
310 CurLoop = Worklist.pop_back_val();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000311 CurPreheader = 0;
Bill Wendling0f940c92007-12-07 21:42:31 +0000312
Evan Cheng4038f9c2010-04-08 01:03:47 +0000313 // If this is done before regalloc, only visit outer-most preheader-sporting
314 // loops.
Dan Gohmanaa742602010-07-09 18:49:45 +0000315 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
316 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohmanc475c362009-01-15 22:01:38 +0000317 continue;
Dan Gohmanaa742602010-07-09 18:49:45 +0000318 }
Dan Gohmanc475c362009-01-15 22:01:38 +0000319
Evan Chengd94671a2010-04-07 00:41:17 +0000320 if (!PreRegAlloc)
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000321 HoistRegionPostRA();
Evan Chengd94671a2010-04-07 00:41:17 +0000322 else {
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000323 // CSEMap is initialized for loop header when the first instruction is
324 // being hoisted.
325 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng82e0a1a2010-05-29 00:06:36 +0000326 FirstInLoop = true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000327 HoistRegion(N, true);
Evan Chengd94671a2010-04-07 00:41:17 +0000328 CSEMap.clear();
329 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000330 }
331
332 return Changed;
333}
334
Evan Cheng4038f9c2010-04-08 01:03:47 +0000335/// InstructionStoresToFI - Return true if instruction stores to the
336/// specified frame.
337static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
338 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
339 oe = MI->memoperands_end(); o != oe; ++o) {
340 if (!(*o)->isStore() || !(*o)->getValue())
341 continue;
342 if (const FixedStackPseudoSourceValue *Value =
343 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
344 if (Value->getFrameIndex() == FI)
345 return true;
346 }
347 }
348 return false;
349}
350
351/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
352/// gather register def and frame object update information.
353void MachineLICM::ProcessMI(MachineInstr *MI,
354 unsigned *PhysRegDefs,
355 SmallSet<int, 32> &StoredFIs,
356 SmallVector<CandidateInfo, 32> &Candidates) {
357 bool RuledOut = false;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000358 bool HasNonInvariantUse = false;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000359 unsigned Def = 0;
360 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
361 const MachineOperand &MO = MI->getOperand(i);
362 if (MO.isFI()) {
363 // Remember if the instruction stores to the frame index.
364 int FI = MO.getIndex();
365 if (!StoredFIs.count(FI) &&
366 MFI->isSpillSlotObjectIndex(FI) &&
367 InstructionStoresToFI(MI, FI))
368 StoredFIs.insert(FI);
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000369 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000370 continue;
371 }
372
373 if (!MO.isReg())
374 continue;
375 unsigned Reg = MO.getReg();
376 if (!Reg)
377 continue;
378 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
379 "Not expecting virtual register!");
380
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000381 if (!MO.isDef()) {
Evan Cheng63275372010-04-13 22:13:34 +0000382 if (Reg && PhysRegDefs[Reg])
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000383 // If it's using a non-loop-invariant register, then it's obviously not
384 // safe to hoist.
385 HasNonInvariantUse = true;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000386 continue;
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000387 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000388
389 if (MO.isImplicit()) {
390 ++PhysRegDefs[Reg];
391 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
392 ++PhysRegDefs[*AS];
393 if (!MO.isDead())
394 // Non-dead implicit def? This cannot be hoisted.
395 RuledOut = true;
396 // No need to check if a dead implicit def is also defined by
397 // another instruction.
398 continue;
399 }
400
401 // FIXME: For now, avoid instructions with multiple defs, unless
402 // it's a dead implicit def.
403 if (Def)
404 RuledOut = true;
405 else
406 Def = Reg;
407
408 // If we have already seen another instruction that defines the same
409 // register, then this is not safe.
410 if (++PhysRegDefs[Reg] > 1)
411 // MI defined register is seen defined by another instruction in
412 // the loop, it cannot be a LICM candidate.
413 RuledOut = true;
414 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
415 if (++PhysRegDefs[*AS] > 1)
416 RuledOut = true;
417 }
418
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000419 // Only consider reloads for now and remats which do not have register
420 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000421 if (Def && !RuledOut) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000422 int FI = INT_MIN;
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000423 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000424 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
425 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng4038f9c2010-04-08 01:03:47 +0000426 }
427}
428
429/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
430/// invariants out to the preheader.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000431void MachineLICM::HoistRegionPostRA() {
Evan Chengd94671a2010-04-07 00:41:17 +0000432 unsigned NumRegs = TRI->getNumRegs();
433 unsigned *PhysRegDefs = new unsigned[NumRegs];
434 std::fill(PhysRegDefs, PhysRegDefs + NumRegs, 0);
435
Evan Cheng4038f9c2010-04-08 01:03:47 +0000436 SmallVector<CandidateInfo, 32> Candidates;
Evan Chengd94671a2010-04-07 00:41:17 +0000437 SmallSet<int, 32> StoredFIs;
438
439 // Walk the entire region, count number of defs for each register, and
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000440 // collect potential LICM candidates.
441 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
442 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
443 MachineBasicBlock *BB = Blocks[i];
Evan Chengd94671a2010-04-07 00:41:17 +0000444 // Conservatively treat live-in's as an external def.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000445 // FIXME: That means a reload that're reused in successor block(s) will not
446 // be LICM'ed.
Dan Gohman81bf03e2010-04-13 16:57:55 +0000447 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Chengd94671a2010-04-07 00:41:17 +0000448 E = BB->livein_end(); I != E; ++I) {
449 unsigned Reg = *I;
450 ++PhysRegDefs[Reg];
Evan Cheng4038f9c2010-04-08 01:03:47 +0000451 for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS)
452 ++PhysRegDefs[*AS];
Evan Chengd94671a2010-04-07 00:41:17 +0000453 }
454
455 for (MachineBasicBlock::iterator
456 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Chengd94671a2010-04-07 00:41:17 +0000457 MachineInstr *MI = &*MII;
Evan Cheng4038f9c2010-04-08 01:03:47 +0000458 ProcessMI(MI, PhysRegDefs, StoredFIs, Candidates);
Evan Chengd94671a2010-04-07 00:41:17 +0000459 }
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000460 }
Evan Chengd94671a2010-04-07 00:41:17 +0000461
462 // Now evaluate whether the potential candidates qualify.
463 // 1. Check if the candidate defined register is defined by another
464 // instruction in the loop.
465 // 2. If the candidate is a load from stack slot (always true for now),
466 // check if the slot is stored anywhere in the loop.
467 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000468 if (Candidates[i].FI != INT_MIN &&
469 StoredFIs.count(Candidates[i].FI))
Evan Chengd94671a2010-04-07 00:41:17 +0000470 continue;
471
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000472 if (PhysRegDefs[Candidates[i].Def] == 1) {
473 bool Safe = true;
474 MachineInstr *MI = Candidates[i].MI;
Evan Chengc15d9132010-04-13 20:25:29 +0000475 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
476 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng63275372010-04-13 22:13:34 +0000477 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Chengaeb2f4a2010-04-13 20:21:05 +0000478 continue;
479 if (PhysRegDefs[MO.getReg()]) {
480 // If it's using a non-loop-invariant register, then it's obviously
481 // not safe to hoist.
482 Safe = false;
483 break;
484 }
485 }
486 if (Safe)
487 HoistPostRA(MI, Candidates[i].Def);
488 }
Evan Chengd94671a2010-04-07 00:41:17 +0000489 }
Benjamin Kramer678d9b72010-04-12 11:38:35 +0000490
491 delete[] PhysRegDefs;
Evan Chengd94671a2010-04-07 00:41:17 +0000492}
493
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000494/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
495/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000496void MachineLICM::AddToLiveIns(unsigned Reg) {
497 const std::vector<MachineBasicBlock*> Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen9196ab62010-04-20 18:45:47 +0000498 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
499 MachineBasicBlock *BB = Blocks[i];
500 if (!BB->isLiveIn(Reg))
501 BB->addLiveIn(Reg);
502 for (MachineBasicBlock::iterator
503 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
504 MachineInstr *MI = &*MII;
505 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
506 MachineOperand &MO = MI->getOperand(i);
507 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
508 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
509 MO.setIsKill(false);
510 }
511 }
512 }
Evan Cheng4038f9c2010-04-08 01:03:47 +0000513}
514
515/// HoistPostRA - When an instruction is found to only use loop invariant
516/// operands that is safe to hoist, this instruction is called to do the
517/// dirty work.
518void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman853d3fb2010-06-22 17:25:57 +0000519 MachineBasicBlock *Preheader = getCurPreheader();
520 if (!Preheader) return;
521
Evan Chengd94671a2010-04-07 00:41:17 +0000522 // Now move the instructions to the predecessor, inserting it before any
523 // terminator instructions.
524 DEBUG({
525 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +0000526 if (Preheader->getBasicBlock())
Evan Chengd94671a2010-04-07 00:41:17 +0000527 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +0000528 << Preheader->getName();
Evan Chengd94671a2010-04-07 00:41:17 +0000529 if (MI->getParent()->getBasicBlock())
530 dbgs() << " from MachineBasicBlock "
531 << MI->getParent()->getName();
532 dbgs() << "\n";
533 });
534
535 // Splice the instruction to the preheader.
Evan Cheng4038f9c2010-04-08 01:03:47 +0000536 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman853d3fb2010-06-22 17:25:57 +0000537 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng4038f9c2010-04-08 01:03:47 +0000538
Evan Cheng94d1d9c2010-04-17 07:07:11 +0000539 // Add register to livein list to all the BBs in the current loop since a
540 // loop invariant must be kept live throughout the whole loop. This is
541 // important to ensure later passes do not scavenge the def register.
542 AddToLiveIns(Def);
Evan Chengd94671a2010-04-07 00:41:17 +0000543
544 ++NumPostRAHoisted;
545 Changed = true;
546}
547
Bill Wendling0f940c92007-12-07 21:42:31 +0000548/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
549/// dominated by the specified block, and that are in the current loop) in depth
550/// first order w.r.t the DominatorTree. This allows us to visit definitions
551/// before uses, allowing us to hoist a loop body in one pass without iteration.
552///
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000553void MachineLICM::HoistRegion(MachineDomTreeNode *N, bool IsHeader) {
Bill Wendling0f940c92007-12-07 21:42:31 +0000554 assert(N != 0 && "Null dominator tree node?");
555 MachineBasicBlock *BB = N->getBlock();
556
557 // If this subregion is not in the top level loop at all, exit.
558 if (!CurLoop->contains(BB)) return;
559
Evan Cheng0e673912010-10-14 01:16:09 +0000560 MachineBasicBlock *Preheader = getCurPreheader();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000561 if (!Preheader)
562 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000563
Evan Cheng23128422010-10-19 18:58:51 +0000564 if (IsHeader) {
Evan Cheng134982d2010-10-20 22:03:58 +0000565 // Compute registers which are livein into the loop headers.
Evan Cheng23128422010-10-19 18:58:51 +0000566 RegSeen.clear();
567 BackTrace.clear();
568 InitRegPressure(Preheader);
Daniel Dunbar98694132010-10-19 17:14:24 +0000569 }
Evan Cheng11e8b742010-10-19 00:55:07 +0000570
Evan Cheng23128422010-10-19 18:58:51 +0000571 // Remember livein register pressure.
572 BackTrace.push_back(RegPressure);
573
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000574 for (MachineBasicBlock::iterator
575 MII = BB->begin(), E = BB->end(); MII != E; ) {
576 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
577 MachineInstr *MI = &*MII;
Evan Cheng134982d2010-10-20 22:03:58 +0000578 if (!Hoist(MI, Preheader))
579 UpdateRegPressure(MI);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000580 MII = NextMII;
Dan Gohmanc475c362009-01-15 22:01:38 +0000581 }
Bill Wendling0f940c92007-12-07 21:42:31 +0000582
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000583 // Don't hoist things out of a large switch statement. This often causes
584 // code to be hoisted that wasn't going to be executed, and increases
585 // register pressure in a situation where it's likely to matter.
Dale Johannesen21d35c12010-07-20 21:29:12 +0000586 if (BB->succ_size() < 25) {
587 const std::vector<MachineDomTreeNode*> &Children = N->getChildren();
Dale Johannesenbf1ae5e2010-07-20 00:50:13 +0000588 for (unsigned I = 0, E = Children.size(); I != E; ++I)
589 HoistRegion(Children[I]);
Dale Johannesen21d35c12010-07-20 21:29:12 +0000590 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000591
Evan Cheng23128422010-10-19 18:58:51 +0000592 BackTrace.pop_back();
Bill Wendling0f940c92007-12-07 21:42:31 +0000593}
594
Evan Cheng134982d2010-10-20 22:03:58 +0000595static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
596 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
597}
598
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000599/// InitRegPressure - Find all virtual register references that are liveout of
600/// the preheader to initialize the starting "register pressure". Note this
601/// does not count live through (livein but not used) registers.
Evan Cheng0e673912010-10-14 01:16:09 +0000602void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Cheng0e673912010-10-14 01:16:09 +0000603 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000604
Evan Cheng134982d2010-10-20 22:03:58 +0000605 // If the preheader has only a single predecessor and it ends with a
606 // fallthrough or an unconditional branch, then scan its predecessor for live
607 // defs as well. This happens whenever the preheader is created by splitting
608 // the critical edge from the loop predecessor to the loop header.
609 if (BB->pred_size() == 1) {
610 MachineBasicBlock *TBB = 0, *FBB = 0;
611 SmallVector<MachineOperand, 4> Cond;
612 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
613 InitRegPressure(*BB->pred_begin());
614 }
615
Evan Cheng0e673912010-10-14 01:16:09 +0000616 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
617 MII != E; ++MII) {
618 MachineInstr *MI = &*MII;
619 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
620 const MachineOperand &MO = MI->getOperand(i);
621 if (!MO.isReg() || MO.isImplicit())
622 continue;
623 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000624 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000625 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000626
Andrew Trickdc986d22010-10-19 02:50:50 +0000627 bool isNew = RegSeen.insert(Reg);
Evan Cheng0e673912010-10-14 01:16:09 +0000628 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
629 EVT VT = *RC->vt_begin();
630 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000631 if (MO.isDef())
632 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
633 else {
Evan Cheng134982d2010-10-20 22:03:58 +0000634 bool isKill = isOperandKill(MO, MRI);
635 if (isNew && !isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000636 // Haven't seen this, it must be a livein.
637 RegPressure[RCId] += TLI->getRepRegClassCostFor(VT);
Evan Cheng134982d2010-10-20 22:03:58 +0000638 else if (!isNew && isKill)
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000639 RegPressure[RCId] -= TLI->getRepRegClassCostFor(VT);
640 }
Evan Cheng0e673912010-10-14 01:16:09 +0000641 }
642 }
643}
644
Evan Cheng134982d2010-10-20 22:03:58 +0000645/// UpdateRegPressure - Update estimate of register pressure after the
646/// specified instruction.
647void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
648 if (MI->isImplicitDef())
649 return;
Evan Cheng0e673912010-10-14 01:16:09 +0000650
Evan Cheng134982d2010-10-20 22:03:58 +0000651 SmallVector<unsigned, 4> Defs;
Evan Cheng0e673912010-10-14 01:16:09 +0000652 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
653 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng23128422010-10-19 18:58:51 +0000654 if (!MO.isReg() || MO.isImplicit())
Evan Cheng0e673912010-10-14 01:16:09 +0000655 continue;
656 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000657 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000658 continue;
659
Andrew Trickdc986d22010-10-19 02:50:50 +0000660 bool isNew = RegSeen.insert(Reg);
Evan Cheng23128422010-10-19 18:58:51 +0000661 if (MO.isDef())
662 Defs.push_back(Reg);
Evan Cheng134982d2010-10-20 22:03:58 +0000663 else if (!isNew && isOperandKill(MO, MRI)) {
664 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
665 EVT VT = *RC->vt_begin();
666 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
667 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000668
Evan Cheng134982d2010-10-20 22:03:58 +0000669 if (RCCost > RegPressure[RCId])
670 RegPressure[RCId] = 0;
671 else
Evan Cheng23128422010-10-19 18:58:51 +0000672 RegPressure[RCId] -= RCCost;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000673 }
Evan Cheng0e673912010-10-14 01:16:09 +0000674 }
Evan Cheng0e673912010-10-14 01:16:09 +0000675
Evan Cheng23128422010-10-19 18:58:51 +0000676 while (!Defs.empty()) {
677 unsigned Reg = Defs.pop_back_val();
Evan Cheng0e673912010-10-14 01:16:09 +0000678 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
679 EVT VT = *RC->vt_begin();
680 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
681 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
682 RegPressure[RCId] += RCCost;
683 }
684}
685
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000686/// IsLICMCandidate - Returns true if the instruction may be a suitable
687/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
688/// not safe to hoist it.
689bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner77910802010-07-12 00:00:35 +0000690 // Check if it's safe to move the instruction.
691 bool DontMoveAcrossStore = true;
692 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnera22edc82008-01-10 23:08:24 +0000693 return false;
Chris Lattner77910802010-07-12 00:00:35 +0000694
Evan Cheng5dc57ce2010-04-13 18:16:00 +0000695 return true;
696}
697
698/// IsLoopInvariantInst - Returns true if the instruction is loop
699/// invariant. I.e., all virtual register operands are defined outside of the
700/// loop, physical registers aren't accessed explicitly, and there are no side
701/// effects that aren't captured by the operands or other flags.
702///
703bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
704 if (!IsLICMCandidate(I))
705 return false;
Bill Wendling074223a2008-03-10 08:13:01 +0000706
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000707 // The instruction is loop invariant if all of its operands are.
Bill Wendling0f940c92007-12-07 21:42:31 +0000708 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
709 const MachineOperand &MO = I.getOperand(i);
710
Dan Gohmand735b802008-10-03 15:45:36 +0000711 if (!MO.isReg())
Bill Wendlingfb018d02008-08-20 20:32:05 +0000712 continue;
713
Dan Gohmanc475c362009-01-15 22:01:38 +0000714 unsigned Reg = MO.getReg();
715 if (Reg == 0) continue;
716
717 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmana8fb3362009-09-25 23:58:45 +0000718 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmana8fb3362009-09-25 23:58:45 +0000719 if (MO.isUse()) {
720 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman45094e32009-09-26 02:34:00 +0000721 // and we can freely move its uses. Alternatively, if it's allocatable,
722 // it could get allocated to something with a def during allocation.
Evan Cheng0e673912010-10-14 01:16:09 +0000723 if (!MRI->def_empty(Reg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000724 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000725 if (AllocatableSet.test(Reg))
726 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000727 // Check for a def among the register's aliases too.
Dan Gohman45094e32009-09-26 02:34:00 +0000728 for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
729 unsigned AliasReg = *Alias;
Evan Cheng0e673912010-10-14 01:16:09 +0000730 if (!MRI->def_empty(AliasReg))
Dan Gohmana8fb3362009-09-25 23:58:45 +0000731 return false;
Dan Gohman45094e32009-09-26 02:34:00 +0000732 if (AllocatableSet.test(AliasReg))
733 return false;
734 }
Dan Gohmana8fb3362009-09-25 23:58:45 +0000735 // Otherwise it's safe to move.
736 continue;
737 } else if (!MO.isDead()) {
738 // A def that isn't dead. We can't move it.
739 return false;
Dan Gohmana363a9b2010-02-28 00:08:44 +0000740 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
741 // If the reg is live into the loop, we can't hoist an instruction
742 // which would clobber it.
743 return false;
Dan Gohmana8fb3362009-09-25 23:58:45 +0000744 }
745 }
Bill Wendlingfb018d02008-08-20 20:32:05 +0000746
747 if (!MO.isUse())
Bill Wendling0f940c92007-12-07 21:42:31 +0000748 continue;
749
Evan Cheng0e673912010-10-14 01:16:09 +0000750 assert(MRI->getVRegDef(Reg) &&
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +0000751 "Machine instr not mapped for this vreg?!");
Bill Wendling0f940c92007-12-07 21:42:31 +0000752
753 // If the loop contains the definition of an operand, then the instruction
754 // isn't loop invariant.
Evan Cheng0e673912010-10-14 01:16:09 +0000755 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendling0f940c92007-12-07 21:42:31 +0000756 return false;
757 }
758
759 // If we got this far, the instruction is loop invariant!
760 return true;
761}
762
Evan Chengaf6949d2009-02-05 08:45:46 +0000763
Evan Chengd67705f2011-04-11 21:09:18 +0000764/// HasAnyPHIUse - Return true if the specified register is used by any
765/// phi node.
766bool MachineLICM::HasAnyPHIUse(unsigned Reg) const {
Evan Cheng0e673912010-10-14 01:16:09 +0000767 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(Reg),
768 UE = MRI->use_end(); UI != UE; ++UI) {
Evan Cheng45e94d62009-02-04 09:19:56 +0000769 MachineInstr *UseMI = &*UI;
Chris Lattner518bb532010-02-09 19:54:29 +0000770 if (UseMI->isPHI())
Evan Chengaf6949d2009-02-05 08:45:46 +0000771 return true;
Evan Chengd67705f2011-04-11 21:09:18 +0000772 // Look pass copies as well.
773 if (UseMI->isCopy()) {
774 unsigned Def = UseMI->getOperand(0).getReg();
775 if (TargetRegisterInfo::isVirtualRegister(Def) &&
776 HasAnyPHIUse(Def))
777 return true;
778 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000779 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000780 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000781}
782
Evan Cheng23128422010-10-19 18:58:51 +0000783/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
784/// and an use in the current loop, return true if the target considered
785/// it 'high'.
786bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chengc8141df2010-10-26 02:08:50 +0000787 unsigned DefIdx, unsigned Reg) const {
788 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng23128422010-10-19 18:58:51 +0000789 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000790
Evan Cheng0e673912010-10-14 01:16:09 +0000791 for (MachineRegisterInfo::use_nodbg_iterator I = MRI->use_nodbg_begin(Reg),
792 E = MRI->use_nodbg_end(); I != E; ++I) {
793 MachineInstr *UseMI = &*I;
Evan Chengc8141df2010-10-26 02:08:50 +0000794 if (UseMI->isCopyLike())
795 continue;
Evan Cheng0e673912010-10-14 01:16:09 +0000796 if (!CurLoop->contains(UseMI->getParent()))
797 continue;
798 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
799 const MachineOperand &MO = UseMI->getOperand(i);
800 if (!MO.isReg() || !MO.isUse())
801 continue;
802 unsigned MOReg = MO.getReg();
803 if (MOReg != Reg)
804 continue;
805
Evan Cheng23128422010-10-19 18:58:51 +0000806 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, UseMI, i))
807 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000808 }
809
Evan Cheng23128422010-10-19 18:58:51 +0000810 // Only look at the first in loop use.
811 break;
Evan Cheng0e673912010-10-14 01:16:09 +0000812 }
813
Evan Cheng23128422010-10-19 18:58:51 +0000814 return false;
Evan Cheng0e673912010-10-14 01:16:09 +0000815}
816
Evan Chengc8141df2010-10-26 02:08:50 +0000817/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
818/// the operand latency between its def and a use is one or less.
819bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
820 if (MI.getDesc().isAsCheapAsAMove() || MI.isCopyLike())
821 return true;
822 if (!InstrItins || InstrItins->isEmpty())
823 return false;
824
825 bool isCheap = false;
826 unsigned NumDefs = MI.getDesc().getNumDefs();
827 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
828 MachineOperand &DefMO = MI.getOperand(i);
829 if (!DefMO.isReg() || !DefMO.isDef())
830 continue;
831 --NumDefs;
832 unsigned Reg = DefMO.getReg();
833 if (TargetRegisterInfo::isPhysicalRegister(Reg))
834 continue;
835
836 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
837 return false;
838 isCheap = true;
839 }
840
841 return isCheap;
842}
843
Evan Cheng134982d2010-10-20 22:03:58 +0000844/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000845/// if hoisting an instruction of the given cost matrix can cause high
846/// register pressure.
Evan Cheng134982d2010-10-20 22:03:58 +0000847bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost) {
848 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
849 CI != CE; ++CI) {
850 if (CI->second <= 0)
851 continue;
852
853 unsigned RCId = CI->first;
854 for (unsigned i = BackTrace.size(); i != 0; --i) {
855 SmallVector<unsigned, 8> &RP = BackTrace[i-1];
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000856 if (RP[RCId] + CI->second >= RegLimit[RCId])
857 return true;
858 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000859 }
860
861 return false;
862}
863
Evan Cheng134982d2010-10-20 22:03:58 +0000864/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
865/// current block and update their register pressures to reflect the effect
866/// of hoisting MI from the current block to the preheader.
867void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
868 if (MI->isImplicitDef())
869 return;
870
871 // First compute the 'cost' of the instruction, i.e. its contribution
872 // to register pressure.
873 DenseMap<unsigned, int> Cost;
874 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
875 const MachineOperand &MO = MI->getOperand(i);
876 if (!MO.isReg() || MO.isImplicit())
877 continue;
878 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000879 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng134982d2010-10-20 22:03:58 +0000880 continue;
881
882 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
883 EVT VT = *RC->vt_begin();
884 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
885 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
886 if (MO.isDef()) {
887 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
888 if (CI != Cost.end())
889 CI->second += RCCost;
890 else
891 Cost.insert(std::make_pair(RCId, RCCost));
892 } else if (isOperandKill(MO, MRI)) {
893 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
894 if (CI != Cost.end())
895 CI->second -= RCCost;
896 else
897 Cost.insert(std::make_pair(RCId, -RCCost));
898 }
899 }
900
901 // Update register pressure of blocks from loop header to current block.
902 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
903 SmallVector<unsigned, 8> &RP = BackTrace[i];
904 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
905 CI != CE; ++CI) {
906 unsigned RCId = CI->first;
907 RP[RCId] += CI->second;
908 }
909 }
910}
911
Evan Cheng45e94d62009-02-04 09:19:56 +0000912/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
913/// the given loop invariant.
Evan Chengc26abd92009-11-20 23:31:34 +0000914bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Cheng0e673912010-10-14 01:16:09 +0000915 if (MI.isImplicitDef())
916 return true;
917
Evan Cheng23128422010-10-19 18:58:51 +0000918 // If the instruction is cheap, only hoist if it is re-materilizable. LICM
919 // will increase register pressure. It's probably not worth it if the
920 // instruction is cheap.
Evan Cheng87b75ba2009-11-20 19:55:37 +0000921 // Also hoist loads from constant memory, e.g. load from stubs, GOT. Hoisting
922 // these tend to help performance in low register pressure situation. The
923 // trade off is it may cause spill in high pressure situation. It will end up
924 // adding a store in the loop preheader. But the reload is no more expensive.
925 // The side benefit is these loads are frequently CSE'ed.
Evan Chengc8141df2010-10-26 02:08:50 +0000926 if (IsCheapInstruction(MI)) {
Evan Cheng23128422010-10-19 18:58:51 +0000927 if (!TII->isTriviallyReMaterializable(&MI, AA))
Evan Cheng0e673912010-10-14 01:16:09 +0000928 return false;
929 } else {
Evan Cheng23128422010-10-19 18:58:51 +0000930 // Estimate register pressure to determine whether to LICM the instruction.
Evan Cheng0e673912010-10-14 01:16:09 +0000931 // In low register pressure situation, we can be more aggressive about
932 // hoisting. Also, favors hoisting long latency instructions even in
933 // moderately high pressure situation.
Dan Gohmanfca0b102010-11-11 18:08:43 +0000934 // FIXME: If there are long latency loop-invariant instructions inside the
935 // loop at this point, why didn't the optimizer's LICM hoist them?
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000936 DenseMap<unsigned, int> Cost;
Evan Cheng0e673912010-10-14 01:16:09 +0000937 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
938 const MachineOperand &MO = MI.getOperand(i);
939 if (!MO.isReg() || MO.isImplicit())
940 continue;
941 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc9df0252011-01-10 02:58:51 +0000942 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng0e673912010-10-14 01:16:09 +0000943 continue;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000944 if (MO.isDef()) {
Evan Cheng23128422010-10-19 18:58:51 +0000945 if (HasHighOperandLatency(MI, i, Reg)) {
946 ++NumHighLatency;
947 return true;
Evan Cheng0e673912010-10-14 01:16:09 +0000948 }
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000949
950 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
951 EVT VT = *RC->vt_begin();
952 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
953 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
954 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000955 if (CI != Cost.end())
956 CI->second += RCCost;
957 else
958 Cost.insert(std::make_pair(RCId, RCCost));
Evan Cheng134982d2010-10-20 22:03:58 +0000959 } else if (isOperandKill(MO, MRI)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000960 // Is a virtual register use is a kill, hoisting it out of the loop
961 // may actually reduce register pressure or be register pressure
Evan Cheng134982d2010-10-20 22:03:58 +0000962 // neutral.
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000963 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
964 EVT VT = *RC->vt_begin();
965 unsigned RCId = TLI->getRepRegClassFor(VT)->getID();
966 unsigned RCCost = TLI->getRepRegClassCostFor(VT);
967 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
968 if (CI != Cost.end())
969 CI->second -= RCCost;
970 else
971 Cost.insert(std::make_pair(RCId, -RCCost));
Evan Cheng0e673912010-10-14 01:16:09 +0000972 }
973 }
974
Evan Cheng134982d2010-10-20 22:03:58 +0000975 // Visit BBs from header to current BB, if hoisting this doesn't cause
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000976 // high register pressure, then it's safe to proceed.
Evan Cheng134982d2010-10-20 22:03:58 +0000977 if (!CanCauseHighRegPressure(Cost)) {
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000978 ++NumLowRP;
Evan Cheng0e673912010-10-14 01:16:09 +0000979 return true;
Evan Cheng03a9fdf2010-10-16 02:20:26 +0000980 }
Evan Cheng0e673912010-10-14 01:16:09 +0000981
982 // High register pressure situation, only hoist if the instruction is going to
983 // be remat'ed.
984 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
Evan Cheng9fe20092011-01-20 08:34:58 +0000985 !MI.isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +0000986 return false;
Evan Cheng87b75ba2009-11-20 19:55:37 +0000987 }
Evan Cheng45e94d62009-02-04 09:19:56 +0000988
Evan Chengd67705f2011-04-11 21:09:18 +0000989 // If result(s) of this instruction is used by PHIs outside of the loop, then
990 // don't hoist it if the instruction because it will introduce an extra copy.
Evan Cheng45e94d62009-02-04 09:19:56 +0000991 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
992 const MachineOperand &MO = MI.getOperand(i);
993 if (!MO.isReg() || !MO.isDef())
994 continue;
Evan Chengd67705f2011-04-11 21:09:18 +0000995 if (HasAnyPHIUse(MO.getReg()))
Evan Chengaf6949d2009-02-05 08:45:46 +0000996 return false;
Evan Cheng45e94d62009-02-04 09:19:56 +0000997 }
Evan Chengaf6949d2009-02-05 08:45:46 +0000998
999 return true;
1000}
1001
Dan Gohman5c952302009-10-29 17:47:20 +00001002MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Chenge95f3192010-10-08 18:59:19 +00001003 // Don't unfold simple loads.
1004 if (MI->getDesc().canFoldAsLoad())
1005 return 0;
1006
Dan Gohman5c952302009-10-29 17:47:20 +00001007 // If not, we may be able to unfold a load and hoist that.
1008 // First test whether the instruction is loading from an amenable
1009 // memory location.
Evan Cheng9fe20092011-01-20 08:34:58 +00001010 if (!MI->isInvariantLoad(AA))
Evan Cheng87b75ba2009-11-20 19:55:37 +00001011 return 0;
1012
Dan Gohman5c952302009-10-29 17:47:20 +00001013 // Next determine the register class for a temporary register.
Dan Gohman0115e162009-10-30 22:18:41 +00001014 unsigned LoadRegIndex;
Dan Gohman5c952302009-10-29 17:47:20 +00001015 unsigned NewOpc =
1016 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1017 /*UnfoldLoad=*/true,
Dan Gohman0115e162009-10-30 22:18:41 +00001018 /*UnfoldStore=*/false,
1019 &LoadRegIndex);
Dan Gohman5c952302009-10-29 17:47:20 +00001020 if (NewOpc == 0) return 0;
1021 const TargetInstrDesc &TID = TII->get(NewOpc);
1022 if (TID.getNumDefs() != 1) return 0;
Dan Gohman0115e162009-10-30 22:18:41 +00001023 const TargetRegisterClass *RC = TID.OpInfo[LoadRegIndex].getRegClass(TRI);
Dan Gohman5c952302009-10-29 17:47:20 +00001024 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Cheng0e673912010-10-14 01:16:09 +00001025 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Cheng87b75ba2009-11-20 19:55:37 +00001026
1027 MachineFunction &MF = *MI->getParent()->getParent();
Dan Gohman5c952302009-10-29 17:47:20 +00001028 SmallVector<MachineInstr *, 2> NewMIs;
1029 bool Success =
1030 TII->unfoldMemoryOperand(MF, MI, Reg,
1031 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1032 NewMIs);
1033 (void)Success;
1034 assert(Success &&
1035 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1036 "succeeded!");
1037 assert(NewMIs.size() == 2 &&
1038 "Unfolded a load into multiple instructions!");
1039 MachineBasicBlock *MBB = MI->getParent();
1040 MBB->insert(MI, NewMIs[0]);
1041 MBB->insert(MI, NewMIs[1]);
1042 // If unfolding produced a load that wasn't loop-invariant or profitable to
1043 // hoist, discard the new instructions and bail.
Evan Chengc26abd92009-11-20 23:31:34 +00001044 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman5c952302009-10-29 17:47:20 +00001045 NewMIs[0]->eraseFromParent();
1046 NewMIs[1]->eraseFromParent();
1047 return 0;
1048 }
Evan Cheng134982d2010-10-20 22:03:58 +00001049
1050 // Update register pressure for the unfolded instruction.
1051 UpdateRegPressure(NewMIs[1]);
1052
Dan Gohman5c952302009-10-29 17:47:20 +00001053 // Otherwise we successfully unfolded a load that we can hoist.
1054 MI->eraseFromParent();
1055 return NewMIs[0];
1056}
1057
Evan Cheng777c6b72009-11-03 21:40:02 +00001058void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1059 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1060 const MachineInstr *MI = &*I;
Evan Cheng9fe20092011-01-20 08:34:58 +00001061 unsigned Opcode = MI->getOpcode();
1062 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1063 CI = CSEMap.find(Opcode);
1064 if (CI != CSEMap.end())
1065 CI->second.push_back(MI);
1066 else {
1067 std::vector<const MachineInstr*> CSEMIs;
1068 CSEMIs.push_back(MI);
1069 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Cheng777c6b72009-11-03 21:40:02 +00001070 }
1071 }
1072}
1073
Evan Cheng78e5c112009-11-07 03:52:02 +00001074const MachineInstr*
1075MachineLICM::LookForDuplicate(const MachineInstr *MI,
1076 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng9fb744e2009-11-05 00:51:13 +00001077 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1078 const MachineInstr *PrevMI = PrevMIs[i];
Evan Cheng9fe20092011-01-20 08:34:58 +00001079 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : 0)))
Evan Cheng9fb744e2009-11-05 00:51:13 +00001080 return PrevMI;
1081 }
1082 return 0;
1083}
1084
1085bool MachineLICM::EliminateCSE(MachineInstr *MI,
1086 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengdb898092010-07-14 01:22:19 +00001087 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1088 // the undef property onto uses.
1089 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng78e5c112009-11-07 03:52:02 +00001090 return false;
1091
1092 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene65a41eb2010-01-05 00:03:48 +00001093 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001094
1095 // Replace virtual registers defined by MI by their counterparts defined
1096 // by Dup.
Evan Cheng78e5c112009-11-07 03:52:02 +00001097 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1098 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman6ac33b42010-02-28 01:33:43 +00001099
1100 // Physical registers may not differ here.
1101 assert((!MO.isReg() || MO.getReg() == 0 ||
1102 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1103 MO.getReg() == Dup->getOperand(i).getReg()) &&
1104 "Instructions with different phys regs are not identical!");
1105
1106 if (MO.isReg() && MO.isDef() &&
Dan Gohmane6cd7572010-05-13 20:34:42 +00001107 !TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
Evan Cheng0e673912010-10-14 01:16:09 +00001108 MRI->replaceRegWith(MO.getReg(), Dup->getOperand(i).getReg());
1109 MRI->clearKillFlags(Dup->getOperand(i).getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001110 }
Evan Cheng9fb744e2009-11-05 00:51:13 +00001111 }
Evan Cheng78e5c112009-11-07 03:52:02 +00001112 MI->eraseFromParent();
1113 ++NumCSEed;
1114 return true;
Evan Cheng9fb744e2009-11-05 00:51:13 +00001115 }
1116 return false;
1117}
1118
Bill Wendlinge4fc1cc2008-05-12 19:38:32 +00001119/// Hoist - When an instruction is found to use only loop invariant operands
1120/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendling0f940c92007-12-07 21:42:31 +00001121///
Evan Cheng134982d2010-10-20 22:03:58 +00001122bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman589f1f52009-10-28 03:21:57 +00001123 // First check whether we should hoist this instruction.
Evan Chengc26abd92009-11-20 23:31:34 +00001124 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman5c952302009-10-29 17:47:20 +00001125 // If not, try unfolding a hoistable load.
1126 MI = ExtractHoistableLoad(MI);
Evan Cheng134982d2010-10-20 22:03:58 +00001127 if (!MI) return false;
Dan Gohman589f1f52009-10-28 03:21:57 +00001128 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001129
Dan Gohmanc475c362009-01-15 22:01:38 +00001130 // Now move the instructions to the predecessor, inserting it before any
1131 // terminator instructions.
1132 DEBUG({
David Greene65a41eb2010-01-05 00:03:48 +00001133 dbgs() << "Hoisting " << *MI;
Dan Gohman853d3fb2010-06-22 17:25:57 +00001134 if (Preheader->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001135 dbgs() << " to MachineBasicBlock "
Dan Gohman853d3fb2010-06-22 17:25:57 +00001136 << Preheader->getName();
Dan Gohman589f1f52009-10-28 03:21:57 +00001137 if (MI->getParent()->getBasicBlock())
David Greene65a41eb2010-01-05 00:03:48 +00001138 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen324da762009-11-20 01:17:03 +00001139 << MI->getParent()->getName();
David Greene65a41eb2010-01-05 00:03:48 +00001140 dbgs() << "\n";
Dan Gohmanc475c362009-01-15 22:01:38 +00001141 });
Bill Wendling0f940c92007-12-07 21:42:31 +00001142
Evan Cheng777c6b72009-11-03 21:40:02 +00001143 // If this is the first instruction being hoisted to the preheader,
1144 // initialize the CSE map with potential common expressions.
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001145 if (FirstInLoop) {
Dan Gohman853d3fb2010-06-22 17:25:57 +00001146 InitCSEMap(Preheader);
Evan Cheng82e0a1a2010-05-29 00:06:36 +00001147 FirstInLoop = false;
1148 }
Evan Cheng777c6b72009-11-03 21:40:02 +00001149
Evan Chengaf6949d2009-02-05 08:45:46 +00001150 // Look for opportunity to CSE the hoisted instruction.
Evan Cheng777c6b72009-11-03 21:40:02 +00001151 unsigned Opcode = MI->getOpcode();
1152 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1153 CI = CSEMap.find(Opcode);
Evan Cheng9fb744e2009-11-05 00:51:13 +00001154 if (!EliminateCSE(MI, CI)) {
1155 // Otherwise, splice the instruction to the preheader.
Dan Gohman853d3fb2010-06-22 17:25:57 +00001156 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001157
Evan Cheng134982d2010-10-20 22:03:58 +00001158 // Update register pressure for BBs from header to this block.
1159 UpdateBackTraceRegPressure(MI);
1160
Dan Gohmane6cd7572010-05-13 20:34:42 +00001161 // Clear the kill flags of any register this instruction defines,
1162 // since they may need to be live throughout the entire loop
1163 // rather than just live for part of it.
1164 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1165 MachineOperand &MO = MI->getOperand(i);
1166 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Cheng0e673912010-10-14 01:16:09 +00001167 MRI->clearKillFlags(MO.getReg());
Dan Gohmane6cd7572010-05-13 20:34:42 +00001168 }
1169
Evan Chengaf6949d2009-02-05 08:45:46 +00001170 // Add to the CSE map.
1171 if (CI != CSEMap.end())
Dan Gohman589f1f52009-10-28 03:21:57 +00001172 CI->second.push_back(MI);
Evan Chengaf6949d2009-02-05 08:45:46 +00001173 else {
1174 std::vector<const MachineInstr*> CSEMIs;
Dan Gohman589f1f52009-10-28 03:21:57 +00001175 CSEMIs.push_back(MI);
Evan Cheng777c6b72009-11-03 21:40:02 +00001176 CSEMap.insert(std::make_pair(Opcode, CSEMIs));
Evan Chengaf6949d2009-02-05 08:45:46 +00001177 }
1178 }
Bill Wendling0f940c92007-12-07 21:42:31 +00001179
Dan Gohmanc475c362009-01-15 22:01:38 +00001180 ++NumHoisted;
Bill Wendling0f940c92007-12-07 21:42:31 +00001181 Changed = true;
Evan Cheng134982d2010-10-20 22:03:58 +00001182
1183 return true;
Bill Wendling0f940c92007-12-07 21:42:31 +00001184}
Dan Gohman853d3fb2010-06-22 17:25:57 +00001185
1186MachineBasicBlock *MachineLICM::getCurPreheader() {
1187 // Determine the block to which to hoist instructions. If we can't find a
1188 // suitable loop predecessor, we can't do any hoisting.
1189
1190 // If we've tried to get a preheader and failed, don't try again.
1191 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
1192 return 0;
1193
1194 if (!CurPreheader) {
1195 CurPreheader = CurLoop->getLoopPreheader();
1196 if (!CurPreheader) {
1197 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1198 if (!Pred) {
1199 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1200 return 0;
1201 }
1202
1203 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1204 if (!CurPreheader) {
1205 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
1206 return 0;
1207 }
1208 }
1209 }
1210 return CurPreheader;
1211}