blob: 347429141045fe7d3e48c233ba77e3ee694c6ae3 [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
Evan Cheng44436302010-10-16 02:20:26 +000052STATISTIC(NumHoisted,
53 "Number of machine instructions hoisted out of loops");
54STATISTIC(NumLowRP,
55 "Number of instructions hoisted in low reg pressure situation");
56STATISTIC(NumHighLatency,
57 "Number of high latency instructions hoisted");
58STATISTIC(NumCSEed,
59 "Number of hoisted machine instructions CSEed");
Evan Cheng6ea59492010-04-07 00:41:17 +000060STATISTIC(NumPostRAHoisted,
61 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendling43751732007-12-08 01:47:01 +000062
Bill Wendlingfb706bc2007-12-07 21:42:31 +000063namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000064 class MachineLICM : public MachineFunctionPass {
Bill Wendling38236ef2007-12-11 23:27:51 +000065 const TargetInstrInfo *TII;
Benjamin Kramer56b31bd2013-01-11 20:05:37 +000066 const TargetLoweringBase *TLI;
Dan Gohmane30d63f2009-09-25 23:58:45 +000067 const TargetRegisterInfo *TRI;
Evan Cheng6ea59492010-04-07 00:41:17 +000068 const MachineFrameInfo *MFI;
Evan Chengd62719c2010-10-14 01:16:09 +000069 MachineRegisterInfo *MRI;
70 const InstrItineraryData *InstrItins;
Andrew Trickc40815d2012-02-08 21:23:03 +000071 bool PreRegAlloc;
Bill Wendlingb678ae72007-12-11 19:40:06 +000072
Bill Wendlingfb706bc2007-12-07 21:42:31 +000073 // Various analyses that we use...
Dan Gohmanbe8137b2009-10-07 17:38:06 +000074 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng058b9f02010-04-08 01:03:47 +000075 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendling70613b82008-05-12 19:38:32 +000076 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +000077
Bill Wendlingfb706bc2007-12-07 21:42:31 +000078 // State that is updated as we process loops
Bill Wendling70613b82008-05-12 19:38:32 +000079 bool Changed; // True if a loop is changed.
Evan Cheng032f3262010-05-29 00:06:36 +000080 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendling70613b82008-05-12 19:38:32 +000081 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohman79618d12009-01-15 22:01:38 +000082 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Cheng399660c2009-02-05 08:45:46 +000083
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +000084 // Exit blocks for CurLoop.
85 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
86
87 bool isExitBlock(const MachineBasicBlock *MBB) const {
88 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
89 ExitBlocks.end();
90 }
91
Evan Chengd62719c2010-10-14 01:16:09 +000092 // Track 'estimated' register pressure.
Evan Cheng44436302010-10-16 02:20:26 +000093 SmallSet<unsigned, 32> RegSeen;
Evan Chengd62719c2010-10-14 01:16:09 +000094 SmallVector<unsigned, 8> RegPressure;
Evan Cheng44436302010-10-16 02:20:26 +000095
96 // Register pressure "limit" per register class. If the pressure
97 // is higher than the limit, then it's considered high.
Evan Chengd62719c2010-10-14 01:16:09 +000098 SmallVector<unsigned, 8> RegLimit;
99
Evan Cheng44436302010-10-16 02:20:26 +0000100 // Register pressure on path leading from loop preheader to current BB.
101 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
102
Dale Johannesen329d4742010-07-29 17:45:24 +0000103 // For each opcode, keep a list of potential CSE instructions.
Evan Chengf42b5af2009-11-03 21:40:02 +0000104 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Cheng6ea59492010-04-07 00:41:17 +0000105
Evan Chengf192ca02011-10-11 23:48:44 +0000106 enum {
107 SpeculateFalse = 0,
108 SpeculateTrue = 1,
109 SpeculateUnknown = 2
110 };
111
Devang Patel453d4012011-10-11 18:09:58 +0000112 // If a MBB does not dominate loop exiting blocks then it may not safe
113 // to hoist loads from this block.
Evan Chengf192ca02011-10-11 23:48:44 +0000114 // Tri-state: 0 - false, 1 - true, 2 - unknown
115 unsigned SpeculationState;
Devang Patel453d4012011-10-11 18:09:58 +0000116
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000117 public:
118 static char ID; // Pass identification, replacement for typeid
Evan Cheng6ea59492010-04-07 00:41:17 +0000119 MachineLICM() :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000120 MachineFunctionPass(ID), PreRegAlloc(true) {
121 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
122 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000123
124 explicit MachineLICM(bool PreRA) :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000125 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
126 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
127 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000128
Craig Topper4584cd52014-03-07 09:26:03 +0000129 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000130
Craig Topper4584cd52014-03-07 09:26:03 +0000131 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000132 AU.addRequired<MachineLoopInfo>();
133 AU.addRequired<MachineDominatorTree>();
Dan Gohmanbe8137b2009-10-07 17:38:06 +0000134 AU.addRequired<AliasAnalysis>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000135 AU.addPreserved<MachineLoopInfo>();
136 AU.addPreserved<MachineDominatorTree>();
137 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000138 }
Evan Cheng399660c2009-02-05 08:45:46 +0000139
Craig Topper4584cd52014-03-07 09:26:03 +0000140 void releaseMemory() override {
Evan Cheng44436302010-10-16 02:20:26 +0000141 RegSeen.clear();
Evan Chengd62719c2010-10-14 01:16:09 +0000142 RegPressure.clear();
143 RegLimit.clear();
Evan Cheng63c76082010-10-19 18:58:51 +0000144 BackTrace.clear();
Evan Cheng399660c2009-02-05 08:45:46 +0000145 CSEMap.clear();
146 }
147
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000148 private:
Evan Cheng058b9f02010-04-08 01:03:47 +0000149 /// CandidateInfo - Keep track of information about hoisting candidates.
150 struct CandidateInfo {
151 MachineInstr *MI;
Evan Cheng058b9f02010-04-08 01:03:47 +0000152 unsigned Def;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000153 int FI;
154 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
155 : MI(mi), Def(def), FI(fi) {}
Evan Cheng058b9f02010-04-08 01:03:47 +0000156 };
157
158 /// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
159 /// invariants out to the preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000160 void HoistRegionPostRA();
Evan Cheng058b9f02010-04-08 01:03:47 +0000161
162 /// HoistPostRA - When an instruction is found to only use loop invariant
163 /// operands that is safe to hoist, this instruction is called to do the
164 /// dirty work.
165 void HoistPostRA(MachineInstr *MI, unsigned Def);
166
167 /// ProcessMI - Examine the instruction for potentai LICM candidate. Also
168 /// gather register def and frame object update information.
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000169 void ProcessMI(MachineInstr *MI,
170 BitVector &PhysRegDefs,
171 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000172 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000173 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng058b9f02010-04-08 01:03:47 +0000174
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000175 /// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the
176 /// current loop.
177 void AddToLiveIns(unsigned Reg);
Evan Cheng058b9f02010-04-08 01:03:47 +0000178
Evan Cheng0a2aff22010-04-13 18:16:00 +0000179 /// IsLICMCandidate - Returns true if the instruction may be a suitable
Chris Lattner0b7ae202010-07-12 00:00:35 +0000180 /// candidate for LICM. e.g. If the instruction is a call, then it's
181 /// obviously not safe to hoist it.
Evan Cheng0a2aff22010-04-13 18:16:00 +0000182 bool IsLICMCandidate(MachineInstr &I);
183
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000184 /// IsLoopInvariantInst - Returns true if the instruction is loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000185 /// invariant. I.e., all virtual register operands are defined outside of
186 /// the loop, physical registers aren't accessed (explicitly or implicitly),
187 /// and the instruction is hoistable.
Andrew Trick5209c732012-02-08 21:23:00 +0000188 ///
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000189 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000190
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000191 /// HasLoopPHIUse - Return true if the specified instruction is used by any
192 /// phi node in the current loop.
193 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengef42bea2011-04-11 21:09:18 +0000194
Evan Cheng63c76082010-10-19 18:58:51 +0000195 /// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
196 /// and an use in the current loop, return true if the target considered
197 /// it 'high'.
Evan Chenge96b8d72010-10-26 02:08:50 +0000198 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
199 unsigned Reg) const;
200
201 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Chengd62719c2010-10-14 01:16:09 +0000202
Evan Cheng87066f02010-10-20 22:03:58 +0000203 /// CanCauseHighRegPressure - Visit BBs from header to current BB,
204 /// check if hoisting an instruction of the given cost matrix can cause high
Evan Cheng44436302010-10-16 02:20:26 +0000205 /// register pressure.
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +0000206 bool CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost, bool Cheap);
Evan Cheng87066f02010-10-20 22:03:58 +0000207
208 /// UpdateBackTraceRegPressure - Traverse the back trace from header to
209 /// the current block and update their register pressures to reflect the
210 /// effect of hoisting MI from the current block to the preheader.
211 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng44436302010-10-16 02:20:26 +0000212
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000213 /// IsProfitableToHoist - Return true if it is potentially profitable to
214 /// hoist the given loop invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +0000215 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000216
Devang Patel453d4012011-10-11 18:09:58 +0000217 /// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
218 /// If not then a load from this mbb may not be safe to hoist.
219 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
220
Pete Cooper1eed5b52011-12-22 02:05:40 +0000221 void EnterScope(MachineBasicBlock *MBB);
222
223 void ExitScope(MachineBasicBlock *MBB);
224
225 /// ExitScopeIfDone - Destroy scope for the MBB that corresponds to given
226 /// dominator tree node if its a leaf or all of its children are done. Walk
227 /// up the dominator tree to destroy ancestors which are now done.
228 void ExitScopeIfDone(MachineDomTreeNode *Node,
229 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
230 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap);
231
232 /// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
233 /// blocks dominated by the specified header block, and that are in the
234 /// current loop) in depth first order w.r.t the DominatorTree. This allows
235 /// us to visit definitions before uses, allowing us to hoist a loop body in
236 /// one pass without iteration.
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000237 ///
Pete Cooper1eed5b52011-12-22 02:05:40 +0000238 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
239 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000240
Evan Cheng90da66b2011-09-01 01:45:00 +0000241 /// getRegisterClassIDAndCost - For a given MI, register, and the operand
242 /// index, return the ID and cost of its representative register class by
243 /// reference.
244 void getRegisterClassIDAndCost(const MachineInstr *MI,
245 unsigned Reg, unsigned OpIdx,
246 unsigned &RCId, unsigned &RCCost) const;
247
Evan Cheng44436302010-10-16 02:20:26 +0000248 /// InitRegPressure - Find all virtual register references that are liveout
249 /// of the preheader to initialize the starting "register pressure". Note
250 /// this does not count live through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000251 void InitRegPressure(MachineBasicBlock *BB);
252
Evan Cheng87066f02010-10-20 22:03:58 +0000253 /// UpdateRegPressure - Update estimate of register pressure after the
254 /// specified instruction.
255 void UpdateRegPressure(const MachineInstr *MI);
Evan Chengd62719c2010-10-14 01:16:09 +0000256
Dan Gohman104f57c2009-10-29 17:47:20 +0000257 /// ExtractHoistableLoad - Unfold a load from the given machineinstr if
258 /// the load itself could be hoisted. Return the unfolded and hoistable
259 /// load, or null if the load couldn't be unfolded or if it wouldn't
260 /// be hoistable.
261 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
262
Evan Cheng7ff83192009-11-07 03:52:02 +0000263 /// LookForDuplicate - Find an instruction amount PrevMIs that is a
264 /// duplicate of MI. Return this instruction if it's found.
265 const MachineInstr *LookForDuplicate(const MachineInstr *MI,
266 std::vector<const MachineInstr*> &PrevMIs);
267
Evan Cheng921152f2009-11-05 00:51:13 +0000268 /// EliminateCSE - Given a LICM'ed instruction, look for an instruction on
269 /// the preheader that compute the same value. If it's found, do a RAU on
270 /// with the definition of the existing instruction rather than hoisting
271 /// the instruction to the preheader.
272 bool EliminateCSE(MachineInstr *MI,
273 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI);
274
Evan Chengaf138952011-10-12 00:09:14 +0000275 /// MayCSE - Return true if the given instruction will be CSE'd if it's
276 /// hoisted out of the loop.
277 bool MayCSE(MachineInstr *MI);
278
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000279 /// Hoist - When an instruction is found to only use loop invariant operands
280 /// that is safe to hoist, this instruction is called to do the dirty work.
Evan Cheng87066f02010-10-20 22:03:58 +0000281 /// It returns true if the instruction is hoisted.
282 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Chengf42b5af2009-11-03 21:40:02 +0000283
284 /// InitCSEMap - Initialize the CSE map with instructions that are in the
285 /// current loop preheader that may become duplicates of instructions that
286 /// are hoisted out of the loop.
287 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman3570f812010-06-22 17:25:57 +0000288
289 /// getCurPreheader - Get the preheader for the current loop, splitting
290 /// a critical edge if needed.
291 MachineBasicBlock *getCurPreheader();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000292 };
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000293} // end anonymous namespace
294
Dan Gohmand78c4002008-05-13 00:00:25 +0000295char MachineLICM::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000296char &llvm::MachineLICMID = MachineLICM::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000297INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
298 "Machine Loop Invariant Code Motion", false, false)
299INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
300INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
301INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
302INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000303 "Machine Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000304
Dan Gohman3570f812010-06-22 17:25:57 +0000305/// LoopIsOuterMostWithPredecessor - Test if the given loop is the outer-most
306/// loop that has a unique predecessor.
307static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohman7929c442010-07-09 18:49:45 +0000308 // Check whether this loop even has a unique predecessor.
309 if (!CurLoop->getLoopPredecessor())
310 return false;
311 // Ok, now check to see if any of its outer loops do.
Dan Gohman79618d12009-01-15 22:01:38 +0000312 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman3570f812010-06-22 17:25:57 +0000313 if (L->getLoopPredecessor())
Dan Gohman79618d12009-01-15 22:01:38 +0000314 return false;
Dan Gohman7929c442010-07-09 18:49:45 +0000315 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohman79618d12009-01-15 22:01:38 +0000316 return true;
317}
318
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000319bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000320 if (skipOptnoneFunction(*MF.getFunction()))
321 return false;
322
Evan Cheng032f3262010-05-29 00:06:36 +0000323 Changed = FirstInLoop = false;
Eric Christopherb65c7b92014-10-14 06:26:57 +0000324 TII = MF.getSubtarget().getInstrInfo();
325 TLI = MF.getSubtarget().getTargetLowering();
326 TRI = MF.getSubtarget().getRegisterInfo();
Evan Cheng6ea59492010-04-07 00:41:17 +0000327 MFI = MF.getFrameInfo();
Evan Chengd62719c2010-10-14 01:16:09 +0000328 MRI = &MF.getRegInfo();
Eric Christopherb65c7b92014-10-14 06:26:57 +0000329 InstrItins = MF.getSubtarget().getInstrItineraryData();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000330
Andrew Trickc40815d2012-02-08 21:23:03 +0000331 PreRegAlloc = MRI->isSSA();
332
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000333 if (PreRegAlloc)
334 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
335 else
336 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
Craig Toppera538d832012-08-22 06:07:19 +0000337 DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000338
Evan Chengd62719c2010-10-14 01:16:09 +0000339 if (PreRegAlloc) {
340 // Estimate register pressure during pre-regalloc pass.
341 unsigned NumRC = TRI->getNumRegClasses();
342 RegPressure.resize(NumRC);
Evan Chengd62719c2010-10-14 01:16:09 +0000343 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000344 RegLimit.resize(NumRC);
Evan Chengd62719c2010-10-14 01:16:09 +0000345 for (TargetRegisterInfo::regclass_iterator I = TRI->regclass_begin(),
346 E = TRI->regclass_end(); I != E; ++I)
Cameron Zwarichdf616942011-03-07 21:56:36 +0000347 RegLimit[(*I)->getID()] = TRI->getRegPressureLimit(*I, MF);
Evan Chengd62719c2010-10-14 01:16:09 +0000348 }
349
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000350 // Get our Loop information...
Evan Cheng058b9f02010-04-08 01:03:47 +0000351 MLI = &getAnalysis<MachineLoopInfo>();
352 DT = &getAnalysis<MachineDominatorTree>();
353 AA = &getAnalysis<AliasAnalysis>();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000354
Dan Gohman7929c442010-07-09 18:49:45 +0000355 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
356 while (!Worklist.empty()) {
357 CurLoop = Worklist.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000358 CurPreheader = nullptr;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000359 ExitBlocks.clear();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000360
Evan Cheng058b9f02010-04-08 01:03:47 +0000361 // If this is done before regalloc, only visit outer-most preheader-sporting
362 // loops.
Dan Gohman7929c442010-07-09 18:49:45 +0000363 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
364 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohman79618d12009-01-15 22:01:38 +0000365 continue;
Dan Gohman7929c442010-07-09 18:49:45 +0000366 }
Dan Gohman79618d12009-01-15 22:01:38 +0000367
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000368 CurLoop->getExitBlocks(ExitBlocks);
369
Evan Cheng6ea59492010-04-07 00:41:17 +0000370 if (!PreRegAlloc)
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000371 HoistRegionPostRA();
Evan Cheng6ea59492010-04-07 00:41:17 +0000372 else {
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000373 // CSEMap is initialized for loop header when the first instruction is
374 // being hoisted.
375 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng032f3262010-05-29 00:06:36 +0000376 FirstInLoop = true;
Pete Cooper1eed5b52011-12-22 02:05:40 +0000377 HoistOutOfLoop(N);
Evan Cheng6ea59492010-04-07 00:41:17 +0000378 CSEMap.clear();
379 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000380 }
381
382 return Changed;
383}
384
Evan Cheng058b9f02010-04-08 01:03:47 +0000385/// InstructionStoresToFI - Return true if instruction stores to the
386/// specified frame.
387static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
388 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
389 oe = MI->memoperands_end(); o != oe; ++o) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000390 if (!(*o)->isStore() || !(*o)->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000391 continue;
392 if (const FixedStackPseudoSourceValue *Value =
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000393 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000394 if (Value->getFrameIndex() == FI)
395 return true;
396 }
397 }
398 return false;
399}
400
401/// ProcessMI - Examine the instruction for potentai LICM candidate. Also
402/// gather register def and frame object update information.
403void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000404 BitVector &PhysRegDefs,
405 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000406 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000407 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000408 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000409 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000410 unsigned Def = 0;
411 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
412 const MachineOperand &MO = MI->getOperand(i);
413 if (MO.isFI()) {
414 // Remember if the instruction stores to the frame index.
415 int FI = MO.getIndex();
416 if (!StoredFIs.count(FI) &&
417 MFI->isSpillSlotObjectIndex(FI) &&
418 InstructionStoresToFI(MI, FI))
419 StoredFIs.insert(FI);
Evan Cheng89e74792010-04-13 20:21:05 +0000420 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000421 continue;
422 }
423
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000424 // We can't hoist an instruction defining a physreg that is clobbered in
425 // the loop.
426 if (MO.isRegMask()) {
Jakob Stoklund Olesen5e1ac452012-02-02 23:52:57 +0000427 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000428 continue;
429 }
430
Evan Cheng058b9f02010-04-08 01:03:47 +0000431 if (!MO.isReg())
432 continue;
433 unsigned Reg = MO.getReg();
434 if (!Reg)
435 continue;
436 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
437 "Not expecting virtual register!");
438
Evan Cheng0a2aff22010-04-13 18:16:00 +0000439 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000440 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-04-13 20:21:05 +0000441 // If it's using a non-loop-invariant register, then it's obviously not
442 // safe to hoist.
443 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000444 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000445 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000446
447 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000448 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
449 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000450 if (!MO.isDead())
451 // Non-dead implicit def? This cannot be hoisted.
452 RuledOut = true;
453 // No need to check if a dead implicit def is also defined by
454 // another instruction.
455 continue;
456 }
457
458 // FIXME: For now, avoid instructions with multiple defs, unless
459 // it's a dead implicit def.
460 if (Def)
461 RuledOut = true;
462 else
463 Def = Reg;
464
465 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000466 // register, then this is not safe. Two defs is indicated by setting a
467 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000468 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000469 if (PhysRegDefs.test(*AS))
470 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000471 PhysRegDefs.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000472 }
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000473 if (PhysRegClobbers.test(Reg))
474 // MI defined register is seen defined by another instruction in
475 // the loop, it cannot be a LICM candidate.
476 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000477 }
478
Evan Cheng0a2aff22010-04-13 18:16:00 +0000479 // Only consider reloads for now and remats which do not have register
480 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000481 if (Def && !RuledOut) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000482 int FI = INT_MIN;
Evan Cheng89e74792010-04-13 20:21:05 +0000483 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng0a2aff22010-04-13 18:16:00 +0000484 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
485 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000486 }
487}
488
489/// HoistRegionPostRA - Walk the specified region of the CFG and hoist loop
490/// invariants out to the preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000491void MachineLICM::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000492 MachineBasicBlock *Preheader = getCurPreheader();
493 if (!Preheader)
494 return;
495
Evan Cheng6ea59492010-04-07 00:41:17 +0000496 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000497 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
498 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000499
Evan Cheng058b9f02010-04-08 01:03:47 +0000500 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000501 SmallSet<int, 32> StoredFIs;
502
503 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000504 // collect potential LICM candidates.
Benjamin Kramer7d605262013-09-15 22:04:42 +0000505 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000506 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
507 MachineBasicBlock *BB = Blocks[i];
Bill Wendling918cea22011-10-12 02:58:01 +0000508
509 // If the header of the loop containing this basic block is a landing pad,
510 // then don't try to hoist instructions out of this loop.
511 const MachineLoop *ML = MLI->getLoopFor(BB);
512 if (ML && ML->getHeader()->isLandingPad()) continue;
513
Evan Cheng6ea59492010-04-07 00:41:17 +0000514 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000515 // FIXME: That means a reload that're reused in successor block(s) will not
516 // be LICM'ed.
Dan Gohman9d2d0532010-04-13 16:57:55 +0000517 for (MachineBasicBlock::livein_iterator I = BB->livein_begin(),
Evan Cheng6ea59492010-04-07 00:41:17 +0000518 E = BB->livein_end(); I != E; ++I) {
519 unsigned Reg = *I;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000520 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
521 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000522 }
523
Evan Chengf192ca02011-10-11 23:48:44 +0000524 SpeculationState = SpeculateUnknown;
Evan Cheng6ea59492010-04-07 00:41:17 +0000525 for (MachineBasicBlock::iterator
526 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Cheng6ea59492010-04-07 00:41:17 +0000527 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000528 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng6ea59492010-04-07 00:41:17 +0000529 }
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000530 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000531
Evan Cheng7fede872012-03-27 01:50:58 +0000532 // Gather the registers read / clobbered by the terminator.
533 BitVector TermRegs(NumRegs);
534 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
535 if (TI != Preheader->end()) {
536 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
537 const MachineOperand &MO = TI->getOperand(i);
538 if (!MO.isReg())
539 continue;
540 unsigned Reg = MO.getReg();
541 if (!Reg)
542 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000543 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
544 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000545 }
546 }
547
Evan Cheng6ea59492010-04-07 00:41:17 +0000548 // Now evaluate whether the potential candidates qualify.
549 // 1. Check if the candidate defined register is defined by another
550 // instruction in the loop.
551 // 2. If the candidate is a load from stack slot (always true for now),
552 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000553 // 3. Make sure candidate def should not clobber
554 // registers read by the terminator. Similarly its def should not be
555 // clobbered by the terminator.
Evan Cheng6ea59492010-04-07 00:41:17 +0000556 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000557 if (Candidates[i].FI != INT_MIN &&
558 StoredFIs.count(Candidates[i].FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000559 continue;
560
Evan Cheng7fede872012-03-27 01:50:58 +0000561 unsigned Def = Candidates[i].Def;
562 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000563 bool Safe = true;
564 MachineInstr *MI = Candidates[i].MI;
Evan Chengcce672c2010-04-13 20:25:29 +0000565 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
566 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng87585d72010-04-13 22:13:34 +0000567 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000568 continue;
Evan Cheng7fede872012-03-27 01:50:58 +0000569 unsigned Reg = MO.getReg();
570 if (PhysRegDefs.test(Reg) ||
571 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000572 // If it's using a non-loop-invariant register, then it's obviously
573 // not safe to hoist.
574 Safe = false;
575 break;
576 }
577 }
578 if (Safe)
579 HoistPostRA(MI, Candidates[i].Def);
580 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000581 }
582}
583
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000584/// AddToLiveIns - Add register 'Reg' to the livein sets of BBs in the current
585/// loop, and make sure it is not killed by any instructions in the loop.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000586void MachineLICM::AddToLiveIns(unsigned Reg) {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000587 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000588 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
589 MachineBasicBlock *BB = Blocks[i];
590 if (!BB->isLiveIn(Reg))
591 BB->addLiveIn(Reg);
592 for (MachineBasicBlock::iterator
593 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
594 MachineInstr *MI = &*MII;
595 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
596 MachineOperand &MO = MI->getOperand(i);
597 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
598 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
599 MO.setIsKill(false);
600 }
601 }
602 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000603}
604
605/// HoistPostRA - When an instruction is found to only use loop invariant
606/// operands that is safe to hoist, this instruction is called to do the
607/// dirty work.
608void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000609 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000610
Evan Cheng6ea59492010-04-07 00:41:17 +0000611 // Now move the instructions to the predecessor, inserting it before any
612 // terminator instructions.
Jakob Stoklund Olesen90823532012-01-23 21:01:11 +0000613 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
614 << MI->getParent()->getNumber() << ": " << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000615
616 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000617 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000618 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000619
Andrew Trick5209c732012-02-08 21:23:00 +0000620 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000621 // loop invariant must be kept live throughout the whole loop. This is
622 // important to ensure later passes do not scavenge the def register.
623 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000624
625 ++NumPostRAHoisted;
626 Changed = true;
627}
628
Devang Patel453d4012011-10-11 18:09:58 +0000629// IsGuaranteedToExecute - Check if this mbb is guaranteed to execute.
630// If not then a load from this mbb may not be safe to hoist.
631bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000632 if (SpeculationState != SpeculateUnknown)
633 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000634
Devang Patel453d4012011-10-11 18:09:58 +0000635 if (BB != CurLoop->getHeader()) {
636 // Check loop exiting blocks.
637 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
638 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
639 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
640 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000641 SpeculationState = SpeculateTrue;
642 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000643 }
644 }
645
Evan Chengf192ca02011-10-11 23:48:44 +0000646 SpeculationState = SpeculateFalse;
647 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000648}
649
Pete Cooper1eed5b52011-12-22 02:05:40 +0000650void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
651 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000652
Pete Cooper1eed5b52011-12-22 02:05:40 +0000653 // Remember livein register pressure.
654 BackTrace.push_back(RegPressure);
655}
Bill Wendling918cea22011-10-12 02:58:01 +0000656
Pete Cooper1eed5b52011-12-22 02:05:40 +0000657void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
658 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
659 BackTrace.pop_back();
660}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000661
Pete Cooper1eed5b52011-12-22 02:05:40 +0000662/// ExitScopeIfDone - Destroy scope for the MBB that corresponds to the given
663/// dominator tree node if its a leaf or all of its children are done. Walk
664/// up the dominator tree to destroy ancestors which are now done.
665void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Chengda468322012-01-10 22:27:32 +0000666 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
667 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000668 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000669 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000670
Pete Cooper1eed5b52011-12-22 02:05:40 +0000671 // Pop scope.
672 ExitScope(Node->getBlock());
673
674 // Now traverse upwards to pop ancestors whose offsprings are all done.
675 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
676 unsigned Left = --OpenChildren[Parent];
677 if (Left != 0)
678 break;
679 ExitScope(Parent->getBlock());
680 Node = Parent;
681 }
682}
683
684/// HoistOutOfLoop - Walk the specified loop in the CFG (defined by all
685/// blocks dominated by the specified header block, and that are in the
686/// current loop) in depth first order w.r.t the DominatorTree. This allows
687/// us to visit definitions before uses, allowing us to hoist a loop body in
688/// one pass without iteration.
689///
690void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
691 SmallVector<MachineDomTreeNode*, 32> Scopes;
692 SmallVector<MachineDomTreeNode*, 8> WorkList;
693 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
694 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
695
696 // Perform a DFS walk to determine the order of visit.
697 WorkList.push_back(HeaderN);
698 do {
699 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000700 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000701 MachineBasicBlock *BB = Node->getBlock();
702
703 // If the header of the loop containing this basic block is a landing pad,
704 // then don't try to hoist instructions out of this loop.
705 const MachineLoop *ML = MLI->getLoopFor(BB);
706 if (ML && ML->getHeader()->isLandingPad())
707 continue;
708
709 // If this subregion is not in the top level loop at all, exit.
710 if (!CurLoop->contains(BB))
711 continue;
712
713 Scopes.push_back(Node);
714 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
715 unsigned NumChildren = Children.size();
716
717 // Don't hoist things out of a large switch statement. This often causes
718 // code to be hoisted that wasn't going to be executed, and increases
719 // register pressure in a situation where it's likely to matter.
720 if (BB->succ_size() >= 25)
721 NumChildren = 0;
722
723 OpenChildren[Node] = NumChildren;
724 // Add children in reverse order as then the next popped worklist node is
725 // the first child of this node. This means we ultimately traverse the
726 // DOM tree in exactly the same order as if we'd recursed.
727 for (int i = (int)NumChildren-1; i >= 0; --i) {
728 MachineDomTreeNode *Child = Children[i];
729 ParentMap[Child] = Node;
730 WorkList.push_back(Child);
731 }
732 } while (!WorkList.empty());
733
734 if (Scopes.size() != 0) {
735 MachineBasicBlock *Preheader = getCurPreheader();
736 if (!Preheader)
737 return;
738
Evan Cheng87066f02010-10-20 22:03:58 +0000739 // Compute registers which are livein into the loop headers.
Evan Cheng63c76082010-10-19 18:58:51 +0000740 RegSeen.clear();
741 BackTrace.clear();
742 InitRegPressure(Preheader);
Daniel Dunbar418204e2010-10-19 17:14:24 +0000743 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000744
Pete Cooper1eed5b52011-12-22 02:05:40 +0000745 // Now perform LICM.
746 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
747 MachineDomTreeNode *Node = Scopes[i];
748 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000749
Pete Cooper1eed5b52011-12-22 02:05:40 +0000750 MachineBasicBlock *Preheader = getCurPreheader();
751 if (!Preheader)
752 continue;
753
754 EnterScope(MBB);
755
756 // Process the block
757 SpeculationState = SpeculateUnknown;
758 for (MachineBasicBlock::iterator
759 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
760 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
761 MachineInstr *MI = &*MII;
762 if (!Hoist(MI, Preheader))
763 UpdateRegPressure(MI);
764 MII = NextMII;
765 }
766
767 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
768 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000769 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000770}
771
Evan Cheng87066f02010-10-20 22:03:58 +0000772static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
773 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
774}
775
Evan Cheng90da66b2011-09-01 01:45:00 +0000776/// getRegisterClassIDAndCost - For a given MI, register, and the operand
777/// index, return the ID and cost of its representative register class.
778void
779MachineLICM::getRegisterClassIDAndCost(const MachineInstr *MI,
780 unsigned Reg, unsigned OpIdx,
781 unsigned &RCId, unsigned &RCCost) const {
782 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
Patrik Hagglund05394352012-12-13 18:45:35 +0000783 MVT VT = *RC->vt_begin();
Owen Andersonca2f78a2011-11-16 01:02:57 +0000784 if (VT == MVT::Untyped) {
Evan Cheng90da66b2011-09-01 01:45:00 +0000785 RCId = RC->getID();
786 RCCost = 1;
787 } else {
788 RCId = TLI->getRepRegClassFor(VT)->getID();
789 RCCost = TLI->getRepRegClassCostFor(VT);
790 }
791}
Andrew Trick5209c732012-02-08 21:23:00 +0000792
Evan Cheng44436302010-10-16 02:20:26 +0000793/// InitRegPressure - Find all virtual register references that are liveout of
794/// the preheader to initialize the starting "register pressure". Note this
795/// does not count live through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000796void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000797 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000798
Evan Cheng87066f02010-10-20 22:03:58 +0000799 // If the preheader has only a single predecessor and it ends with a
800 // fallthrough or an unconditional branch, then scan its predecessor for live
801 // defs as well. This happens whenever the preheader is created by splitting
802 // the critical edge from the loop predecessor to the loop header.
803 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000804 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000805 SmallVector<MachineOperand, 4> Cond;
806 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
807 InitRegPressure(*BB->pred_begin());
808 }
809
Evan Chengd62719c2010-10-14 01:16:09 +0000810 for (MachineBasicBlock::iterator MII = BB->begin(), E = BB->end();
811 MII != E; ++MII) {
812 MachineInstr *MI = &*MII;
813 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
814 const MachineOperand &MO = MI->getOperand(i);
815 if (!MO.isReg() || MO.isImplicit())
816 continue;
817 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000818 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000819 continue;
Evan Chengd62719c2010-10-14 01:16:09 +0000820
Andrew Trick2006bbe2010-10-19 02:50:50 +0000821 bool isNew = RegSeen.insert(Reg);
Evan Cheng90da66b2011-09-01 01:45:00 +0000822 unsigned RCId, RCCost;
823 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng44436302010-10-16 02:20:26 +0000824 if (MO.isDef())
Evan Cheng90da66b2011-09-01 01:45:00 +0000825 RegPressure[RCId] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000826 else {
Evan Cheng87066f02010-10-20 22:03:58 +0000827 bool isKill = isOperandKill(MO, MRI);
828 if (isNew && !isKill)
Evan Cheng44436302010-10-16 02:20:26 +0000829 // Haven't seen this, it must be a livein.
Evan Cheng90da66b2011-09-01 01:45:00 +0000830 RegPressure[RCId] += RCCost;
Evan Cheng87066f02010-10-20 22:03:58 +0000831 else if (!isNew && isKill)
Evan Cheng90da66b2011-09-01 01:45:00 +0000832 RegPressure[RCId] -= RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000833 }
Evan Chengd62719c2010-10-14 01:16:09 +0000834 }
835 }
836}
837
Evan Cheng87066f02010-10-20 22:03:58 +0000838/// UpdateRegPressure - Update estimate of register pressure after the
839/// specified instruction.
840void MachineLICM::UpdateRegPressure(const MachineInstr *MI) {
841 if (MI->isImplicitDef())
842 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000843
Evan Cheng87066f02010-10-20 22:03:58 +0000844 SmallVector<unsigned, 4> Defs;
Evan Chengd62719c2010-10-14 01:16:09 +0000845 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
846 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000847 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000848 continue;
849 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000850 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000851 continue;
852
Andrew Trick2006bbe2010-10-19 02:50:50 +0000853 bool isNew = RegSeen.insert(Reg);
Evan Cheng63c76082010-10-19 18:58:51 +0000854 if (MO.isDef())
855 Defs.push_back(Reg);
Evan Cheng87066f02010-10-20 22:03:58 +0000856 else if (!isNew && isOperandKill(MO, MRI)) {
Evan Cheng90da66b2011-09-01 01:45:00 +0000857 unsigned RCId, RCCost;
858 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng87066f02010-10-20 22:03:58 +0000859 if (RCCost > RegPressure[RCId])
860 RegPressure[RCId] = 0;
861 else
Evan Cheng63c76082010-10-19 18:58:51 +0000862 RegPressure[RCId] -= RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000863 }
Evan Chengd62719c2010-10-14 01:16:09 +0000864 }
Evan Chengd62719c2010-10-14 01:16:09 +0000865
Evan Cheng90da66b2011-09-01 01:45:00 +0000866 unsigned Idx = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000867 while (!Defs.empty()) {
868 unsigned Reg = Defs.pop_back_val();
Evan Cheng90da66b2011-09-01 01:45:00 +0000869 unsigned RCId, RCCost;
870 getRegisterClassIDAndCost(MI, Reg, Idx, RCId, RCCost);
Evan Chengd62719c2010-10-14 01:16:09 +0000871 RegPressure[RCId] += RCCost;
Evan Cheng90da66b2011-09-01 01:45:00 +0000872 ++Idx;
Evan Chengd62719c2010-10-14 01:16:09 +0000873 }
874}
875
Andrew Trick5209c732012-02-08 21:23:00 +0000876/// isLoadFromGOTOrConstantPool - Return true if this machine instruction
Devang Patel1d8ab462011-10-20 17:42:23 +0000877/// loads from global offset table or constant pool.
878static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng7f8e5632011-12-07 07:15:52 +0000879 assert (MI.mayLoad() && "Expected MI that loads!");
Devang Patel69a45652011-10-17 17:35:01 +0000880 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
Andrew Trick5209c732012-02-08 21:23:00 +0000881 E = MI.memoperands_end(); I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000882 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
883 if (PSV == PSV->getGOT() || PSV == PSV->getConstantPool())
884 return true;
Devang Patel69a45652011-10-17 17:35:01 +0000885 }
886 }
887 return false;
888}
889
Evan Cheng0a2aff22010-04-13 18:16:00 +0000890/// IsLICMCandidate - Returns true if the instruction may be a suitable
891/// candidate for LICM. e.g. If the instruction is a call, then it's obviously
892/// not safe to hoist it.
893bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +0000894 // Check if it's safe to move the instruction.
895 bool DontMoveAcrossStore = true;
896 if (!I.isSafeToMove(TII, AA, DontMoveAcrossStore))
Chris Lattnerc8226f32008-01-10 23:08:24 +0000897 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000898
899 // If it is load then check if it is guaranteed to execute by making sure that
900 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +0000901 // the loop which does not execute this load, so we can't hoist it. Loads
902 // from constant memory are not safe to speculate all the time, for example
903 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +0000904 // Stores and side effects are already checked by isSafeToMove.
Andrew Trick5209c732012-02-08 21:23:00 +0000905 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +0000906 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +0000907 return false;
908
Evan Cheng0a2aff22010-04-13 18:16:00 +0000909 return true;
910}
911
912/// IsLoopInvariantInst - Returns true if the instruction is loop
913/// invariant. I.e., all virtual register operands are defined outside of the
914/// loop, physical registers aren't accessed explicitly, and there are no side
915/// effects that aren't captured by the operands or other flags.
Andrew Trick5209c732012-02-08 21:23:00 +0000916///
Evan Cheng0a2aff22010-04-13 18:16:00 +0000917bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
918 if (!IsLICMCandidate(I))
919 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +0000920
Bill Wendling70613b82008-05-12 19:38:32 +0000921 // The instruction is loop invariant if all of its operands are.
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000922 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
923 const MachineOperand &MO = I.getOperand(i);
924
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000925 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +0000926 continue;
927
Dan Gohman79618d12009-01-15 22:01:38 +0000928 unsigned Reg = MO.getReg();
929 if (Reg == 0) continue;
930
931 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmane30d63f2009-09-25 23:58:45 +0000932 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +0000933 if (MO.isUse()) {
934 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +0000935 // and we can freely move its uses. Alternatively, if it's allocatable,
936 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesen86ae07f2012-01-16 22:34:08 +0000937 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmane30d63f2009-09-25 23:58:45 +0000938 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000939 // Otherwise it's safe to move.
940 continue;
941 } else if (!MO.isDead()) {
942 // A def that isn't dead. We can't move it.
943 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +0000944 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
945 // If the reg is live into the loop, we can't hoist an instruction
946 // which would clobber it.
947 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000948 }
949 }
Bill Wendlingcd01e892008-08-20 20:32:05 +0000950
951 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000952 continue;
953
Evan Chengd62719c2010-10-14 01:16:09 +0000954 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +0000955 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000956
957 // If the loop contains the definition of an operand, then the instruction
958 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +0000959 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000960 return false;
961 }
962
963 // If we got this far, the instruction is loop invariant!
964 return true;
965}
966
Evan Cheng399660c2009-02-05 08:45:46 +0000967
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000968/// HasLoopPHIUse - Return true if the specified instruction is used by a
969/// phi node and hoisting it could cause a copy to be inserted.
970bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
971 SmallVector<const MachineInstr*, 8> Work(1, MI);
972 do {
973 MI = Work.pop_back_val();
974 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
975 if (!MO->isReg() || !MO->isDef())
976 continue;
977 unsigned Reg = MO->getReg();
978 if (!TargetRegisterInfo::isVirtualRegister(Reg))
979 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000980 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000981 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +0000982 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000983 // A PHI inside the loop causes a copy because the live range of Reg is
984 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +0000985 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000986 return true;
987 // A PHI in an exit block can cause a copy to be inserted if the PHI
988 // has multiple predecessors in the loop with different values.
989 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +0000990 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000991 return true;
992 continue;
993 }
994 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +0000995 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
996 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000997 }
Evan Chengef42bea2011-04-11 21:09:18 +0000998 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000999 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +00001000 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001001}
1002
Evan Cheng63c76082010-10-19 18:58:51 +00001003/// HasHighOperandLatency - Compute operand latency between a def of 'Reg'
1004/// and an use in the current loop, return true if the target considered
1005/// it 'high'.
1006bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chenge96b8d72010-10-26 02:08:50 +00001007 unsigned DefIdx, unsigned Reg) const {
1008 if (!InstrItins || InstrItins->isEmpty() || MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +00001009 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001010
Owen Andersonb36376e2014-03-17 19:36:09 +00001011 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1012 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001013 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001014 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +00001015 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001016 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1017 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +00001018 if (!MO.isReg() || !MO.isUse())
1019 continue;
1020 unsigned MOReg = MO.getReg();
1021 if (MOReg != Reg)
1022 continue;
1023
Owen Andersonb36376e2014-03-17 19:36:09 +00001024 if (TII->hasHighOperandLatency(InstrItins, MRI, &MI, DefIdx, &UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +00001025 return true;
Evan Chengd62719c2010-10-14 01:16:09 +00001026 }
1027
Evan Cheng63c76082010-10-19 18:58:51 +00001028 // Only look at the first in loop use.
1029 break;
Evan Chengd62719c2010-10-14 01:16:09 +00001030 }
1031
Evan Cheng63c76082010-10-19 18:58:51 +00001032 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001033}
1034
Evan Chenge96b8d72010-10-26 02:08:50 +00001035/// IsCheapInstruction - Return true if the instruction is marked "cheap" or
1036/// the operand latency between its def and a use is one or less.
1037bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Jiangning Liuc3053122014-07-29 01:55:19 +00001038 if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001039 return true;
1040 if (!InstrItins || InstrItins->isEmpty())
1041 return false;
1042
1043 bool isCheap = false;
1044 unsigned NumDefs = MI.getDesc().getNumDefs();
1045 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1046 MachineOperand &DefMO = MI.getOperand(i);
1047 if (!DefMO.isReg() || !DefMO.isDef())
1048 continue;
1049 --NumDefs;
1050 unsigned Reg = DefMO.getReg();
1051 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1052 continue;
1053
1054 if (!TII->hasLowDefLatency(InstrItins, &MI, i))
1055 return false;
1056 isCheap = true;
1057 }
1058
1059 return isCheap;
1060}
1061
Evan Cheng87066f02010-10-20 22:03:58 +00001062/// CanCauseHighRegPressure - Visit BBs from header to current BB, check
Evan Cheng44436302010-10-16 02:20:26 +00001063/// if hoisting an instruction of the given cost matrix can cause high
1064/// register pressure.
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001065bool MachineLICM::CanCauseHighRegPressure(DenseMap<unsigned, int> &Cost,
1066 bool CheapInstr) {
Evan Cheng87066f02010-10-20 22:03:58 +00001067 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1068 CI != CE; ++CI) {
Andrew Trick5209c732012-02-08 21:23:00 +00001069 if (CI->second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001070 continue;
1071
1072 unsigned RCId = CI->first;
Pete Cooper1c3b1ef2011-12-22 02:13:25 +00001073 unsigned Limit = RegLimit[RCId];
1074 int Cost = CI->second;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001075
1076 // Don't hoist cheap instructions if they would increase register pressure,
1077 // even if we're under the limit.
1078 if (CheapInstr)
1079 return true;
1080
Evan Cheng87066f02010-10-20 22:03:58 +00001081 for (unsigned i = BackTrace.size(); i != 0; --i) {
Craig Topper2cd5ff82013-07-11 16:22:38 +00001082 SmallVectorImpl<unsigned> &RP = BackTrace[i-1];
Pete Cooper1c3b1ef2011-12-22 02:13:25 +00001083 if (RP[RCId] + Cost >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001084 return true;
1085 }
Evan Cheng44436302010-10-16 02:20:26 +00001086 }
1087
1088 return false;
1089}
1090
Evan Cheng87066f02010-10-20 22:03:58 +00001091/// UpdateBackTraceRegPressure - Traverse the back trace from header to the
1092/// current block and update their register pressures to reflect the effect
1093/// of hoisting MI from the current block to the preheader.
1094void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
1095 if (MI->isImplicitDef())
1096 return;
1097
1098 // First compute the 'cost' of the instruction, i.e. its contribution
1099 // to register pressure.
1100 DenseMap<unsigned, int> Cost;
1101 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
1102 const MachineOperand &MO = MI->getOperand(i);
1103 if (!MO.isReg() || MO.isImplicit())
1104 continue;
1105 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +00001106 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Cheng87066f02010-10-20 22:03:58 +00001107 continue;
1108
Evan Cheng90da66b2011-09-01 01:45:00 +00001109 unsigned RCId, RCCost;
1110 getRegisterClassIDAndCost(MI, Reg, i, RCId, RCCost);
Evan Cheng87066f02010-10-20 22:03:58 +00001111 if (MO.isDef()) {
1112 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1113 if (CI != Cost.end())
1114 CI->second += RCCost;
1115 else
1116 Cost.insert(std::make_pair(RCId, RCCost));
1117 } else if (isOperandKill(MO, MRI)) {
1118 DenseMap<unsigned, int>::iterator CI = Cost.find(RCId);
1119 if (CI != Cost.end())
1120 CI->second -= RCCost;
1121 else
1122 Cost.insert(std::make_pair(RCId, -RCCost));
1123 }
1124 }
1125
1126 // Update register pressure of blocks from loop header to current block.
1127 for (unsigned i = 0, e = BackTrace.size(); i != e; ++i) {
Craig Topper2cd5ff82013-07-11 16:22:38 +00001128 SmallVectorImpl<unsigned> &RP = BackTrace[i];
Evan Cheng87066f02010-10-20 22:03:58 +00001129 for (DenseMap<unsigned, int>::iterator CI = Cost.begin(), CE = Cost.end();
1130 CI != CE; ++CI) {
1131 unsigned RCId = CI->first;
1132 RP[RCId] += CI->second;
1133 }
1134 }
1135}
1136
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001137/// IsProfitableToHoist - Return true if it is potentially profitable to hoist
1138/// the given loop invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001139bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001140 if (MI.isImplicitDef())
1141 return true;
1142
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001143 // Besides removing computation from the loop, hoisting an instruction has
1144 // these effects:
1145 //
1146 // - The value defined by the instruction becomes live across the entire
1147 // loop. This increases register pressure in the loop.
1148 //
1149 // - If the value is used by a PHI in the loop, a copy will be required for
1150 // lowering the PHI after extending the live range.
1151 //
1152 // - When hoisting the last use of a value in the loop, that value no longer
1153 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001154
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001155 bool CheapInstr = IsCheapInstruction(MI);
1156 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001157
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001158 // Don't hoist a cheap instruction if it would create a copy in the loop.
1159 if (CheapInstr && CreatesCopy) {
1160 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1161 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001162 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001163
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001164 // Rematerializable instructions should always be hoisted since the register
1165 // allocator can just pull them down again when needed.
1166 if (TII->isTriviallyReMaterializable(&MI, AA))
1167 return true;
1168
1169 // Estimate register pressure to determine whether to LICM the instruction.
1170 // In low register pressure situation, we can be more aggressive about
1171 // hoisting. Also, favors hoisting long latency instructions even in
1172 // moderately high pressure situation.
1173 // Cheap instructions will only be hoisted if they don't increase register
1174 // pressure at all.
1175 // FIXME: If there are long latency loop-invariant instructions inside the
1176 // loop at this point, why didn't the optimizer's LICM hoist them?
1177 DenseMap<unsigned, int> Cost;
1178 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1179 const MachineOperand &MO = MI.getOperand(i);
1180 if (!MO.isReg() || MO.isImplicit())
1181 continue;
1182 unsigned Reg = MO.getReg();
1183 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1184 continue;
1185
1186 unsigned RCId, RCCost;
1187 getRegisterClassIDAndCost(&MI, Reg, i, RCId, RCCost);
1188 if (MO.isDef()) {
1189 if (HasHighOperandLatency(MI, i, Reg)) {
1190 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1191 ++NumHighLatency;
1192 return true;
1193 }
1194 Cost[RCId] += RCCost;
1195 } else if (isOperandKill(MO, MRI)) {
1196 // Is a virtual register use is a kill, hoisting it out of the loop
1197 // may actually reduce register pressure or be register pressure
1198 // neutral.
1199 Cost[RCId] -= RCCost;
1200 }
1201 }
1202
1203 // Visit BBs from header to current BB, if hoisting this doesn't cause
1204 // high register pressure, then it's safe to proceed.
1205 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1206 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1207 ++NumLowRP;
1208 return true;
1209 }
1210
1211 // Don't risk increasing register pressure if it would create copies.
1212 if (CreatesCopy) {
1213 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001214 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001215 }
1216
1217 // Do not "speculate" in high register pressure situation. If an
1218 // instruction is not guaranteed to be executed in the loop, it's best to be
1219 // conservative.
1220 if (AvoidSpeculation &&
1221 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1222 DEBUG(dbgs() << "Won't speculate: " << MI);
1223 return false;
1224 }
1225
1226 // High register pressure situation, only hoist if the instruction is going
1227 // to be remat'ed.
1228 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1229 !MI.isInvariantLoad(AA)) {
1230 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1231 return false;
1232 }
Evan Cheng399660c2009-02-05 08:45:46 +00001233
1234 return true;
1235}
1236
Dan Gohman104f57c2009-10-29 17:47:20 +00001237MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001238 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001239 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001240 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001241
Dan Gohman104f57c2009-10-29 17:47:20 +00001242 // If not, we may be able to unfold a load and hoist that.
1243 // First test whether the instruction is loading from an amenable
1244 // memory location.
Evan Chengb8b0ad82011-01-20 08:34:58 +00001245 if (!MI->isInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001246 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001247
Dan Gohman104f57c2009-10-29 17:47:20 +00001248 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001249 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001250 unsigned NewOpc =
1251 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1252 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001253 /*UnfoldStore=*/false,
1254 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001255 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001256 const MCInstrDesc &MID = TII->get(NewOpc);
Craig Topperc0196b12014-04-14 00:51:57 +00001257 if (MID.getNumDefs() != 1) return nullptr;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001258 MachineFunction &MF = *MI->getParent()->getParent();
1259 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001260 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Chengd62719c2010-10-14 01:16:09 +00001261 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001262
Dan Gohman104f57c2009-10-29 17:47:20 +00001263 SmallVector<MachineInstr *, 2> NewMIs;
1264 bool Success =
1265 TII->unfoldMemoryOperand(MF, MI, Reg,
1266 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1267 NewMIs);
1268 (void)Success;
1269 assert(Success &&
1270 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1271 "succeeded!");
1272 assert(NewMIs.size() == 2 &&
1273 "Unfolded a load into multiple instructions!");
1274 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001275 MachineBasicBlock::iterator Pos = MI;
1276 MBB->insert(Pos, NewMIs[0]);
1277 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001278 // If unfolding produced a load that wasn't loop-invariant or profitable to
1279 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001280 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001281 NewMIs[0]->eraseFromParent();
1282 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001283 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001284 }
Evan Cheng87066f02010-10-20 22:03:58 +00001285
1286 // Update register pressure for the unfolded instruction.
1287 UpdateRegPressure(NewMIs[1]);
1288
Dan Gohman104f57c2009-10-29 17:47:20 +00001289 // Otherwise we successfully unfolded a load that we can hoist.
1290 MI->eraseFromParent();
1291 return NewMIs[0];
1292}
1293
Evan Chengf42b5af2009-11-03 21:40:02 +00001294void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1295 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1296 const MachineInstr *MI = &*I;
Evan Chengb8b0ad82011-01-20 08:34:58 +00001297 unsigned Opcode = MI->getOpcode();
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001298 CSEMap[Opcode].push_back(MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001299 }
1300}
1301
Evan Cheng7ff83192009-11-07 03:52:02 +00001302const MachineInstr*
1303MachineLICM::LookForDuplicate(const MachineInstr *MI,
1304 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng921152f2009-11-05 00:51:13 +00001305 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1306 const MachineInstr *PrevMI = PrevMIs[i];
Craig Topperc0196b12014-04-14 00:51:57 +00001307 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001308 return PrevMI;
1309 }
Craig Topperc0196b12014-04-14 00:51:57 +00001310 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001311}
1312
1313bool MachineLICM::EliminateCSE(MachineInstr *MI,
1314 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001315 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1316 // the undef property onto uses.
1317 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001318 return false;
1319
1320 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene55cf95c2010-01-05 00:03:48 +00001321 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001322
1323 // Replace virtual registers defined by MI by their counterparts defined
1324 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001325 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001326 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1327 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001328
1329 // Physical registers may not differ here.
1330 assert((!MO.isReg() || MO.getReg() == 0 ||
1331 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1332 MO.getReg() == Dup->getOperand(i).getReg()) &&
1333 "Instructions with different phys regs are not identical!");
1334
1335 if (MO.isReg() && MO.isDef() &&
Evan Chengaa563df2011-10-17 19:50:12 +00001336 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1337 Defs.push_back(i);
1338 }
1339
1340 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1341 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1342 unsigned Idx = Defs[i];
1343 unsigned Reg = MI->getOperand(Idx).getReg();
1344 unsigned DupReg = Dup->getOperand(Idx).getReg();
1345 OrigRCs.push_back(MRI->getRegClass(DupReg));
1346
1347 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1348 // Restore old RCs if more than one defs.
1349 for (unsigned j = 0; j != i; ++j)
1350 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1351 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001352 }
Evan Cheng921152f2009-11-05 00:51:13 +00001353 }
Evan Chengaa563df2011-10-17 19:50:12 +00001354
1355 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1356 unsigned Idx = Defs[i];
1357 unsigned Reg = MI->getOperand(Idx).getReg();
1358 unsigned DupReg = Dup->getOperand(Idx).getReg();
1359 MRI->replaceRegWith(Reg, DupReg);
1360 MRI->clearKillFlags(DupReg);
1361 }
1362
Evan Cheng7ff83192009-11-07 03:52:02 +00001363 MI->eraseFromParent();
1364 ++NumCSEed;
1365 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001366 }
1367 return false;
1368}
1369
Evan Chengaf138952011-10-12 00:09:14 +00001370/// MayCSE - Return true if the given instruction will be CSE'd if it's
1371/// hoisted out of the loop.
1372bool MachineLICM::MayCSE(MachineInstr *MI) {
1373 unsigned Opcode = MI->getOpcode();
1374 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1375 CI = CSEMap.find(Opcode);
1376 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1377 // the undef property onto uses.
1378 if (CI == CSEMap.end() || MI->isImplicitDef())
1379 return false;
1380
Craig Topperc0196b12014-04-14 00:51:57 +00001381 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001382}
1383
Bill Wendling70613b82008-05-12 19:38:32 +00001384/// Hoist - When an instruction is found to use only loop invariant operands
1385/// that are safe to hoist, this instruction is called to do the dirty work.
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001386///
Evan Cheng87066f02010-10-20 22:03:58 +00001387bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman1b44f102009-10-28 03:21:57 +00001388 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001389 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001390 // If not, try unfolding a hoistable load.
1391 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001392 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001393 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001394
Dan Gohman79618d12009-01-15 22:01:38 +00001395 // Now move the instructions to the predecessor, inserting it before any
1396 // terminator instructions.
1397 DEBUG({
David Greene55cf95c2010-01-05 00:03:48 +00001398 dbgs() << "Hoisting " << *MI;
Dan Gohman3570f812010-06-22 17:25:57 +00001399 if (Preheader->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001400 dbgs() << " to MachineBasicBlock "
Dan Gohman3570f812010-06-22 17:25:57 +00001401 << Preheader->getName();
Dan Gohman1b44f102009-10-28 03:21:57 +00001402 if (MI->getParent()->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001403 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen2bbeaa82009-11-20 01:17:03 +00001404 << MI->getParent()->getName();
David Greene55cf95c2010-01-05 00:03:48 +00001405 dbgs() << "\n";
Dan Gohman79618d12009-01-15 22:01:38 +00001406 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001407
Evan Chengf42b5af2009-11-03 21:40:02 +00001408 // If this is the first instruction being hoisted to the preheader,
1409 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001410 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001411 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001412 FirstInLoop = false;
1413 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001414
Evan Cheng399660c2009-02-05 08:45:46 +00001415 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001416 unsigned Opcode = MI->getOpcode();
1417 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1418 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001419 if (!EliminateCSE(MI, CI)) {
1420 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001421 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001422
Evan Cheng87066f02010-10-20 22:03:58 +00001423 // Update register pressure for BBs from header to this block.
1424 UpdateBackTraceRegPressure(MI);
1425
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001426 // Clear the kill flags of any register this instruction defines,
1427 // since they may need to be live throughout the entire loop
1428 // rather than just live for part of it.
1429 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1430 MachineOperand &MO = MI->getOperand(i);
1431 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001432 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001433 }
1434
Evan Cheng399660c2009-02-05 08:45:46 +00001435 // Add to the CSE map.
1436 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001437 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001438 else
1439 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001440 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001441
Dan Gohman79618d12009-01-15 22:01:38 +00001442 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001443 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001444
1445 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001446}
Dan Gohman3570f812010-06-22 17:25:57 +00001447
1448MachineBasicBlock *MachineLICM::getCurPreheader() {
1449 // Determine the block to which to hoist instructions. If we can't find a
1450 // suitable loop predecessor, we can't do any hoisting.
1451
1452 // If we've tried to get a preheader and failed, don't try again.
1453 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001454 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001455
1456 if (!CurPreheader) {
1457 CurPreheader = CurLoop->getLoopPreheader();
1458 if (!CurPreheader) {
1459 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1460 if (!Pred) {
1461 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001462 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001463 }
1464
1465 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1466 if (!CurPreheader) {
1467 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001468 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001469 }
1470 }
1471 }
1472 return CurPreheader;
1473}