blob: cb14a5cab4b4d0418dd71cb75e17750180f3bffb [file] [log] [blame]
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001//===-- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Wendlingfb706bc2007-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 Gohman79618d12009-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 Wendlingfb706bc2007-12-07 21:42:31 +000021//===----------------------------------------------------------------------===//
22
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000023#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/SmallSet.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Analysis/AliasAnalysis.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000028#include "llvm/CodeGen/MachineDominators.h"
Evan Cheng6ea59492010-04-07 00:41:17 +000029#include "llvm/CodeGen/MachineFrameInfo.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000030#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000031#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling5da19452008-01-02 19:32:43 +000032#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000033#include "llvm/CodeGen/PseudoSourceValue.h"
Evan Cheng8264e272011-06-29 01:14:12 +000034#include "llvm/MC/MCInstrItineraries.h"
Evan Chengb35afca2011-10-12 21:33:49 +000035#include "llvm/Support/CommandLine.h"
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000036#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000037#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000038#include "llvm/Target/TargetInstrInfo.h"
39#include "llvm/Target/TargetLowering.h"
40#include "llvm/Target/TargetMachine.h"
41#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000042#include "llvm/Target/TargetSubtargetInfo.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000043using namespace llvm;
44
Chandler Carruth1b9dde02014-04-22 02:02:50 +000045#define DEBUG_TYPE "machine-licm"
46
Evan Chengb35afca2011-10-12 21:33:49 +000047static cl::opt<bool>
48AvoidSpeculation("avoid-speculation",
49 cl::desc("MachineLICM should avoid speculation"),
Evan Cheng73133372011-10-26 01:26:57 +000050 cl::init(true), cl::Hidden);
Evan Chengb35afca2011-10-12 21:33:49 +000051
Hal Finkel0709f512015-01-08 22:10:48 +000052static cl::opt<bool>
53HoistCheapInsts("hoist-cheap-insts",
54 cl::desc("MachineLICM should hoist even cheap instructions"),
55 cl::init(false), cl::Hidden);
56
Evan Cheng44436302010-10-16 02:20:26 +000057STATISTIC(NumHoisted,
58 "Number of machine instructions hoisted out of loops");
59STATISTIC(NumLowRP,
60 "Number of instructions hoisted in low reg pressure situation");
61STATISTIC(NumHighLatency,
62 "Number of high latency instructions hoisted");
63STATISTIC(NumCSEed,
64 "Number of hoisted machine instructions CSEed");
Evan Cheng6ea59492010-04-07 00:41:17 +000065STATISTIC(NumPostRAHoisted,
66 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendling43751732007-12-08 01:47:01 +000067
Bill Wendlingfb706bc2007-12-07 21:42:31 +000068namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000069 class MachineLICM : public MachineFunctionPass {
Bill Wendling38236ef2007-12-11 23:27:51 +000070 const TargetInstrInfo *TII;
Benjamin Kramer56b31bd2013-01-11 20:05:37 +000071 const TargetLoweringBase *TLI;
Dan Gohmane30d63f2009-09-25 23:58:45 +000072 const TargetRegisterInfo *TRI;
Evan Cheng6ea59492010-04-07 00:41:17 +000073 const MachineFrameInfo *MFI;
Evan Chengd62719c2010-10-14 01:16:09 +000074 MachineRegisterInfo *MRI;
75 const InstrItineraryData *InstrItins;
Andrew Trickc40815d2012-02-08 21:23:03 +000076 bool PreRegAlloc;
Bill Wendlingb678ae72007-12-11 19:40:06 +000077
Bill Wendlingfb706bc2007-12-07 21:42:31 +000078 // Various analyses that we use...
Dan Gohmanbe8137b2009-10-07 17:38:06 +000079 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng058b9f02010-04-08 01:03:47 +000080 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendling70613b82008-05-12 19:38:32 +000081 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +000082
Bill Wendlingfb706bc2007-12-07 21:42:31 +000083 // State that is updated as we process loops
Bill Wendling70613b82008-05-12 19:38:32 +000084 bool Changed; // True if a loop is changed.
Evan Cheng032f3262010-05-29 00:06:36 +000085 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendling70613b82008-05-12 19:38:32 +000086 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohman79618d12009-01-15 22:01:38 +000087 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Cheng399660c2009-02-05 08:45:46 +000088
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +000089 // Exit blocks for CurLoop.
90 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
91
92 bool isExitBlock(const MachineBasicBlock *MBB) const {
93 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
94 ExitBlocks.end();
95 }
96
Evan Chengd62719c2010-10-14 01:16:09 +000097 // Track 'estimated' register pressure.
Evan Cheng44436302010-10-16 02:20:26 +000098 SmallSet<unsigned, 32> RegSeen;
Evan Chengd62719c2010-10-14 01:16:09 +000099 SmallVector<unsigned, 8> RegPressure;
Evan Cheng44436302010-10-16 02:20:26 +0000100
101 // Register pressure "limit" per register class. If the pressure
102 // is higher than the limit, then it's considered high.
Evan Chengd62719c2010-10-14 01:16:09 +0000103 SmallVector<unsigned, 8> RegLimit;
104
Evan Cheng44436302010-10-16 02:20:26 +0000105 // Register pressure on path leading from loop preheader to current BB.
106 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
107
Dale Johannesen329d4742010-07-29 17:45:24 +0000108 // For each opcode, keep a list of potential CSE instructions.
Evan Chengf42b5af2009-11-03 21:40:02 +0000109 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Cheng6ea59492010-04-07 00:41:17 +0000110
Evan Chengf192ca02011-10-11 23:48:44 +0000111 enum {
112 SpeculateFalse = 0,
113 SpeculateTrue = 1,
114 SpeculateUnknown = 2
115 };
116
Devang Patel453d4012011-10-11 18:09:58 +0000117 // If a MBB does not dominate loop exiting blocks then it may not safe
118 // to hoist loads from this block.
Evan Chengf192ca02011-10-11 23:48:44 +0000119 // Tri-state: 0 - false, 1 - true, 2 - unknown
120 unsigned SpeculationState;
Devang Patel453d4012011-10-11 18:09:58 +0000121
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000122 public:
123 static char ID; // Pass identification, replacement for typeid
Evan Cheng6ea59492010-04-07 00:41:17 +0000124 MachineLICM() :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000125 MachineFunctionPass(ID), PreRegAlloc(true) {
126 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
127 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000128
129 explicit MachineLICM(bool PreRA) :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000130 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
131 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
132 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000133
Craig Topper4584cd52014-03-07 09:26:03 +0000134 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000135
Craig Topper4584cd52014-03-07 09:26:03 +0000136 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000137 AU.addRequired<MachineLoopInfo>();
138 AU.addRequired<MachineDominatorTree>();
Dan Gohmanbe8137b2009-10-07 17:38:06 +0000139 AU.addRequired<AliasAnalysis>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000140 AU.addPreserved<MachineLoopInfo>();
141 AU.addPreserved<MachineDominatorTree>();
142 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000143 }
Evan Cheng399660c2009-02-05 08:45:46 +0000144
Craig Topper4584cd52014-03-07 09:26:03 +0000145 void releaseMemory() override {
Evan Cheng44436302010-10-16 02:20:26 +0000146 RegSeen.clear();
Evan Chengd62719c2010-10-14 01:16:09 +0000147 RegPressure.clear();
148 RegLimit.clear();
Evan Cheng63c76082010-10-19 18:58:51 +0000149 BackTrace.clear();
Evan Cheng399660c2009-02-05 08:45:46 +0000150 CSEMap.clear();
151 }
152
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000153 private:
Evan Cheng058b9f02010-04-08 01:03:47 +0000154 /// CandidateInfo - Keep track of information about hoisting candidates.
155 struct CandidateInfo {
156 MachineInstr *MI;
Evan Cheng058b9f02010-04-08 01:03:47 +0000157 unsigned Def;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000158 int FI;
159 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
160 : MI(mi), Def(def), FI(fi) {}
Evan Cheng058b9f02010-04-08 01:03:47 +0000161 };
162
163 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
164 /// invariants out to the preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000165 void HoistRegionPostRA();
Evan Cheng058b9f02010-04-08 01:03:47 +0000166
167 /// HoistPostRA - When an instruction is found to only use loop invariant
168 /// operands that is safe to hoist, this instruction is called to do the
169 /// dirty work.
170 void HoistPostRA(MachineInstr *MI, unsigned Def);
171
172 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
173 /// gather register def and frame object update information.
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000174 void ProcessMI(MachineInstr *MI,
175 BitVector &PhysRegDefs,
176 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000177 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000178 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng058b9f02010-04-08 01:03:47 +0000179
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000180 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
181 /// current loop.
182 void AddToLiveIns(unsigned Reg);
Evan Cheng058b9f02010-04-08 01:03:47 +0000183
Evan Cheng0a2aff22010-04-13 18:16:00 +0000184 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner0b7ae202010-07-12 00:00:35 +0000185 /// candidate for LICM. e.g. If the instruction is a call, then it's
186 /// obviously not safe to hoist it.
Evan Cheng0a2aff22010-04-13 18:16:00 +0000187 bool IsLICMCandidate(MachineInstr &I);
188
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000189 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000190 /// invariant. I.e., all virtual register operands are defined outside of
191 /// the loop, physical registers aren't accessed (explicitly or implicitly),
192 /// and the instruction is hoistable.
Andrew Trick5209c732012-02-08 21:23:00 +0000193 ///
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000194 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000195
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000196 /// HasLoopPHIUse - Return true if the specified instruction is used by any
197 /// phi node in the current loop.
198 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengef42bea2011-04-11 21:09:18 +0000199
Evan Cheng63c76082010-10-19 18:58:51 +0000200 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
201 /// and an use in the current loop, return true if the target considered
202 /// it 'high'.
Evan Chenge96b8d72010-10-26 02:08:50 +0000203 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
204 unsigned Reg) const;
205
206 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Chengd62719c2010-10-14 01:16:09 +0000207
Evan Cheng87066f02010-10-20 22:03:58 +0000208 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
209 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng44436302010-10-16 02:20:26 +0000210 /// register pressure.
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +0000211 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost, bool Cheap);
Evan Cheng87066f02010-10-20 22:03:58 +0000212
213 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
214 /// the current block and update their register pressures to reflect the
215 /// effect of hoisting MI from the current block to the preheader.
216 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng44436302010-10-16 02:20:26 +0000217
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000218 /// IsProfitableToHoist - Return true if it is potentially profitable to
219 /// hoist the given loop invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +0000220 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000221
Devang Patel453d4012011-10-11 18:09:58 +0000222 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
223 /// If not then a load from this mbb may not be safe to hoist.
224 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
225
Pete Cooper1eed5b52011-12-22 02:05:40 +0000226 void EnterScope(MachineBasicBlock *MBB);
227
228 void ExitScope(MachineBasicBlock *MBB);
229
230 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
231 /// dominator tree node if its a leaf or all of its children are done. Walk
232 /// up the dominator tree to destroy ancestors which are now done.
233 void ExitScopeIfDone(MachineDomTreeNode *Node,
234 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
235 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
236
237 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
238 /// blocks dominated by the specified header block, and that are in the
239 /// current loop) in depth first order w.r.t the DominatorTree. This allows
240 /// us to visit definitions before uses, allowing us to hoist a loop body in
241 /// one pass without iteration.
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000242 ///
Pete Cooper1eed5b52011-12-22 02:05:40 +0000243 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
244 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000245
Evan Cheng90da66b2011-09-01 01:45:00 +0000246 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
247 /// index, return the ID and cost of its representative register class by
248 /// reference.
249 void getRegisterClassIDAndCost(const MachineInstr *MI,
250 unsigned Reg, unsigned OpIdx,
251 unsigned &RCId, unsigned &RCCost) const;
252
Evan Cheng44436302010-10-16 02:20:26 +0000253 /// InitRegPressure - Find all virtual register references that are liveout
254 /// of the preheader to initialize the starting "register pressure". Note
255 /// this does not count live through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000256 void InitRegPressure(MachineBasicBlock *BB);
257
Evan Cheng87066f02010-10-20 22:03:58 +0000258 /// UpdateRegPressure - Update estimate of register pressure after the
259 /// specified instruction.
260 void UpdateRegPressure(const MachineInstr *MI);
Evan Chengd62719c2010-10-14 01:16:09 +0000261
Dan Gohman104f57c2009-10-29 17:47:20 +0000262 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
263 /// the load itself could be hoisted. Return the unfolded and hoistable
264 /// load, or null if the load couldn't be unfolded or if it wouldn't
265 /// be hoistable.
266 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
267
Evan Cheng7ff83192009-11-07 03:52:02 +0000268 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
269 /// duplicate of MI. Return this instruction if it's found.
270 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
271 std::vector<const MachineInstr*> &PrevMIs);
272
Evan Cheng921152f2009-11-05 00:51:13 +0000273 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
274 /// the preheader that compute the same value. If it's found, do a RAU on
275 /// with the definition of the existing instruction rather than hoisting
276 /// the instruction to the preheader.
277 bool EliminateCSE(MachineInstr *MI,
278 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
279
Evan Chengaf138952011-10-12 00:09:14 +0000280 /// MayCSE - Return true if the given instruction will be CSE'd if it's
281 /// hoisted out of the loop.
282 bool MayCSE(MachineInstr *MI);
283
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000284 /// Hoist - When an instruction is found to only use loop invariant operands
285 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng87066f02010-10-20 22:03:58 +0000286 /// It returns true if the instruction is hoisted.
287 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Chengf42b5af2009-11-03 21:40:02 +0000288
289 /// InitCSEMap - Initialize the CSE map with instructions that are in the
290 /// current loop preheader that may become duplicates of instructions that
291 /// are hoisted out of the loop.
292 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman3570f812010-06-22 17:25:57 +0000293
294 /// getCurPreheader - Get the preheader for the current loop, splitting
295 /// a critical edge if needed.
296 MachineBasicBlock *getCurPreheader();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000297 };
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000298} // end anonymous namespace
299
Dan Gohmand78c4002008-05-13 00:00:25 +0000300char MachineLICM::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000301char &llvm::MachineLICMID = MachineLICM::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000302INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
303 "Machine Loop Invariant Code Motion", false, false)
304INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
305INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
306INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
307INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000308 "Machine Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000309
Dan Gohman3570f812010-06-22 17:25:57 +0000310/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
311/// loop that has a unique predecessor.
312static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohman7929c442010-07-09 18:49:45 +0000313 // Check whether this loop even has a unique predecessor.
314 if (!CurLoop->getLoopPredecessor())
315 return false;
316 // Ok, now check to see if any of its outer loops do.
Dan Gohman79618d12009-01-15 22:01:38 +0000317 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman3570f812010-06-22 17:25:57 +0000318 if (L->getLoopPredecessor())
Dan Gohman79618d12009-01-15 22:01:38 +0000319 return false;
Dan Gohman7929c442010-07-09 18:49:45 +0000320 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohman79618d12009-01-15 22:01:38 +0000321 return true;
322}
323
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000324bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000325 if (skipOptnoneFunction(*MF.getFunction()))
326 return false;
327
Evan Cheng032f3262010-05-29 00:06:36 +0000328 Changed = FirstInLoop = false;
Eric Christopherb65c7b92014-10-14 06:26:57 +0000329 TII = MF.getSubtarget().getInstrInfo();
330 TLI = MF.getSubtarget().getTargetLowering();
331 TRI = MF.getSubtarget().getRegisterInfo();
Evan Cheng6ea59492010-04-07 00:41:17 +0000332 MFI = MF.getFrameInfo();
Evan Chengd62719c2010-10-14 01:16:09 +0000333 MRI = &MF.getRegInfo();
Eric Christopherb65c7b92014-10-14 06:26:57 +0000334 InstrItins = MF.getSubtarget().getInstrItineraryData();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000335
Andrew Trickc40815d2012-02-08 21:23:03 +0000336 PreRegAlloc = MRI->isSSA();
337
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000338 if (PreRegAlloc)
339 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
340 else
341 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
Craig Toppera538d832012-08-22 06:07:19 +0000342 DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000343
Evan Chengd62719c2010-10-14 01:16:09 +0000344 if (PreRegAlloc) {
345 // Estimate register pressure during pre-regalloc pass.
346 unsigned NumRC = TRI->getNumRegClasses();
347 RegPressure.resize(NumRC);
Evan Chengd62719c2010-10-14 01:16:09 +0000348 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000349 RegLimit.resize(NumRC);
Evan Chengd62719c2010-10-14 01:16:09 +0000350 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
351 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichdf616942011-03-07 21:56:36 +0000352 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Chengd62719c2010-10-14 01:16:09 +0000353 }
354
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000355 // Get our Loop information...
Evan Cheng058b9f02010-04-08 01:03:47 +0000356 MLI = &getAnalysis<MachineLoopInfo>();
357 DT = &getAnalysis<MachineDominatorTree>();
358 AA = &getAnalysis<AliasAnalysis>();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000359
Dan Gohman7929c442010-07-09 18:49:45 +0000360 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
361 while (!Worklist.empty()) {
362 CurLoop = Worklist.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000363 CurPreheader = nullptr;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000364 ExitBlocks.clear();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000365
Evan Cheng058b9f02010-04-08 01:03:47 +0000366 // If this is done before regalloc, only visit outer-most preheader-sporting
367 // loops.
Dan Gohman7929c442010-07-09 18:49:45 +0000368 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
369 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohman79618d12009-01-15 22:01:38 +0000370 continue;
Dan Gohman7929c442010-07-09 18:49:45 +0000371 }
Dan Gohman79618d12009-01-15 22:01:38 +0000372
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000373 CurLoop->getExitBlocks(ExitBlocks);
374
Evan Cheng6ea59492010-04-07 00:41:17 +0000375 if (!PreRegAlloc)
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000376 HoistRegionPostRA();
Evan Cheng6ea59492010-04-07 00:41:17 +0000377 else {
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000378 // CSEMap is initialized for loop header when the first instruction is
379 // being hoisted.
380 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng032f3262010-05-29 00:06:36 +0000381 FirstInLoop = true;
Pete Cooper1eed5b52011-12-22 02:05:40 +0000382 HoistOutOfLoop(N);
Evan Cheng6ea59492010-04-07 00:41:17 +0000383 CSEMap.clear();
384 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000385 }
386
387 return Changed;
388}
389
Evan Cheng058b9f02010-04-08 01:03:47 +0000390/// InstructionStoresToFI - Return true if instruction stores to the
391/// specified frame.
392static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
393 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
394 oe = MI->memoperands_end(); o != oe; ++o) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000395 if (!(*o)->isStore() || !(*o)->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000396 continue;
397 if (const FixedStackPseudoSourceValue *Value =
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000398 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000399 if (Value->getFrameIndex() == FI)
400 return true;
401 }
402 }
403 return false;
404}
405
406/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
407/// gather register def and frame object update information.
408void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000409 BitVector &PhysRegDefs,
410 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000411 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000412 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000413 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000414 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000415 unsigned Def = 0;
416 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
417 const MachineOperand &MO = MI->getOperand(i);
418 if (MO.isFI()) {
419 // Remember if the instruction stores to the frame index.
420 int FI = MO.getIndex();
421 if (!StoredFIs.count(FI) &&
422 MFI->isSpillSlotObjectIndex(FI) &&
423 InstructionStoresToFI(MI, FI))
424 StoredFIs.insert(FI);
Evan Cheng89e74792010-04-13 20:21:05 +0000425 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000426 continue;
427 }
428
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000429 // We can't hoist an instruction defining a physreg that is clobbered in
430 // the loop.
431 if (MO.isRegMask()) {
Jakob Stoklund Olesen5e1ac452012-02-02 23:52:57 +0000432 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000433 continue;
434 }
435
Evan Cheng058b9f02010-04-08 01:03:47 +0000436 if (!MO.isReg())
437 continue;
438 unsigned Reg = MO.getReg();
439 if (!Reg)
440 continue;
441 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
442 "Not expecting virtual register!");
443
Evan Cheng0a2aff22010-04-13 18:16:00 +0000444 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000445 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-04-13 20:21:05 +0000446 // If it's using a non-loop-invariant register, then it's obviously not
447 // safe to hoist.
448 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000449 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000450 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000451
452 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000453 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
454 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000455 if (!MO.isDead())
456 // Non-dead implicit def? This cannot be hoisted.
457 RuledOut = true;
458 // No need to check if a dead implicit def is also defined by
459 // another instruction.
460 continue;
461 }
462
463 // FIXME: For now, avoid instructions with multiple defs, unless
464 // it's a dead implicit def.
465 if (Def)
466 RuledOut = true;
467 else
468 Def = Reg;
469
470 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000471 // register, then this is not safe. Two defs is indicated by setting a
472 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000473 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000474 if (PhysRegDefs.test(*AS))
475 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000476 PhysRegDefs.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000477 }
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000478 if (PhysRegClobbers.test(Reg))
479 // MI defined register is seen defined by another instruction in
480 // the loop, it cannot be a LICM candidate.
481 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000482 }
483
Evan Cheng0a2aff22010-04-13 18:16:00 +0000484 // Only consider reloads for now and remats which do not have register
485 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000486 if (Def && !RuledOut) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000487 int FI = INT_MIN;
Evan Cheng89e74792010-04-13 20:21:05 +0000488 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng0a2aff22010-04-13 18:16:00 +0000489 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
490 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000491 }
492}
493
494/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
495/// invariants out to the preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000496void MachineLICM::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000497 MachineBasicBlock *Preheader = getCurPreheader();
498 if (!Preheader)
499 return;
500
Evan Cheng6ea59492010-04-07 00:41:17 +0000501 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000502 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
503 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000504
Evan Cheng058b9f02010-04-08 01:03:47 +0000505 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000506 SmallSet<int, 32> StoredFIs;
507
508 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000509 // collect potential LICM candidates.
Benjamin Kramer7d605262013-09-15 22:04:42 +0000510 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000511 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
512 MachineBasicBlock *BB = Blocks[i];
Bill Wendling918cea22011-10-12 02:58:01 +0000513
514 // If the header of the loop containing this basic block is a landing pad,
515 // then don't try to hoist instructions out of this loop.
516 const MachineLoop *ML = MLI->getLoopFor(BB);
517 if (ML && ML->getHeader()->isLandingPad()) continue;
518
Evan Cheng6ea59492010-04-07 00:41:17 +0000519 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000520 // FIXME: That means a reload that're reused in successor block(s) will not
521 // be LICM'ed.
Dan Gohman9d2d0532010-04-13 16:57:55 +0000522 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Cheng6ea59492010-04-07 00:41:17 +0000523 E = BB->livein_end(); I != E; ++I) {
524 unsigned Reg = *I;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000525 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
526 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000527 }
528
Evan Chengf192ca02011-10-11 23:48:44 +0000529 SpeculationState = SpeculateUnknown;
Evan Cheng6ea59492010-04-07 00:41:17 +0000530 for (MachineBasicBlock::iterator
531 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Cheng6ea59492010-04-07 00:41:17 +0000532 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000533 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng6ea59492010-04-07 00:41:17 +0000534 }
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000535 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000536
Evan Cheng7fede872012-03-27 01:50:58 +0000537 // Gather the registers read / clobbered by the terminator.
538 BitVector TermRegs(NumRegs);
539 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
540 if (TI != Preheader->end()) {
541 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
542 const MachineOperand &MO = TI->getOperand(i);
543 if (!MO.isReg())
544 continue;
545 unsigned Reg = MO.getReg();
546 if (!Reg)
547 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000548 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
549 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000550 }
551 }
552
Evan Cheng6ea59492010-04-07 00:41:17 +0000553 // Now evaluate whether the potential candidates qualify.
554 // 1. Check if the candidate defined register is defined by another
555 // instruction in the loop.
556 // 2. If the candidate is a load from stack slot (always true for now),
557 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000558 // 3. Make sure candidate def should not clobber
559 // registers read by the terminator. Similarly its def should not be
560 // clobbered by the terminator.
Evan Cheng6ea59492010-04-07 00:41:17 +0000561 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000562 if (Candidates[i].FI != INT_MIN &&
563 StoredFIs.count(Candidates[i].FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000564 continue;
565
Evan Cheng7fede872012-03-27 01:50:58 +0000566 unsigned Def = Candidates[i].Def;
567 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000568 bool Safe = true;
569 MachineInstr *MI = Candidates[i].MI;
Evan Chengcce672c2010-04-13 20:25:29 +0000570 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
571 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng87585d72010-04-13 22:13:34 +0000572 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000573 continue;
Evan Cheng7fede872012-03-27 01:50:58 +0000574 unsigned Reg = MO.getReg();
575 if (PhysRegDefs.test(Reg) ||
576 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000577 // If it's using a non-loop-invariant register, then it's obviously
578 // not safe to hoist.
579 Safe = false;
580 break;
581 }
582 }
583 if (Safe)
584 HoistPostRA(MI, Candidates[i].Def);
585 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000586 }
587}
588
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000589/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
590/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000591void MachineLICM::AddToLiveIns(unsigned Reg) {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000592 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000593 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
594 MachineBasicBlock *BB = Blocks[i];
595 if (!BB->isLiveIn(Reg))
596 BB->addLiveIn(Reg);
597 for (MachineBasicBlock::iterator
598 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
599 MachineInstr *MI = &*MII;
600 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
601 MachineOperand &MO = MI->getOperand(i);
602 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
603 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
604 MO.setIsKill(false);
605 }
606 }
607 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000608}
609
610/// HoistPostRA - When an instruction is found to only use loop invariant
611/// operands that is safe to hoist, this instruction is called to do the
612/// dirty work.
613void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000614 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000615
Evan Cheng6ea59492010-04-07 00:41:17 +0000616 // Now move the instructions to the predecessor, inserting it before any
617 // terminator instructions.
Jakob Stoklund Olesen90823532012-01-23 21:01:11 +0000618 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
619 << MI->getParent()->getNumber() << ": " << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000620
621 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000622 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000623 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000624
Andrew Trick5209c732012-02-08 21:23:00 +0000625 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000626 // loop invariant must be kept live throughout the whole loop. This is
627 // important to ensure later passes do not scavenge the def register.
628 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000629
630 ++NumPostRAHoisted;
631 Changed = true;
632}
633
Devang Patel453d4012011-10-11 18:09:58 +0000634// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
635// If not then a load from this mbb may not be safe to hoist.
636bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000637 if (SpeculationState != SpeculateUnknown)
638 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000639
Devang Patel453d4012011-10-11 18:09:58 +0000640 if (BB != CurLoop->getHeader()) {
641 // Check loop exiting blocks.
642 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
643 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
644 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
645 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000646 SpeculationState = SpeculateTrue;
647 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000648 }
649 }
650
Evan Chengf192ca02011-10-11 23:48:44 +0000651 SpeculationState = SpeculateFalse;
652 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000653}
654
Pete Cooper1eed5b52011-12-22 02:05:40 +0000655void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
656 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000657
Pete Cooper1eed5b52011-12-22 02:05:40 +0000658 // Remember livein register pressure.
659 BackTrace.push_back(RegPressure);
660}
Bill Wendling918cea22011-10-12 02:58:01 +0000661
Pete Cooper1eed5b52011-12-22 02:05:40 +0000662void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
663 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
664 BackTrace.pop_back();
665}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000666
Pete Cooper1eed5b52011-12-22 02:05:40 +0000667/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
668/// dominator tree node if its a leaf or all of its children are done. Walk
669/// up the dominator tree to destroy ancestors which are now done.
670void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Chengda468322012-01-10 22:27:32 +0000671 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
672 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000673 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000674 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000675
Pete Cooper1eed5b52011-12-22 02:05:40 +0000676 // Pop scope.
677 ExitScope(Node->getBlock());
678
679 // Now traverse upwards to pop ancestors whose offsprings are all done.
680 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
681 unsigned Left = --OpenChildren[Parent];
682 if (Left != 0)
683 break;
684 ExitScope(Parent->getBlock());
685 Node = Parent;
686 }
687}
688
689/// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
690/// blocks dominated by the specified header block, and that are in the
691/// current loop) in depth first order w.r.t the DominatorTree. This allows
692/// us to visit definitions before uses, allowing us to hoist a loop body in
693/// one pass without iteration.
694///
695void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
696 SmallVector<MachineDomTreeNode*, 32> Scopes;
697 SmallVector<MachineDomTreeNode*, 8> WorkList;
698 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
699 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
700
701 // Perform a DFS walk to determine the order of visit.
702 WorkList.push_back(HeaderN);
703 do {
704 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000705 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000706 MachineBasicBlock *BB = Node->getBlock();
707
708 // If the header of the loop containing this basic block is a landing pad,
709 // then don't try to hoist instructions out of this loop.
710 const MachineLoop *ML = MLI->getLoopFor(BB);
711 if (ML && ML->getHeader()->isLandingPad())
712 continue;
713
714 // If this subregion is not in the top level loop at all, exit.
715 if (!CurLoop->contains(BB))
716 continue;
717
718 Scopes.push_back(Node);
719 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
720 unsigned NumChildren = Children.size();
721
722 // Don't hoist things out of a large switch statement. This often causes
723 // code to be hoisted that wasn't going to be executed, and increases
724 // register pressure in a situation where it's likely to matter.
725 if (BB->succ_size() >= 25)
726 NumChildren = 0;
727
728 OpenChildren[Node] = NumChildren;
729 // Add children in reverse order as then the next popped worklist node is
730 // the first child of this node. This means we ultimately traverse the
731 // DOM tree in exactly the same order as if we'd recursed.
732 for (int i = (int)NumChildren-1; i >= 0; --i) {
733 MachineDomTreeNode *Child = Children[i];
734 ParentMap[Child] = Node;
735 WorkList.push_back(Child);
736 }
737 } while (!WorkList.empty());
738
739 if (Scopes.size() != 0) {
740 MachineBasicBlock *Preheader = getCurPreheader();
741 if (!Preheader)
742 return;
743
Evan Cheng87066f02010-10-20 22:03:58 +0000744 // Compute registers which are livein into the loop headers.
Evan Cheng63c76082010-10-19 18:58:51 +0000745 RegSeen.clear();
746 BackTrace.clear();
747 InitRegPressure(Preheader);
Daniel Dunbar418204e2010-10-19 17:14:24 +0000748 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000749
Pete Cooper1eed5b52011-12-22 02:05:40 +0000750 // Now perform LICM.
751 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
752 MachineDomTreeNode *Node = Scopes[i];
753 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000754
Pete Cooper1eed5b52011-12-22 02:05:40 +0000755 MachineBasicBlock *Preheader = getCurPreheader();
756 if (!Preheader)
757 continue;
758
759 EnterScope(MBB);
760
761 // Process the block
762 SpeculationState = SpeculateUnknown;
763 for (MachineBasicBlock::iterator
764 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
765 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
766 MachineInstr *MI = &*MII;
767 if (!Hoist(MI, Preheader))
768 UpdateRegPressure(MI);
769 MII = NextMII;
770 }
771
772 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
773 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000774 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000775}
776
Evan Cheng87066f02010-10-20 22:03:58 +0000777static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
778 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
779}
780
Evan Cheng90da66b2011-09-01 01:45:00 +0000781/// getRegisterClassIDAndCost - For a given MI, register, and the operand
782/// index, return the ID and cost of its representative register class.
783void
784MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
785 unsigned Reg, unsigned OpIdx,
786 unsigned &RCId, unsigned &RCCost) const {
787 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Patrik Hagglund05394352012-12-13 18:45:35 +0000788 MVT VT = *RC->vt_begin();
Owen Andersonca2f78a2011-11-16 01:02:57 +0000789 if (VT == MVT::Untyped) {
Evan Cheng90da66b2011-09-01 01:45:00 +0000790 RCId = RC->getID();
791 RCCost = 1;
792 } else {
793 RCId = TLI->getRepRegClassFor(VT)->getID();
794 RCCost = TLI->getRepRegClassCostFor(VT);
795 }
796}
Andrew Trick5209c732012-02-08 21:23:00 +0000797
Evan Cheng44436302010-10-16 02:20:26 +0000798/// InitRegPressure - Find all virtual register references that are liveout of
799/// the preheader to initialize the starting "register pressure". Note this
800/// does not count live through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000801void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000802 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000803
Evan Cheng87066f02010-10-20 22:03:58 +0000804 // If the preheader has only a single predecessor and it ends with a
805 // fallthrough or an unconditional branch, then scan its predecessor for live
806 // defs as well. This happens whenever the preheader is created by splitting
807 // the critical edge from the loop predecessor to the loop header.
808 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000809 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000810 SmallVector<MachineOperand, 4> Cond;
811 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
812 InitRegPressure(*BB->pred_begin());
813 }
814
Evan Chengd62719c2010-10-14 01:16:09 +0000815 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
816 MII != E; ++MII) {
817 MachineInstr *MI = &*MII;
818 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
819 const MachineOperand &MO = MI->getOperand(i);
820 if (!MO.isReg() || MO.isImplicit())
821 continue;
822 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000823 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000824 continue;
Evan Chengd62719c2010-10-14 01:16:09 +0000825
David Blaikie70573dc2014-11-19 07:49:26 +0000826 bool isNew = RegSeen.insert(Reg).second;
Evan Cheng90da66b2011-09-01 01:45:00 +0000827 unsigned RCId, RCCost;
828 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng44436302010-10-16 02:20:26 +0000829 if (MO.isDef())
Evan Cheng90da66b2011-09-01 01:45:00 +0000830 RegPressure[RCId] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000831 else {
Evan Cheng87066f02010-10-20 22:03:58 +0000832 bool isKill = isOperandKill(MO, MRI);
833 if (isNew && !isKill)
Evan Cheng44436302010-10-16 02:20:26 +0000834 // Haven't seen this, it must be a livein.
Evan Cheng90da66b2011-09-01 01:45:00 +0000835 RegPressure[RCId] += RCCost;
Evan Cheng87066f02010-10-20 22:03:58 +0000836 else if (!isNew && isKill)
Evan Cheng90da66b2011-09-01 01:45:00 +0000837 RegPressure[RCId] -= RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000838 }
Evan Chengd62719c2010-10-14 01:16:09 +0000839 }
840 }
841}
842
Evan Cheng87066f02010-10-20 22:03:58 +0000843/// UpdateRegPressure - Update estimate of register pressure after the
844/// specified instruction.
845void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
846 if (MI->isImplicitDef())
847 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000848
Evan Cheng87066f02010-10-20 22:03:58 +0000849 SmallVector<unsigned, 4> Defs;
Evan Chengd62719c2010-10-14 01:16:09 +0000850 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
851 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000852 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000853 continue;
854 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000855 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000856 continue;
857
David Blaikie70573dc2014-11-19 07:49:26 +0000858 bool isNew = RegSeen.insert(Reg).second;
Evan Cheng63c76082010-10-19 18:58:51 +0000859 if (MO.isDef())
860 Defs.push_back(Reg);
Evan Cheng87066f02010-10-20 22:03:58 +0000861 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng90da66b2011-09-01 01:45:00 +0000862 unsigned RCId, RCCost;
863 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng87066f02010-10-20 22:03:58 +0000864 if (RCCost > RegPressure[RCId])
865 RegPressure[RCId] = 0;
866 else
Evan Cheng63c76082010-10-19 18:58:51 +0000867 RegPressure[RCId] -= RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000868 }
Evan Chengd62719c2010-10-14 01:16:09 +0000869 }
Evan Chengd62719c2010-10-14 01:16:09 +0000870
Evan Cheng90da66b2011-09-01 01:45:00 +0000871 unsigned Idx = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000872 while (!Defs.empty()) {
873 unsigned Reg = Defs.pop_back_val();
Evan Cheng90da66b2011-09-01 01:45:00 +0000874 unsigned RCId, RCCost;
875 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Chengd62719c2010-10-14 01:16:09 +0000876 RegPressure[RCId] += RCCost;
Evan Cheng90da66b2011-09-01 01:45:00 +0000877 ++Idx;
Evan Chengd62719c2010-10-14 01:16:09 +0000878 }
879}
880
Andrew Trick5209c732012-02-08 21:23:00 +0000881/// isLoadFromGOTOrConstantPool - Return true if this machine instruction
Devang Patel1d8ab462011-10-20 17:42:23 +0000882/// loads from global offset table or constant pool.
883static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng7f8e5632011-12-07 07:15:52 +0000884 assert (MI.mayLoad() && "Expected MI that loads!");
Devang Patel69a45652011-10-17 17:35:01 +0000885 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
Andrew Trick5209c732012-02-08 21:23:00 +0000886 E = MI.memoperands_end(); I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000887 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
888 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
889 return true;
Devang Patel69a45652011-10-17 17:35:01 +0000890 }
891 }
892 return false;
893}
894
Evan Cheng0a2aff22010-04-13 18:16:00 +0000895/// IsLICMCandidate - Returns true if the instruction may be a suitable
896/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
897/// not safe to hoist it.
898bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +0000899 // Check if it's safe to move the instruction.
900 bool DontMoveAcrossStore = true;
901 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnerc8226f32008-01-10 23:08:24 +0000902 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000903
904 // If it is load then check if it is guaranteed to execute by making sure that
905 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +0000906 // the loop which does not execute this load, so we can't hoist it. Loads
907 // from constant memory are not safe to speculate all the time, for example
908 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +0000909 // Stores and side effects are already checked by isSafeToMove.
Andrew Trick5209c732012-02-08 21:23:00 +0000910 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +0000911 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +0000912 return false;
913
Evan Cheng0a2aff22010-04-13 18:16:00 +0000914 return true;
915}
916
917/// IsLoopInvariantInst - Returns true if the instruction is loop
918/// invariant. I.e., all virtual register operands are defined outside of the
919/// loop, physical registers aren't accessed explicitly, and there are no side
920/// effects that aren't captured by the operands or other flags.
Andrew Trick5209c732012-02-08 21:23:00 +0000921///
Evan Cheng0a2aff22010-04-13 18:16:00 +0000922bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
923 if (!IsLICMCandidate(I))
924 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +0000925
Bill Wendling70613b82008-05-12 19:38:32 +0000926 // The instruction is loop invariant if all of its operands are.
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000927 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
928 const MachineOperand &MO = I.getOperand(i);
929
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000930 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +0000931 continue;
932
Dan Gohman79618d12009-01-15 22:01:38 +0000933 unsigned Reg = MO.getReg();
934 if (Reg == 0) continue;
935
936 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmane30d63f2009-09-25 23:58:45 +0000937 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +0000938 if (MO.isUse()) {
939 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +0000940 // and we can freely move its uses. Alternatively, if it's allocatable,
941 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesen86ae07f2012-01-16 22:34:08 +0000942 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmane30d63f2009-09-25 23:58:45 +0000943 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000944 // Otherwise it's safe to move.
945 continue;
946 } else if (!MO.isDead()) {
947 // A def that isn't dead. We can't move it.
948 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +0000949 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
950 // If the reg is live into the loop, we can't hoist an instruction
951 // which would clobber it.
952 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000953 }
954 }
Bill Wendlingcd01e892008-08-20 20:32:05 +0000955
956 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000957 continue;
958
Evan Chengd62719c2010-10-14 01:16:09 +0000959 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +0000960 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000961
962 // If the loop contains the definition of an operand, then the instruction
963 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +0000964 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000965 return false;
966 }
967
968 // If we got this far, the instruction is loop invariant!
969 return true;
970}
971
Evan Cheng399660c2009-02-05 08:45:46 +0000972
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000973/// HasLoopPHIUse - Return true if the specified instruction is used by a
974/// phi node and hoisting it could cause a copy to be inserted.
975bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
976 SmallVector<const MachineInstr*, 8> Work(1, MI);
977 do {
978 MI = Work.pop_back_val();
979 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
980 if (!MO->isReg() || !MO->isDef())
981 continue;
982 unsigned Reg = MO->getReg();
983 if (!TargetRegisterInfo::isVirtualRegister(Reg))
984 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000985 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000986 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +0000987 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000988 // A PHI inside the loop causes a copy because the live range of Reg is
989 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +0000990 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000991 return true;
992 // A PHI in an exit block can cause a copy to be inserted if the PHI
993 // has multiple predecessors in the loop with different values.
994 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +0000995 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000996 return true;
997 continue;
998 }
999 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +00001000 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1001 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001002 }
Evan Chengef42bea2011-04-11 21:09:18 +00001003 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001004 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +00001005 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001006}
1007
Evan Cheng63c76082010-10-19 18:58:51 +00001008/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1009/// and an use in the current loop, return true if the target considered
1010/// it 'high'.
1011bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chenge96b8d72010-10-26 02:08:50 +00001012 unsigned DefIdx, unsigned Reg) const {
1013 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +00001014 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001015
Owen Andersonb36376e2014-03-17 19:36:09 +00001016 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1017 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001018 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001019 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +00001020 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001021 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1022 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +00001023 if (!MO.isReg() || !MO.isUse())
1024 continue;
1025 unsigned MOReg = MO.getReg();
1026 if (MOReg != Reg)
1027 continue;
1028
Owen Andersonb36376e2014-03-17 19:36:09 +00001029 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, &UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +00001030 return true;
Evan Chengd62719c2010-10-14 01:16:09 +00001031 }
1032
Evan Cheng63c76082010-10-19 18:58:51 +00001033 // Only look at the first in loop use.
1034 break;
Evan Chengd62719c2010-10-14 01:16:09 +00001035 }
1036
Evan Cheng63c76082010-10-19 18:58:51 +00001037 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001038}
1039
Evan Chenge96b8d72010-10-26 02:08:50 +00001040/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1041/// the operand latency between its def and a use is one or less.
1042bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Jiangning Liuc3053122014-07-29 01:55:19 +00001043 if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001044 return true;
1045 if (!InstrItins || InstrItins->isEmpty())
1046 return false;
1047
1048 bool isCheap = false;
1049 unsigned NumDefs = MI.getDesc().getNumDefs();
1050 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1051 MachineOperand &DefMO = MI.getOperand(i);
1052 if (!DefMO.isReg() || !DefMO.isDef())
1053 continue;
1054 --NumDefs;
1055 unsigned Reg = DefMO.getReg();
1056 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1057 continue;
1058
1059 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1060 return false;
1061 isCheap = true;
1062 }
1063
1064 return isCheap;
1065}
1066
Evan Cheng87066f02010-10-20 22:03:58 +00001067/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng44436302010-10-16 02:20:26 +00001068/// if hoisting an instruction of the given cost matrix can cause high
1069/// register pressure.
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001070bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost,
1071 bool CheapInstr) {
Evan Cheng87066f02010-10-20 22:03:58 +00001072 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1073 CI != CE; ++CI) {
Andrew Trick5209c732012-02-08 21:23:00 +00001074 if (CI->second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001075 continue;
1076
1077 unsigned RCId = CI->first;
Pete Cooper1c3b1ef2011-12-22 02:13:25 +00001078 unsigned Limit = RegLimit[RCId];
1079 int Cost = CI->second;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001080
1081 // Don't hoist cheap instructions if they would increase register pressure,
1082 // even if we're under the limit.
Hal Finkel0709f512015-01-08 22:10:48 +00001083 if (CheapInstr && !HoistCheapInsts)
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001084 return true;
1085
Evan Cheng87066f02010-10-20 22:03:58 +00001086 for (unsigned i = BackTrace.size(); i != 0; --i) {
Craig Topper2cd5ff82013-07-11 16:22:38 +00001087 SmallVectorImpl<unsigned> &RP = BackTrace[i-1];
Pete Cooper1c3b1ef2011-12-22 02:13:25 +00001088 if (RP[RCId] + Cost >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001089 return true;
1090 }
Evan Cheng44436302010-10-16 02:20:26 +00001091 }
1092
1093 return false;
1094}
1095
Evan Cheng87066f02010-10-20 22:03:58 +00001096/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1097/// current block and update their register pressures to reflect the effect
1098/// of hoisting MI from the current block to the preheader.
1099void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1100 if (MI->isImplicitDef())
1101 return;
1102
1103 // First compute the 'cost' of the instruction, i.e. its contribution
1104 // to register pressure.
1105 DenseMap<unsigned, int> Cost;
1106 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1107 const MachineOperand &MO = MI->getOperand(i);
1108 if (!MO.isReg() || MO.isImplicit())
1109 continue;
1110 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001111 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng87066f02010-10-20 22:03:58 +00001112 continue;
1113
Evan Cheng90da66b2011-09-01 01:45:00 +00001114 unsigned RCId, RCCost;
1115 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng87066f02010-10-20 22:03:58 +00001116 if (MO.isDef()) {
1117 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1118 if (CI != Cost.end())
1119 CI->second += RCCost;
1120 else
1121 Cost.insert(std::make_pair(RCId, RCCost));
1122 } else if (isOperandKill(MO, MRI)) {
1123 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1124 if (CI != Cost.end())
1125 CI->second -= RCCost;
1126 else
1127 Cost.insert(std::make_pair(RCId, -RCCost));
1128 }
1129 }
1130
1131 // Update register pressure of blocks from loop header to current block.
1132 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
Craig Topper2cd5ff82013-07-11 16:22:38 +00001133 SmallVectorImpl<unsigned> &RP = BackTrace[i];
Evan Cheng87066f02010-10-20 22:03:58 +00001134 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1135 CI != CE; ++CI) {
1136 unsigned RCId = CI->first;
1137 RP[RCId] += CI->second;
1138 }
1139 }
1140}
1141
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001142/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1143/// the given loop invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001144bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001145 if (MI.isImplicitDef())
1146 return true;
1147
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001148 // Besides removing computation from the loop, hoisting an instruction has
1149 // these effects:
1150 //
1151 // - The value defined by the instruction becomes live across the entire
1152 // loop. This increases register pressure in the loop.
1153 //
1154 // - If the value is used by a PHI in the loop, a copy will be required for
1155 // lowering the PHI after extending the live range.
1156 //
1157 // - When hoisting the last use of a value in the loop, that value no longer
1158 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001159
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001160 bool CheapInstr = IsCheapInstruction(MI);
1161 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001162
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001163 // Don't hoist a cheap instruction if it would create a copy in the loop.
1164 if (CheapInstr && CreatesCopy) {
1165 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1166 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001167 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001168
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001169 // Rematerializable instructions should always be hoisted since the register
1170 // allocator can just pull them down again when needed.
1171 if (TII->isTriviallyReMaterializable(&MI, AA))
1172 return true;
1173
1174 // Estimate register pressure to determine whether to LICM the instruction.
1175 // In low register pressure situation, we can be more aggressive about
1176 // hoisting. Also, favors hoisting long latency instructions even in
1177 // moderately high pressure situation.
1178 // Cheap instructions will only be hoisted if they don't increase register
1179 // pressure at all.
1180 // FIXME: If there are long latency loop-invariant instructions inside the
1181 // loop at this point, why didn't the optimizer's LICM hoist them?
1182 DenseMap<unsigned, int> Cost;
1183 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1184 const MachineOperand &MO = MI.getOperand(i);
1185 if (!MO.isReg() || MO.isImplicit())
1186 continue;
1187 unsigned Reg = MO.getReg();
1188 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1189 continue;
1190
1191 unsigned RCId, RCCost;
1192 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
1193 if (MO.isDef()) {
1194 if (HasHighOperandLatency(MI, i, Reg)) {
1195 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1196 ++NumHighLatency;
1197 return true;
1198 }
1199 Cost[RCId] += RCCost;
1200 } else if (isOperandKill(MO, MRI)) {
1201 // Is a virtual register use is a kill, hoisting it out of the loop
1202 // may actually reduce register pressure or be register pressure
1203 // neutral.
1204 Cost[RCId] -= RCCost;
1205 }
1206 }
1207
1208 // Visit BBs from header to current BB, if hoisting this doesn't cause
1209 // high register pressure, then it's safe to proceed.
1210 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1211 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1212 ++NumLowRP;
1213 return true;
1214 }
1215
1216 // Don't risk increasing register pressure if it would create copies.
1217 if (CreatesCopy) {
1218 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001219 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001220 }
1221
1222 // Do not "speculate" in high register pressure situation. If an
1223 // instruction is not guaranteed to be executed in the loop, it's best to be
1224 // conservative.
1225 if (AvoidSpeculation &&
1226 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1227 DEBUG(dbgs() << "Won't speculate: " << MI);
1228 return false;
1229 }
1230
1231 // High register pressure situation, only hoist if the instruction is going
1232 // to be remat'ed.
1233 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1234 !MI.isInvariantLoad(AA)) {
1235 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1236 return false;
1237 }
Evan Cheng399660c2009-02-05 08:45:46 +00001238
1239 return true;
1240}
1241
Dan Gohman104f57c2009-10-29 17:47:20 +00001242MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001243 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001244 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001245 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001246
Dan Gohman104f57c2009-10-29 17:47:20 +00001247 // If not, we may be able to unfold a load and hoist that.
1248 // First test whether the instruction is loading from an amenable
1249 // memory location.
Evan Chengb8b0ad82011-01-20 08:34:58 +00001250 if (!MI->isInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001251 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001252
Dan Gohman104f57c2009-10-29 17:47:20 +00001253 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001254 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001255 unsigned NewOpc =
1256 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1257 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001258 /*UnfoldStore=*/false,
1259 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001260 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001261 const MCInstrDesc &MID = TII->get(NewOpc);
Craig Topperc0196b12014-04-14 00:51:57 +00001262 if (MID.getNumDefs() != 1) return nullptr;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001263 MachineFunction &MF = *MI->getParent()->getParent();
1264 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001265 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Chengd62719c2010-10-14 01:16:09 +00001266 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001267
Dan Gohman104f57c2009-10-29 17:47:20 +00001268 SmallVector<MachineInstr *, 2> NewMIs;
1269 bool Success =
1270 TII->unfoldMemoryOperand(MF, MI, Reg,
1271 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1272 NewMIs);
1273 (void)Success;
1274 assert(Success &&
1275 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1276 "succeeded!");
1277 assert(NewMIs.size() == 2 &&
1278 "Unfolded a load into multiple instructions!");
1279 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001280 MachineBasicBlock::iterator Pos = MI;
1281 MBB->insert(Pos, NewMIs[0]);
1282 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001283 // If unfolding produced a load that wasn't loop-invariant or profitable to
1284 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001285 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001286 NewMIs[0]->eraseFromParent();
1287 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001288 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001289 }
Evan Cheng87066f02010-10-20 22:03:58 +00001290
1291 // Update register pressure for the unfolded instruction.
1292 UpdateRegPressure(NewMIs[1]);
1293
Dan Gohman104f57c2009-10-29 17:47:20 +00001294 // Otherwise we successfully unfolded a load that we can hoist.
1295 MI->eraseFromParent();
1296 return NewMIs[0];
1297}
1298
Evan Chengf42b5af2009-11-03 21:40:02 +00001299void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1300 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1301 const MachineInstr *MI = &*I;
Evan Chengb8b0ad82011-01-20 08:34:58 +00001302 unsigned Opcode = MI->getOpcode();
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001303 CSEMap[Opcode].push_back(MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001304 }
1305}
1306
Evan Cheng7ff83192009-11-07 03:52:02 +00001307const MachineInstr*
1308MachineLICM::LookForDuplicate(const MachineInstr *MI,
1309 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng921152f2009-11-05 00:51:13 +00001310 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1311 const MachineInstr *PrevMI = PrevMIs[i];
Craig Topperc0196b12014-04-14 00:51:57 +00001312 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001313 return PrevMI;
1314 }
Craig Topperc0196b12014-04-14 00:51:57 +00001315 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001316}
1317
1318bool MachineLICM::EliminateCSE(MachineInstr *MI,
1319 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001320 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1321 // the undef property onto uses.
1322 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001323 return false;
1324
1325 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene55cf95c2010-01-05 00:03:48 +00001326 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001327
1328 // Replace virtual registers defined by MI by their counterparts defined
1329 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001330 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001331 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1332 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001333
1334 // Physical registers may not differ here.
1335 assert((!MO.isReg() || MO.getReg() == 0 ||
1336 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1337 MO.getReg() == Dup->getOperand(i).getReg()) &&
1338 "Instructions with different phys regs are not identical!");
1339
1340 if (MO.isReg() && MO.isDef() &&
Evan Chengaa563df2011-10-17 19:50:12 +00001341 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1342 Defs.push_back(i);
1343 }
1344
1345 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1346 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1347 unsigned Idx = Defs[i];
1348 unsigned Reg = MI->getOperand(Idx).getReg();
1349 unsigned DupReg = Dup->getOperand(Idx).getReg();
1350 OrigRCs.push_back(MRI->getRegClass(DupReg));
1351
1352 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1353 // Restore old RCs if more than one defs.
1354 for (unsigned j = 0; j != i; ++j)
1355 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1356 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001357 }
Evan Cheng921152f2009-11-05 00:51:13 +00001358 }
Evan Chengaa563df2011-10-17 19:50:12 +00001359
1360 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1361 unsigned Idx = Defs[i];
1362 unsigned Reg = MI->getOperand(Idx).getReg();
1363 unsigned DupReg = Dup->getOperand(Idx).getReg();
1364 MRI->replaceRegWith(Reg, DupReg);
1365 MRI->clearKillFlags(DupReg);
1366 }
1367
Evan Cheng7ff83192009-11-07 03:52:02 +00001368 MI->eraseFromParent();
1369 ++NumCSEed;
1370 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001371 }
1372 return false;
1373}
1374
Evan Chengaf138952011-10-12 00:09:14 +00001375/// MayCSE - Return true if the given instruction will be CSE'd if it's
1376/// hoisted out of the loop.
1377bool MachineLICM::MayCSE(MachineInstr *MI) {
1378 unsigned Opcode = MI->getOpcode();
1379 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1380 CI = CSEMap.find(Opcode);
1381 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1382 // the undef property onto uses.
1383 if (CI == CSEMap.end() || MI->isImplicitDef())
1384 return false;
1385
Craig Topperc0196b12014-04-14 00:51:57 +00001386 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001387}
1388
Bill Wendling70613b82008-05-12 19:38:32 +00001389/// Hoist - When an instruction is found to use only loop invariant operands
1390/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001391///
Evan Cheng87066f02010-10-20 22:03:58 +00001392bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman1b44f102009-10-28 03:21:57 +00001393 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001394 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001395 // If not, try unfolding a hoistable load.
1396 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001397 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001398 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001399
Dan Gohman79618d12009-01-15 22:01:38 +00001400 // Now move the instructions to the predecessor, inserting it before any
1401 // terminator instructions.
1402 DEBUG({
David Greene55cf95c2010-01-05 00:03:48 +00001403 dbgs() << "Hoisting " << *MI;
Dan Gohman3570f812010-06-22 17:25:57 +00001404 if (Preheader->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001405 dbgs() << " to MachineBasicBlock "
Dan Gohman3570f812010-06-22 17:25:57 +00001406 << Preheader->getName();
Dan Gohman1b44f102009-10-28 03:21:57 +00001407 if (MI->getParent()->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001408 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen2bbeaa82009-11-20 01:17:03 +00001409 << MI->getParent()->getName();
David Greene55cf95c2010-01-05 00:03:48 +00001410 dbgs() << "\n";
Dan Gohman79618d12009-01-15 22:01:38 +00001411 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001412
Evan Chengf42b5af2009-11-03 21:40:02 +00001413 // If this is the first instruction being hoisted to the preheader,
1414 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001415 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001416 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001417 FirstInLoop = false;
1418 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001419
Evan Cheng399660c2009-02-05 08:45:46 +00001420 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001421 unsigned Opcode = MI->getOpcode();
1422 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1423 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001424 if (!EliminateCSE(MI, CI)) {
1425 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001426 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001427
Evan Cheng87066f02010-10-20 22:03:58 +00001428 // Update register pressure for BBs from header to this block.
1429 UpdateBackTraceRegPressure(MI);
1430
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001431 // Clear the kill flags of any register this instruction defines,
1432 // since they may need to be live throughout the entire loop
1433 // rather than just live for part of it.
1434 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1435 MachineOperand &MO = MI->getOperand(i);
1436 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001437 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001438 }
1439
Evan Cheng399660c2009-02-05 08:45:46 +00001440 // Add to the CSE map.
1441 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001442 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001443 else
1444 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001445 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001446
Dan Gohman79618d12009-01-15 22:01:38 +00001447 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001448 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001449
1450 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001451}
Dan Gohman3570f812010-06-22 17:25:57 +00001452
1453MachineBasicBlock *MachineLICM::getCurPreheader() {
1454 // Determine the block to which to hoist instructions. If we can't find a
1455 // suitable loop predecessor, we can't do any hoisting.
1456
1457 // If we've tried to get a preheader and failed, don't try again.
1458 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001459 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001460
1461 if (!CurPreheader) {
1462 CurPreheader = CurLoop->getLoopPreheader();
1463 if (!CurPreheader) {
1464 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1465 if (!Pred) {
1466 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001467 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001468 }
1469
1470 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1471 if (!CurPreheader) {
1472 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001473 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001474 }
1475 }
1476 }
1477 return CurPreheader;
1478}