blob: 1a8e92332bc1ea7bfb0db9d56cad42ff8f0b0b52 [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 is not intended to be a replacement or a complete alternative
14// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
15// constructs that are not exposed before lowering and instruction selection.
16//
Bill Wendlingfb706bc2007-12-07 21:42:31 +000017//===----------------------------------------------------------------------===//
18
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000019#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/AliasAnalysis.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000024#include "llvm/CodeGen/MachineDominators.h"
Evan Cheng6ea59492010-04-07 00:41:17 +000025#include "llvm/CodeGen/MachineFrameInfo.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000027#include "llvm/CodeGen/MachineMemOperand.h"
Bill Wendling5da19452008-01-02 19:32:43 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000029#include "llvm/CodeGen/PseudoSourceValue.h"
Matthias Braun88e21312015-06-13 03:42:11 +000030#include "llvm/CodeGen/TargetSchedule.h"
Evan Chengb35afca2011-10-12 21:33:49 +000031#include "llvm/Support/CommandLine.h"
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000032#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000033#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/Target/TargetInstrInfo.h"
35#include "llvm/Target/TargetLowering.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000038#include "llvm/Target/TargetSubtargetInfo.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000039using namespace llvm;
40
Chandler Carruth1b9dde02014-04-22 02:02:50 +000041#define DEBUG_TYPE "machine-licm"
42
Evan Chengb35afca2011-10-12 21:33:49 +000043static cl::opt<bool>
44AvoidSpeculation("avoid-speculation",
45 cl::desc("MachineLICM should avoid speculation"),
Evan Cheng73133372011-10-26 01:26:57 +000046 cl::init(true), cl::Hidden);
Evan Chengb35afca2011-10-12 21:33:49 +000047
Hal Finkel0709f512015-01-08 22:10:48 +000048static cl::opt<bool>
49HoistCheapInsts("hoist-cheap-insts",
50 cl::desc("MachineLICM should hoist even cheap instructions"),
51 cl::init(false), cl::Hidden);
52
Daniel Jasper15e69542015-03-14 10:58:38 +000053static cl::opt<bool>
54SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
55 cl::desc("MachineLICM should sink instructions into "
56 "loops to avoid register spills"),
57 cl::init(false), cl::Hidden);
58
Evan Cheng44436302010-10-16 02:20:26 +000059STATISTIC(NumHoisted,
60 "Number of machine instructions hoisted out of loops");
61STATISTIC(NumLowRP,
62 "Number of instructions hoisted in low reg pressure situation");
63STATISTIC(NumHighLatency,
64 "Number of high latency instructions hoisted");
65STATISTIC(NumCSEed,
66 "Number of hoisted machine instructions CSEed");
Evan Cheng6ea59492010-04-07 00:41:17 +000067STATISTIC(NumPostRAHoisted,
68 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendling43751732007-12-08 01:47:01 +000069
Bill Wendlingfb706bc2007-12-07 21:42:31 +000070namespace {
Nick Lewycky02d5f772009-10-25 06:33:48 +000071 class MachineLICM : public MachineFunctionPass {
Bill Wendling38236ef2007-12-11 23:27:51 +000072 const TargetInstrInfo *TII;
Benjamin Kramer56b31bd2013-01-11 20:05:37 +000073 const TargetLoweringBase *TLI;
Dan Gohmane30d63f2009-09-25 23:58:45 +000074 const TargetRegisterInfo *TRI;
Evan Cheng6ea59492010-04-07 00:41:17 +000075 const MachineFrameInfo *MFI;
Evan Chengd62719c2010-10-14 01:16:09 +000076 MachineRegisterInfo *MRI;
Matthias Braun88e21312015-06-13 03:42:11 +000077 TargetSchedModel SchedModel;
Andrew Trickc40815d2012-02-08 21:23:03 +000078 bool PreRegAlloc;
Bill Wendlingb678ae72007-12-11 19:40:06 +000079
Bill Wendlingfb706bc2007-12-07 21:42:31 +000080 // Various analyses that we use...
Dan Gohmanbe8137b2009-10-07 17:38:06 +000081 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng058b9f02010-04-08 01:03:47 +000082 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendling70613b82008-05-12 19:38:32 +000083 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +000084
Bill Wendlingfb706bc2007-12-07 21:42:31 +000085 // State that is updated as we process loops
Bill Wendling70613b82008-05-12 19:38:32 +000086 bool Changed; // True if a loop is changed.
Evan Cheng032f3262010-05-29 00:06:36 +000087 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendling70613b82008-05-12 19:38:32 +000088 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohman79618d12009-01-15 22:01:38 +000089 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Cheng399660c2009-02-05 08:45:46 +000090
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +000091 // Exit blocks for CurLoop.
92 SmallVector<MachineBasicBlock*, 8> ExitBlocks;
93
94 bool isExitBlock(const MachineBasicBlock *MBB) const {
95 return std::find(ExitBlocks.begin(), ExitBlocks.end(), MBB) !=
96 ExitBlocks.end();
97 }
98
Evan Chengd62719c2010-10-14 01:16:09 +000099 // Track 'estimated' register pressure.
Evan Cheng44436302010-10-16 02:20:26 +0000100 SmallSet<unsigned, 32> RegSeen;
Evan Chengd62719c2010-10-14 01:16:09 +0000101 SmallVector<unsigned, 8> RegPressure;
Evan Cheng44436302010-10-16 02:20:26 +0000102
Daniel Jasper274928f2015-04-14 11:56:25 +0000103 // Register pressure "limit" per register pressure set. If the pressure
Evan Cheng44436302010-10-16 02:20:26 +0000104 // is higher than the limit, then it's considered high.
Evan Chengd62719c2010-10-14 01:16:09 +0000105 SmallVector<unsigned, 8> RegLimit;
106
Evan Cheng44436302010-10-16 02:20:26 +0000107 // Register pressure on path leading from loop preheader to current BB.
108 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
109
Dale Johannesen329d4742010-07-29 17:45:24 +0000110 // For each opcode, keep a list of potential CSE instructions.
Evan Chengf42b5af2009-11-03 21:40:02 +0000111 DenseMap<unsigned, std::vector<const MachineInstr*> > CSEMap;
Evan Cheng6ea59492010-04-07 00:41:17 +0000112
Evan Chengf192ca02011-10-11 23:48:44 +0000113 enum {
114 SpeculateFalse = 0,
115 SpeculateTrue = 1,
116 SpeculateUnknown = 2
117 };
118
Devang Patel453d4012011-10-11 18:09:58 +0000119 // If a MBB does not dominate loop exiting blocks then it may not safe
120 // to hoist loads from this block.
Evan Chengf192ca02011-10-11 23:48:44 +0000121 // Tri-state: 0 - false, 1 - true, 2 - unknown
122 unsigned SpeculationState;
Devang Patel453d4012011-10-11 18:09:58 +0000123
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000124 public:
125 static char ID; // Pass identification, replacement for typeid
Evan Cheng6ea59492010-04-07 00:41:17 +0000126 MachineLICM() :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000127 MachineFunctionPass(ID), PreRegAlloc(true) {
128 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
129 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000130
131 explicit MachineLICM(bool PreRA) :
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000132 MachineFunctionPass(ID), PreRegAlloc(PreRA) {
133 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
134 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000135
Craig Topper4584cd52014-03-07 09:26:03 +0000136 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000137
Craig Topper4584cd52014-03-07 09:26:03 +0000138 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000139 AU.addRequired<MachineLoopInfo>();
140 AU.addRequired<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000141 AU.addRequired<AAResultsWrapperPass>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000142 AU.addPreserved<MachineLoopInfo>();
143 AU.addPreserved<MachineDominatorTree>();
144 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000145 }
Evan Cheng399660c2009-02-05 08:45:46 +0000146
Craig Topper4584cd52014-03-07 09:26:03 +0000147 void releaseMemory() override {
Evan Cheng44436302010-10-16 02:20:26 +0000148 RegSeen.clear();
Evan Chengd62719c2010-10-14 01:16:09 +0000149 RegPressure.clear();
150 RegLimit.clear();
Evan Cheng63c76082010-10-19 18:58:51 +0000151 BackTrace.clear();
Evan Cheng399660c2009-02-05 08:45:46 +0000152 CSEMap.clear();
153 }
154
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000155 private:
Sanjay Patel87c6c072015-12-10 16:34:21 +0000156 /// Keep track of information about hoisting candidates.
Evan Cheng058b9f02010-04-08 01:03:47 +0000157 struct CandidateInfo {
158 MachineInstr *MI;
Evan Cheng058b9f02010-04-08 01:03:47 +0000159 unsigned Def;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000160 int FI;
161 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
162 : MI(mi), Def(def), FI(fi) {}
Evan Cheng058b9f02010-04-08 01:03:47 +0000163 };
164
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000165 void HoistRegionPostRA();
Evan Cheng058b9f02010-04-08 01:03:47 +0000166
Evan Cheng058b9f02010-04-08 01:03:47 +0000167 void HoistPostRA(MachineInstr *MI, unsigned Def);
168
Sanjay Patel87c6c072015-12-10 16:34:21 +0000169 void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
170 BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000171 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng058b9f02010-04-08 01:03:47 +0000172
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000173 void AddToLiveIns(unsigned Reg);
Evan Cheng058b9f02010-04-08 01:03:47 +0000174
Evan Cheng0a2aff22010-04-13 18:16:00 +0000175 bool IsLICMCandidate(MachineInstr &I);
176
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000177 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000178
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000179 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengef42bea2011-04-11 21:09:18 +0000180
Evan Chenge96b8d72010-10-26 02:08:50 +0000181 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
182 unsigned Reg) const;
183
184 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Chengd62719c2010-10-14 01:16:09 +0000185
Daniel Jasperefece522015-04-03 16:19:48 +0000186 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
187 bool Cheap);
Evan Cheng87066f02010-10-20 22:03:58 +0000188
Evan Cheng87066f02010-10-20 22:03:58 +0000189 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng44436302010-10-16 02:20:26 +0000190
Evan Cheng73f9a9e2009-11-20 23:31:34 +0000191 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000192
Devang Patel453d4012011-10-11 18:09:58 +0000193 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
194
Pete Cooper1eed5b52011-12-22 02:05:40 +0000195 void EnterScope(MachineBasicBlock *MBB);
196
197 void ExitScope(MachineBasicBlock *MBB);
198
Sanjay Patel87c6c072015-12-10 16:34:21 +0000199 void ExitScopeIfDone(
200 MachineDomTreeNode *Node,
201 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
202 DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
Pete Cooper1eed5b52011-12-22 02:05:40 +0000203
Pete Cooper1eed5b52011-12-22 02:05:40 +0000204 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
Sanjay Patel87c6c072015-12-10 16:34:21 +0000205
Pete Cooper1eed5b52011-12-22 02:05:40 +0000206 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000207
Daniel Jasper15e69542015-03-14 10:58:38 +0000208 void SinkIntoLoop();
209
Evan Chengd62719c2010-10-14 01:16:09 +0000210 void InitRegPressure(MachineBasicBlock *BB);
211
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000212 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
213 bool ConsiderSeen,
214 bool ConsiderUnseenAsDef);
215
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000216 void UpdateRegPressure(const MachineInstr *MI,
217 bool ConsiderUnseenAsDef = false);
Evan Chengd62719c2010-10-14 01:16:09 +0000218
Dan Gohman104f57c2009-10-29 17:47:20 +0000219 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
220
Sanjay Patel87c6c072015-12-10 16:34:21 +0000221 const MachineInstr *
222 LookForDuplicate(const MachineInstr *MI,
223 std::vector<const MachineInstr *> &PrevMIs);
Evan Cheng7ff83192009-11-07 03:52:02 +0000224
Sanjay Patel87c6c072015-12-10 16:34:21 +0000225 bool EliminateCSE(
226 MachineInstr *MI,
227 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI);
Evan Cheng921152f2009-11-05 00:51:13 +0000228
Evan Chengaf138952011-10-12 00:09:14 +0000229 bool MayCSE(MachineInstr *MI);
230
Evan Cheng87066f02010-10-20 22:03:58 +0000231 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Chengf42b5af2009-11-03 21:40:02 +0000232
Evan Chengf42b5af2009-11-03 21:40:02 +0000233 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman3570f812010-06-22 17:25:57 +0000234
Dan Gohman3570f812010-06-22 17:25:57 +0000235 MachineBasicBlock *getCurPreheader();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000236 };
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000237} // end anonymous namespace
238
Dan Gohmand78c4002008-05-13 00:00:25 +0000239char MachineLICM::ID = 0;
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000240char &llvm::MachineLICMID = MachineLICM::ID;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000241INITIALIZE_PASS_BEGIN(MachineLICM, "machinelicm",
242 "Machine Loop Invariant Code Motion", false, false)
243INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
244INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000245INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000246INITIALIZE_PASS_END(MachineLICM, "machinelicm",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000247 "Machine Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000248
Sanjay Patel87c6c072015-12-10 16:34:21 +0000249/// Test if the given loop is the outer-most loop that has a unique predecessor.
Dan Gohman3570f812010-06-22 17:25:57 +0000250static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohman7929c442010-07-09 18:49:45 +0000251 // Check whether this loop even has a unique predecessor.
252 if (!CurLoop->getLoopPredecessor())
253 return false;
254 // Ok, now check to see if any of its outer loops do.
Dan Gohman79618d12009-01-15 22:01:38 +0000255 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman3570f812010-06-22 17:25:57 +0000256 if (L->getLoopPredecessor())
Dan Gohman79618d12009-01-15 22:01:38 +0000257 return false;
Dan Gohman7929c442010-07-09 18:49:45 +0000258 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohman79618d12009-01-15 22:01:38 +0000259 return true;
260}
261
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000262bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000263 if (skipOptnoneFunction(*MF.getFunction()))
264 return false;
265
Evan Cheng032f3262010-05-29 00:06:36 +0000266 Changed = FirstInLoop = false;
Matthias Braun88e21312015-06-13 03:42:11 +0000267 const TargetSubtargetInfo &ST = MF.getSubtarget();
268 TII = ST.getInstrInfo();
269 TLI = ST.getTargetLowering();
270 TRI = ST.getRegisterInfo();
Evan Cheng6ea59492010-04-07 00:41:17 +0000271 MFI = MF.getFrameInfo();
Evan Chengd62719c2010-10-14 01:16:09 +0000272 MRI = &MF.getRegInfo();
Matthias Braun88e21312015-06-13 03:42:11 +0000273 SchedModel.init(ST.getSchedModel(), &ST, TII);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000274
Andrew Trickc40815d2012-02-08 21:23:03 +0000275 PreRegAlloc = MRI->isSSA();
276
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000277 if (PreRegAlloc)
278 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
279 else
280 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
Craig Toppera538d832012-08-22 06:07:19 +0000281 DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000282
Evan Chengd62719c2010-10-14 01:16:09 +0000283 if (PreRegAlloc) {
284 // Estimate register pressure during pre-regalloc pass.
Daniel Jasper274928f2015-04-14 11:56:25 +0000285 unsigned NumRPS = TRI->getNumRegPressureSets();
286 RegPressure.resize(NumRPS);
Evan Chengd62719c2010-10-14 01:16:09 +0000287 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Daniel Jasper274928f2015-04-14 11:56:25 +0000288 RegLimit.resize(NumRPS);
289 for (unsigned i = 0, e = NumRPS; i != e; ++i)
290 RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
Evan Chengd62719c2010-10-14 01:16:09 +0000291 }
292
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000293 // Get our Loop information...
Evan Cheng058b9f02010-04-08 01:03:47 +0000294 MLI = &getAnalysis<MachineLoopInfo>();
295 DT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000296 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000297
Dan Gohman7929c442010-07-09 18:49:45 +0000298 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
299 while (!Worklist.empty()) {
300 CurLoop = Worklist.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000301 CurPreheader = nullptr;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000302 ExitBlocks.clear();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000303
Evan Cheng058b9f02010-04-08 01:03:47 +0000304 // If this is done before regalloc, only visit outer-most preheader-sporting
305 // loops.
Dan Gohman7929c442010-07-09 18:49:45 +0000306 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
307 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohman79618d12009-01-15 22:01:38 +0000308 continue;
Dan Gohman7929c442010-07-09 18:49:45 +0000309 }
Dan Gohman79618d12009-01-15 22:01:38 +0000310
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000311 CurLoop->getExitBlocks(ExitBlocks);
312
Evan Cheng6ea59492010-04-07 00:41:17 +0000313 if (!PreRegAlloc)
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000314 HoistRegionPostRA();
Evan Cheng6ea59492010-04-07 00:41:17 +0000315 else {
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000316 // CSEMap is initialized for loop header when the first instruction is
317 // being hoisted.
318 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng032f3262010-05-29 00:06:36 +0000319 FirstInLoop = true;
Pete Cooper1eed5b52011-12-22 02:05:40 +0000320 HoistOutOfLoop(N);
Evan Cheng6ea59492010-04-07 00:41:17 +0000321 CSEMap.clear();
Daniel Jasper15e69542015-03-14 10:58:38 +0000322
323 if (SinkInstsToAvoidSpills)
324 SinkIntoLoop();
Evan Cheng6ea59492010-04-07 00:41:17 +0000325 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000326 }
327
328 return Changed;
329}
330
Sanjay Patel87c6c072015-12-10 16:34:21 +0000331/// Return true if instruction stores to the specified frame.
Evan Cheng058b9f02010-04-08 01:03:47 +0000332static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
333 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
334 oe = MI->memoperands_end(); o != oe; ++o) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000335 if (!(*o)->isStore() || !(*o)->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000336 continue;
337 if (const FixedStackPseudoSourceValue *Value =
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000338 dyn_cast<FixedStackPseudoSourceValue>((*o)->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000339 if (Value->getFrameIndex() == FI)
340 return true;
341 }
342 }
343 return false;
344}
345
Sanjay Patel87c6c072015-12-10 16:34:21 +0000346/// Examine the instruction for potentai LICM candidate. Also
Evan Cheng058b9f02010-04-08 01:03:47 +0000347/// gather register def and frame object update information.
348void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000349 BitVector &PhysRegDefs,
350 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000351 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000352 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000353 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000354 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000355 unsigned Def = 0;
356 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
357 const MachineOperand &MO = MI->getOperand(i);
358 if (MO.isFI()) {
359 // Remember if the instruction stores to the frame index.
360 int FI = MO.getIndex();
361 if (!StoredFIs.count(FI) &&
362 MFI->isSpillSlotObjectIndex(FI) &&
363 InstructionStoresToFI(MI, FI))
364 StoredFIs.insert(FI);
Evan Cheng89e74792010-04-13 20:21:05 +0000365 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000366 continue;
367 }
368
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000369 // We can't hoist an instruction defining a physreg that is clobbered in
370 // the loop.
371 if (MO.isRegMask()) {
Jakob Stoklund Olesen5e1ac452012-02-02 23:52:57 +0000372 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000373 continue;
374 }
375
Evan Cheng058b9f02010-04-08 01:03:47 +0000376 if (!MO.isReg())
377 continue;
378 unsigned Reg = MO.getReg();
379 if (!Reg)
380 continue;
381 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
382 "Not expecting virtual register!");
383
Evan Cheng0a2aff22010-04-13 18:16:00 +0000384 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000385 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-04-13 20:21:05 +0000386 // If it's using a non-loop-invariant register, then it's obviously not
387 // safe to hoist.
388 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000389 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000390 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000391
392 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000393 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
394 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000395 if (!MO.isDead())
396 // Non-dead implicit def? This cannot be hoisted.
397 RuledOut = true;
398 // No need to check if a dead implicit def is also defined by
399 // another instruction.
400 continue;
401 }
402
403 // FIXME: For now, avoid instructions with multiple defs, unless
404 // it's a dead implicit def.
405 if (Def)
406 RuledOut = true;
407 else
408 Def = Reg;
409
410 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000411 // register, then this is not safe. Two defs is indicated by setting a
412 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000413 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000414 if (PhysRegDefs.test(*AS))
415 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000416 PhysRegDefs.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000417 }
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000418 if (PhysRegClobbers.test(Reg))
419 // MI defined register is seen defined by another instruction in
420 // the loop, it cannot be a LICM candidate.
421 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000422 }
423
Evan Cheng0a2aff22010-04-13 18:16:00 +0000424 // Only consider reloads for now and remats which do not have register
425 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000426 if (Def && !RuledOut) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000427 int FI = INT_MIN;
Evan Cheng89e74792010-04-13 20:21:05 +0000428 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Evan Cheng0a2aff22010-04-13 18:16:00 +0000429 (TII->isLoadFromStackSlot(MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
430 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000431 }
432}
433
Sanjay Patel87c6c072015-12-10 16:34:21 +0000434/// Walk the specified region of the CFG and hoist loop invariants out to the
435/// preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000436void MachineLICM::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000437 MachineBasicBlock *Preheader = getCurPreheader();
438 if (!Preheader)
439 return;
440
Evan Cheng6ea59492010-04-07 00:41:17 +0000441 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000442 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
443 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000444
Evan Cheng058b9f02010-04-08 01:03:47 +0000445 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000446 SmallSet<int, 32> StoredFIs;
447
448 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000449 // collect potential LICM candidates.
Benjamin Kramer7d605262013-09-15 22:04:42 +0000450 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000451 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
452 MachineBasicBlock *BB = Blocks[i];
Bill Wendling918cea22011-10-12 02:58:01 +0000453
454 // If the header of the loop containing this basic block is a landing pad,
455 // then don't try to hoist instructions out of this loop.
456 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000457 if (ML && ML->getHeader()->isEHPad()) continue;
Bill Wendling918cea22011-10-12 02:58:01 +0000458
Evan Cheng6ea59492010-04-07 00:41:17 +0000459 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000460 // FIXME: That means a reload that're reused in successor block(s) will not
461 // be LICM'ed.
Matthias Braund9da1622015-09-09 18:08:03 +0000462 for (const auto &LI : BB->liveins()) {
463 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000464 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000465 }
466
Evan Chengf192ca02011-10-11 23:48:44 +0000467 SpeculationState = SpeculateUnknown;
Evan Cheng6ea59492010-04-07 00:41:17 +0000468 for (MachineBasicBlock::iterator
469 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
Evan Cheng6ea59492010-04-07 00:41:17 +0000470 MachineInstr *MI = &*MII;
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000471 ProcessMI(MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng6ea59492010-04-07 00:41:17 +0000472 }
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000473 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000474
Evan Cheng7fede872012-03-27 01:50:58 +0000475 // Gather the registers read / clobbered by the terminator.
476 BitVector TermRegs(NumRegs);
477 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
478 if (TI != Preheader->end()) {
479 for (unsigned i = 0, e = TI->getNumOperands(); i != e; ++i) {
480 const MachineOperand &MO = TI->getOperand(i);
481 if (!MO.isReg())
482 continue;
483 unsigned Reg = MO.getReg();
484 if (!Reg)
485 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000486 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
487 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000488 }
489 }
490
Evan Cheng6ea59492010-04-07 00:41:17 +0000491 // Now evaluate whether the potential candidates qualify.
492 // 1. Check if the candidate defined register is defined by another
493 // instruction in the loop.
494 // 2. If the candidate is a load from stack slot (always true for now),
495 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000496 // 3. Make sure candidate def should not clobber
497 // registers read by the terminator. Similarly its def should not be
498 // clobbered by the terminator.
Evan Cheng6ea59492010-04-07 00:41:17 +0000499 for (unsigned i = 0, e = Candidates.size(); i != e; ++i) {
Evan Cheng0a2aff22010-04-13 18:16:00 +0000500 if (Candidates[i].FI != INT_MIN &&
501 StoredFIs.count(Candidates[i].FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000502 continue;
503
Evan Cheng7fede872012-03-27 01:50:58 +0000504 unsigned Def = Candidates[i].Def;
505 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000506 bool Safe = true;
507 MachineInstr *MI = Candidates[i].MI;
Evan Chengcce672c2010-04-13 20:25:29 +0000508 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
509 const MachineOperand &MO = MI->getOperand(j);
Evan Cheng87585d72010-04-13 22:13:34 +0000510 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000511 continue;
Evan Cheng7fede872012-03-27 01:50:58 +0000512 unsigned Reg = MO.getReg();
513 if (PhysRegDefs.test(Reg) ||
514 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000515 // If it's using a non-loop-invariant register, then it's obviously
516 // not safe to hoist.
517 Safe = false;
518 break;
519 }
520 }
521 if (Safe)
522 HoistPostRA(MI, Candidates[i].Def);
523 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000524 }
525}
526
Sanjay Patel87c6c072015-12-10 16:34:21 +0000527/// Add register 'Reg' to the livein sets of BBs in the current loop, and make
528/// sure it is not killed by any instructions in the loop.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000529void MachineLICM::AddToLiveIns(unsigned Reg) {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000530 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000531 for (unsigned i = 0, e = Blocks.size(); i != e; ++i) {
532 MachineBasicBlock *BB = Blocks[i];
533 if (!BB->isLiveIn(Reg))
534 BB->addLiveIn(Reg);
535 for (MachineBasicBlock::iterator
536 MII = BB->begin(), E = BB->end(); MII != E; ++MII) {
537 MachineInstr *MI = &*MII;
538 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
539 MachineOperand &MO = MI->getOperand(i);
540 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
541 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
542 MO.setIsKill(false);
543 }
544 }
545 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000546}
547
Sanjay Patel87c6c072015-12-10 16:34:21 +0000548/// When an instruction is found to only use loop invariant operands that is
549/// safe to hoist, this instruction is called to do the dirty work.
Evan Cheng058b9f02010-04-08 01:03:47 +0000550void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000551 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000552
Evan Cheng6ea59492010-04-07 00:41:17 +0000553 // Now move the instructions to the predecessor, inserting it before any
554 // terminator instructions.
Jakob Stoklund Olesen90823532012-01-23 21:01:11 +0000555 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
556 << MI->getParent()->getNumber() << ": " << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000557
558 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000559 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000560 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000561
Andrew Trick5209c732012-02-08 21:23:00 +0000562 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000563 // loop invariant must be kept live throughout the whole loop. This is
564 // important to ensure later passes do not scavenge the def register.
565 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000566
567 ++NumPostRAHoisted;
568 Changed = true;
569}
570
Sanjay Patel87c6c072015-12-10 16:34:21 +0000571/// Check if this mbb is guaranteed to execute. If not then a load from this mbb
572/// may not be safe to hoist.
Devang Patel453d4012011-10-11 18:09:58 +0000573bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000574 if (SpeculationState != SpeculateUnknown)
575 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000576
Devang Patel453d4012011-10-11 18:09:58 +0000577 if (BB != CurLoop->getHeader()) {
578 // Check loop exiting blocks.
579 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
580 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
581 for (unsigned i = 0, e = CurrentLoopExitingBlocks.size(); i != e; ++i)
582 if (!DT->dominates(BB, CurrentLoopExitingBlocks[i])) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000583 SpeculationState = SpeculateTrue;
584 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000585 }
586 }
587
Evan Chengf192ca02011-10-11 23:48:44 +0000588 SpeculationState = SpeculateFalse;
589 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000590}
591
Pete Cooper1eed5b52011-12-22 02:05:40 +0000592void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
593 DEBUG(dbgs() << "Entering: " << MBB->getName() << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000594
Pete Cooper1eed5b52011-12-22 02:05:40 +0000595 // Remember livein register pressure.
596 BackTrace.push_back(RegPressure);
597}
Bill Wendling918cea22011-10-12 02:58:01 +0000598
Pete Cooper1eed5b52011-12-22 02:05:40 +0000599void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
600 DEBUG(dbgs() << "Exiting: " << MBB->getName() << '\n');
601 BackTrace.pop_back();
602}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000603
Sanjay Patel87c6c072015-12-10 16:34:21 +0000604/// Destroy scope for the MBB that corresponds to the given dominator tree node
605/// if its a leaf or all of its children are done. Walk up the dominator tree to
606/// destroy ancestors which are now done.
Pete Cooper1eed5b52011-12-22 02:05:40 +0000607void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Chengda468322012-01-10 22:27:32 +0000608 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
609 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000610 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000611 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000612
Pete Cooper1eed5b52011-12-22 02:05:40 +0000613 // Pop scope.
614 ExitScope(Node->getBlock());
615
616 // Now traverse upwards to pop ancestors whose offsprings are all done.
617 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
618 unsigned Left = --OpenChildren[Parent];
619 if (Left != 0)
620 break;
621 ExitScope(Parent->getBlock());
622 Node = Parent;
623 }
624}
625
Sanjay Patel87c6c072015-12-10 16:34:21 +0000626/// Walk the specified loop in the CFG (defined by all blocks dominated by the
627/// specified header block, and that are in the current loop) in depth first
628/// order w.r.t the DominatorTree. This allows us to visit definitions before
629/// uses, allowing us to hoist a loop body in one pass without iteration.
Pete Cooper1eed5b52011-12-22 02:05:40 +0000630///
631void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000632 MachineBasicBlock *Preheader = getCurPreheader();
633 if (!Preheader)
634 return;
635
Pete Cooper1eed5b52011-12-22 02:05:40 +0000636 SmallVector<MachineDomTreeNode*, 32> Scopes;
637 SmallVector<MachineDomTreeNode*, 8> WorkList;
638 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
639 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
640
641 // Perform a DFS walk to determine the order of visit.
642 WorkList.push_back(HeaderN);
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000643 while (!WorkList.empty()) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000644 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000645 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000646 MachineBasicBlock *BB = Node->getBlock();
647
648 // If the header of the loop containing this basic block is a landing pad,
649 // then don't try to hoist instructions out of this loop.
650 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000651 if (ML && ML->getHeader()->isEHPad())
Pete Cooper1eed5b52011-12-22 02:05:40 +0000652 continue;
653
654 // If this subregion is not in the top level loop at all, exit.
655 if (!CurLoop->contains(BB))
656 continue;
657
658 Scopes.push_back(Node);
659 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
660 unsigned NumChildren = Children.size();
661
662 // Don't hoist things out of a large switch statement. This often causes
663 // code to be hoisted that wasn't going to be executed, and increases
664 // register pressure in a situation where it's likely to matter.
665 if (BB->succ_size() >= 25)
666 NumChildren = 0;
667
668 OpenChildren[Node] = NumChildren;
669 // Add children in reverse order as then the next popped worklist node is
670 // the first child of this node. This means we ultimately traverse the
671 // DOM tree in exactly the same order as if we'd recursed.
672 for (int i = (int)NumChildren-1; i >= 0; --i) {
673 MachineDomTreeNode *Child = Children[i];
674 ParentMap[Child] = Node;
675 WorkList.push_back(Child);
676 }
Daniel Dunbar418204e2010-10-19 17:14:24 +0000677 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000678
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000679 if (Scopes.size() == 0)
680 return;
681
682 // Compute registers which are livein into the loop headers.
683 RegSeen.clear();
684 BackTrace.clear();
685 InitRegPressure(Preheader);
686
Pete Cooper1eed5b52011-12-22 02:05:40 +0000687 // Now perform LICM.
688 for (unsigned i = 0, e = Scopes.size(); i != e; ++i) {
689 MachineDomTreeNode *Node = Scopes[i];
690 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000691
Pete Cooper1eed5b52011-12-22 02:05:40 +0000692 EnterScope(MBB);
693
694 // Process the block
695 SpeculationState = SpeculateUnknown;
696 for (MachineBasicBlock::iterator
697 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
698 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
699 MachineInstr *MI = &*MII;
700 if (!Hoist(MI, Preheader))
701 UpdateRegPressure(MI);
702 MII = NextMII;
703 }
704
705 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
706 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000707 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000708}
709
Sanjay Patel87c6c072015-12-10 16:34:21 +0000710/// Sink instructions into loops if profitable. This especially tries to prevent
711/// register spills caused by register pressure if there is little to no
712/// overhead moving instructions into loops.
Daniel Jasper15e69542015-03-14 10:58:38 +0000713void MachineLICM::SinkIntoLoop() {
714 MachineBasicBlock *Preheader = getCurPreheader();
715 if (!Preheader)
716 return;
717
718 SmallVector<MachineInstr *, 8> Candidates;
719 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
720 I != Preheader->instr_end(); ++I) {
721 // We need to ensure that we can safely move this instruction into the loop.
722 // As such, it must not have side-effects, e.g. such as a call has.
Duncan P. N. Exon Smith5ec15682015-10-09 19:40:45 +0000723 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
724 Candidates.push_back(&*I);
Daniel Jasper15e69542015-03-14 10:58:38 +0000725 }
726
727 for (MachineInstr *I : Candidates) {
728 const MachineOperand &MO = I->getOperand(0);
729 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
730 continue;
731 if (!MRI->hasOneDef(MO.getReg()))
732 continue;
733 bool CanSink = true;
734 MachineBasicBlock *B = nullptr;
735 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
736 // FIXME: Come up with a proper cost model that estimates whether sinking
737 // the instruction (and thus possibly executing it on every loop
738 // iteration) is more expensive than a register.
739 // For now assumes that copies are cheap and thus almost always worth it.
740 if (!MI.isCopy()) {
741 CanSink = false;
742 break;
743 }
744 if (!B) {
745 B = MI.getParent();
746 continue;
747 }
748 B = DT->findNearestCommonDominator(B, MI.getParent());
749 if (!B) {
750 CanSink = false;
751 break;
752 }
753 }
754 if (!CanSink || !B || B == Preheader)
755 continue;
756 B->splice(B->getFirstNonPHI(), Preheader, I);
757 }
758}
759
Evan Cheng87066f02010-10-20 22:03:58 +0000760static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
761 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
762}
763
Sanjay Patel87c6c072015-12-10 16:34:21 +0000764/// Find all virtual register references that are liveout of the preheader to
765/// initialize the starting "register pressure". Note this does not count live
766/// through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000767void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000768 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000769
Evan Cheng87066f02010-10-20 22:03:58 +0000770 // If the preheader has only a single predecessor and it ends with a
771 // fallthrough or an unconditional branch, then scan its predecessor for live
772 // defs as well. This happens whenever the preheader is created by splitting
773 // the critical edge from the loop predecessor to the loop header.
774 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000775 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000776 SmallVector<MachineOperand, 4> Cond;
777 if (!TII->AnalyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
778 InitRegPressure(*BB->pred_begin());
779 }
780
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000781 for (const MachineInstr &MI : *BB)
782 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
Evan Chengd62719c2010-10-14 01:16:09 +0000783}
784
Sanjay Patel87c6c072015-12-10 16:34:21 +0000785/// Update estimate of register pressure after the specified instruction.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000786void MachineLICM::UpdateRegPressure(const MachineInstr *MI,
787 bool ConsiderUnseenAsDef) {
788 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
Daniel Jasper274928f2015-04-14 11:56:25 +0000789 for (const auto &RPIdAndCost : Cost) {
790 unsigned Class = RPIdAndCost.first;
791 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000792 RegPressure[Class] = 0;
793 else
Daniel Jasper274928f2015-04-14 11:56:25 +0000794 RegPressure[Class] += RPIdAndCost.second;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000795 }
796}
Evan Chengd62719c2010-10-14 01:16:09 +0000797
Sanjay Patel87c6c072015-12-10 16:34:21 +0000798/// Calculate the additional register pressure that the registers used in MI
799/// cause.
800///
801/// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
802/// figure out which usages are live-ins.
803/// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000804DenseMap<unsigned, int>
805MachineLICM::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
806 bool ConsiderUnseenAsDef) {
807 DenseMap<unsigned, int> Cost;
808 if (MI->isImplicitDef())
809 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000810 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
811 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000812 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000813 continue;
814 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000815 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000816 continue;
817
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000818 // FIXME: It seems bad to use RegSeen only for some of these calculations.
819 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
Daniel Jasper274928f2015-04-14 11:56:25 +0000820 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
821
822 RegClassWeight W = TRI->getRegClassWeight(RC);
823 int RCCost = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000824 if (MO.isDef())
Daniel Jasper274928f2015-04-14 11:56:25 +0000825 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000826 else {
827 bool isKill = isOperandKill(MO, MRI);
828 if (isNew && !isKill && ConsiderUnseenAsDef)
829 // Haven't seen this, it must be a livein.
Daniel Jasper274928f2015-04-14 11:56:25 +0000830 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000831 else if (!isNew && isKill)
Daniel Jasper274928f2015-04-14 11:56:25 +0000832 RCCost = -W.RegWeight;
833 }
834 if (RCCost == 0)
835 continue;
836 const int *PS = TRI->getRegClassPressureSets(RC);
837 for (; *PS != -1; ++PS) {
838 if (Cost.find(*PS) == Cost.end())
839 Cost[*PS] = RCCost;
840 else
841 Cost[*PS] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000842 }
Evan Chengd62719c2010-10-14 01:16:09 +0000843 }
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000844 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000845}
846
Sanjay Patel87c6c072015-12-10 16:34:21 +0000847/// Return true if this machine instruction loads from global offset table or
848/// constant pool.
Devang Patel1d8ab462011-10-20 17:42:23 +0000849static bool isLoadFromGOTOrConstantPool(MachineInstr &MI) {
Evan Cheng7f8e5632011-12-07 07:15:52 +0000850 assert (MI.mayLoad() && "Expected MI that loads!");
Devang Patel69a45652011-10-17 17:35:01 +0000851 for (MachineInstr::mmo_iterator I = MI.memoperands_begin(),
Andrew Trick5209c732012-02-08 21:23:00 +0000852 E = MI.memoperands_end(); I != E; ++I) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000853 if (const PseudoSourceValue *PSV = (*I)->getPseudoValue()) {
Alex Lorenze40c8a22015-08-11 23:09:45 +0000854 if (PSV->isGOT() || PSV->isConstantPool())
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000855 return true;
Devang Patel69a45652011-10-17 17:35:01 +0000856 }
857 }
858 return false;
859}
860
Sanjay Patel87c6c072015-12-10 16:34:21 +0000861/// Returns true if the instruction may be a suitable candidate for LICM.
862/// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
Evan Cheng0a2aff22010-04-13 18:16:00 +0000863bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +0000864 // Check if it's safe to move the instruction.
865 bool DontMoveAcrossStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +0000866 if (!I.isSafeToMove(AA, DontMoveAcrossStore))
Chris Lattnerc8226f32008-01-10 23:08:24 +0000867 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000868
869 // If it is load then check if it is guaranteed to execute by making sure that
870 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +0000871 // the loop which does not execute this load, so we can't hoist it. Loads
872 // from constant memory are not safe to speculate all the time, for example
873 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +0000874 // Stores and side effects are already checked by isSafeToMove.
Andrew Trick5209c732012-02-08 21:23:00 +0000875 if (I.mayLoad() && !isLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +0000876 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +0000877 return false;
878
Evan Cheng0a2aff22010-04-13 18:16:00 +0000879 return true;
880}
881
Sanjay Patel87c6c072015-12-10 16:34:21 +0000882/// Returns true if the instruction is loop invariant.
883/// I.e., all virtual register operands are defined outside of the loop,
884/// physical registers aren't accessed explicitly, and there are no side
Evan Cheng0a2aff22010-04-13 18:16:00 +0000885/// effects that aren't captured by the operands or other flags.
Andrew Trick5209c732012-02-08 21:23:00 +0000886///
Evan Cheng0a2aff22010-04-13 18:16:00 +0000887bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
888 if (!IsLICMCandidate(I))
889 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +0000890
Bill Wendling70613b82008-05-12 19:38:32 +0000891 // The instruction is loop invariant if all of its operands are.
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000892 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
893 const MachineOperand &MO = I.getOperand(i);
894
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000895 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +0000896 continue;
897
Dan Gohman79618d12009-01-15 22:01:38 +0000898 unsigned Reg = MO.getReg();
899 if (Reg == 0) continue;
900
901 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmane30d63f2009-09-25 23:58:45 +0000902 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +0000903 if (MO.isUse()) {
904 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +0000905 // and we can freely move its uses. Alternatively, if it's allocatable,
906 // it could get allocated to something with a def during allocation.
Jakob Stoklund Olesen86ae07f2012-01-16 22:34:08 +0000907 if (!MRI->isConstantPhysReg(Reg, *I.getParent()->getParent()))
Dan Gohmane30d63f2009-09-25 23:58:45 +0000908 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000909 // Otherwise it's safe to move.
910 continue;
911 } else if (!MO.isDead()) {
912 // A def that isn't dead. We can't move it.
913 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +0000914 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
915 // If the reg is live into the loop, we can't hoist an instruction
916 // which would clobber it.
917 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000918 }
919 }
Bill Wendlingcd01e892008-08-20 20:32:05 +0000920
921 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000922 continue;
923
Evan Chengd62719c2010-10-14 01:16:09 +0000924 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +0000925 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000926
927 // If the loop contains the definition of an operand, then the instruction
928 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +0000929 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000930 return false;
931 }
932
933 // If we got this far, the instruction is loop invariant!
934 return true;
935}
936
Evan Cheng399660c2009-02-05 08:45:46 +0000937
Sanjay Patel87c6c072015-12-10 16:34:21 +0000938/// Return true if the specified instruction is used by a phi node and hoisting
939/// it could cause a copy to be inserted.
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000940bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
941 SmallVector<const MachineInstr*, 8> Work(1, MI);
942 do {
943 MI = Work.pop_back_val();
Matthias Braune41e1462015-05-29 02:56:46 +0000944 for (const MachineOperand &MO : MI->operands()) {
945 if (!MO.isReg() || !MO.isDef())
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000946 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000947 unsigned Reg = MO.getReg();
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000948 if (!TargetRegisterInfo::isVirtualRegister(Reg))
949 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000950 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000951 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +0000952 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000953 // A PHI inside the loop causes a copy because the live range of Reg is
954 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +0000955 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000956 return true;
957 // A PHI in an exit block can cause a copy to be inserted if the PHI
958 // has multiple predecessors in the loop with different values.
959 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +0000960 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000961 return true;
962 continue;
963 }
964 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +0000965 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
966 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000967 }
Evan Chengef42bea2011-04-11 21:09:18 +0000968 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000969 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +0000970 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000971}
972
Sanjay Patel87c6c072015-12-10 16:34:21 +0000973/// Compute operand latency between a def of 'Reg' and an use in the current
974/// loop, return true if the target considered it high.
Evan Cheng63c76082010-10-19 18:58:51 +0000975bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chenge96b8d72010-10-26 02:08:50 +0000976 unsigned DefIdx, unsigned Reg) const {
Matthias Braun88e21312015-06-13 03:42:11 +0000977 if (MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +0000978 return false;
Evan Chengd62719c2010-10-14 01:16:09 +0000979
Owen Andersonb36376e2014-03-17 19:36:09 +0000980 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
981 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +0000982 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000983 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +0000984 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000985 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
986 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +0000987 if (!MO.isReg() || !MO.isUse())
988 continue;
989 unsigned MOReg = MO.getReg();
990 if (MOReg != Reg)
991 continue;
992
Matthias Braun88e21312015-06-13 03:42:11 +0000993 if (TII->hasHighOperandLatency(SchedModel, MRI, &MI, DefIdx, &UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +0000994 return true;
Evan Chengd62719c2010-10-14 01:16:09 +0000995 }
996
Evan Cheng63c76082010-10-19 18:58:51 +0000997 // Only look at the first in loop use.
998 break;
Evan Chengd62719c2010-10-14 01:16:09 +0000999 }
1000
Evan Cheng63c76082010-10-19 18:58:51 +00001001 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001002}
1003
Sanjay Patel87c6c072015-12-10 16:34:21 +00001004/// Return true if the instruction is marked "cheap" or the operand latency
1005/// between its def and a use is one or less.
Evan Chenge96b8d72010-10-26 02:08:50 +00001006bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Jiangning Liuc3053122014-07-29 01:55:19 +00001007 if (TII->isAsCheapAsAMove(&MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001008 return true;
Evan Chenge96b8d72010-10-26 02:08:50 +00001009
1010 bool isCheap = false;
1011 unsigned NumDefs = MI.getDesc().getNumDefs();
1012 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1013 MachineOperand &DefMO = MI.getOperand(i);
1014 if (!DefMO.isReg() || !DefMO.isDef())
1015 continue;
1016 --NumDefs;
1017 unsigned Reg = DefMO.getReg();
1018 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1019 continue;
1020
Matthias Braun88e21312015-06-13 03:42:11 +00001021 if (!TII->hasLowDefLatency(SchedModel, &MI, i))
Evan Chenge96b8d72010-10-26 02:08:50 +00001022 return false;
1023 isCheap = true;
1024 }
1025
1026 return isCheap;
1027}
1028
Sanjay Patel87c6c072015-12-10 16:34:21 +00001029/// Visit BBs from header to current BB, check if hoisting an instruction of the
1030/// given cost matrix can cause high register pressure.
Daniel Jasperefece522015-04-03 16:19:48 +00001031bool MachineLICM::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001032 bool CheapInstr) {
Daniel Jasper274928f2015-04-14 11:56:25 +00001033 for (const auto &RPIdAndCost : Cost) {
1034 if (RPIdAndCost.second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001035 continue;
1036
Daniel Jasper274928f2015-04-14 11:56:25 +00001037 unsigned Class = RPIdAndCost.first;
Daniel Jasperefece522015-04-03 16:19:48 +00001038 int Limit = RegLimit[Class];
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001039
1040 // Don't hoist cheap instructions if they would increase register pressure,
1041 // even if we're under the limit.
Hal Finkel0709f512015-01-08 22:10:48 +00001042 if (CheapInstr && !HoistCheapInsts)
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001043 return true;
1044
Daniel Jasperefece522015-04-03 16:19:48 +00001045 for (const auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001046 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001047 return true;
Evan Cheng44436302010-10-16 02:20:26 +00001048 }
1049
1050 return false;
1051}
1052
Sanjay Patel87c6c072015-12-10 16:34:21 +00001053/// Traverse the back trace from header to the current block and update their
1054/// register pressures to reflect the effect of hoisting MI from the current
1055/// block to the preheader.
Evan Cheng87066f02010-10-20 22:03:58 +00001056void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
Evan Cheng87066f02010-10-20 22:03:58 +00001057 // First compute the 'cost' of the instruction, i.e. its contribution
1058 // to register pressure.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001059 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1060 /*ConsiderUnseenAsDef=*/false);
Evan Cheng87066f02010-10-20 22:03:58 +00001061
1062 // Update register pressure of blocks from loop header to current block.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001063 for (auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001064 for (const auto &RPIdAndCost : Cost)
1065 RP[RPIdAndCost.first] += RPIdAndCost.second;
Evan Cheng87066f02010-10-20 22:03:58 +00001066}
1067
Sanjay Patel87c6c072015-12-10 16:34:21 +00001068/// Return true if it is potentially profitable to hoist the given loop
1069/// invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001070bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001071 if (MI.isImplicitDef())
1072 return true;
1073
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001074 // Besides removing computation from the loop, hoisting an instruction has
1075 // these effects:
1076 //
1077 // - The value defined by the instruction becomes live across the entire
1078 // loop. This increases register pressure in the loop.
1079 //
1080 // - If the value is used by a PHI in the loop, a copy will be required for
1081 // lowering the PHI after extending the live range.
1082 //
1083 // - When hoisting the last use of a value in the loop, that value no longer
1084 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001085
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001086 bool CheapInstr = IsCheapInstruction(MI);
1087 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001088
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001089 // Don't hoist a cheap instruction if it would create a copy in the loop.
1090 if (CheapInstr && CreatesCopy) {
1091 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1092 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001093 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001094
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001095 // Rematerializable instructions should always be hoisted since the register
1096 // allocator can just pull them down again when needed.
1097 if (TII->isTriviallyReMaterializable(&MI, AA))
1098 return true;
1099
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001100 // FIXME: If there are long latency loop-invariant instructions inside the
1101 // loop at this point, why didn't the optimizer's LICM hoist them?
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001102 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1103 const MachineOperand &MO = MI.getOperand(i);
1104 if (!MO.isReg() || MO.isImplicit())
1105 continue;
1106 unsigned Reg = MO.getReg();
1107 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1108 continue;
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001109 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1110 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1111 ++NumHighLatency;
1112 return true;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001113 }
1114 }
1115
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001116 // Estimate register pressure to determine whether to LICM the instruction.
1117 // In low register pressure situation, we can be more aggressive about
1118 // hoisting. Also, favors hoisting long latency instructions even in
1119 // moderately high pressure situation.
1120 // Cheap instructions will only be hoisted if they don't increase register
1121 // pressure at all.
1122 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1123 /*ConsiderUnseenAsDef=*/false);
1124
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001125 // Visit BBs from header to current BB, if hoisting this doesn't cause
1126 // high register pressure, then it's safe to proceed.
1127 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1128 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1129 ++NumLowRP;
1130 return true;
1131 }
1132
1133 // Don't risk increasing register pressure if it would create copies.
1134 if (CreatesCopy) {
1135 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001136 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001137 }
1138
1139 // Do not "speculate" in high register pressure situation. If an
1140 // instruction is not guaranteed to be executed in the loop, it's best to be
1141 // conservative.
1142 if (AvoidSpeculation &&
1143 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1144 DEBUG(dbgs() << "Won't speculate: " << MI);
1145 return false;
1146 }
1147
1148 // High register pressure situation, only hoist if the instruction is going
1149 // to be remat'ed.
1150 if (!TII->isTriviallyReMaterializable(&MI, AA) &&
1151 !MI.isInvariantLoad(AA)) {
1152 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1153 return false;
1154 }
Evan Cheng399660c2009-02-05 08:45:46 +00001155
1156 return true;
1157}
1158
Sanjay Patel87c6c072015-12-10 16:34:21 +00001159/// Unfold a load from the given machineinstr if the load itself could be
1160/// hoisted. Return the unfolded and hoistable load, or null if the load
1161/// couldn't be unfolded or if it wouldn't be hoistable.
Dan Gohman104f57c2009-10-29 17:47:20 +00001162MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001163 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001164 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001165 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001166
Dan Gohman104f57c2009-10-29 17:47:20 +00001167 // If not, we may be able to unfold a load and hoist that.
1168 // First test whether the instruction is loading from an amenable
1169 // memory location.
Evan Chengb8b0ad82011-01-20 08:34:58 +00001170 if (!MI->isInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001171 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001172
Dan Gohman104f57c2009-10-29 17:47:20 +00001173 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001174 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001175 unsigned NewOpc =
1176 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1177 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001178 /*UnfoldStore=*/false,
1179 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001180 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001181 const MCInstrDesc &MID = TII->get(NewOpc);
Craig Topperc0196b12014-04-14 00:51:57 +00001182 if (MID.getNumDefs() != 1) return nullptr;
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001183 MachineFunction &MF = *MI->getParent()->getParent();
1184 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001185 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Chengd62719c2010-10-14 01:16:09 +00001186 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001187
Dan Gohman104f57c2009-10-29 17:47:20 +00001188 SmallVector<MachineInstr *, 2> NewMIs;
1189 bool Success =
1190 TII->unfoldMemoryOperand(MF, MI, Reg,
1191 /*UnfoldLoad=*/true, /*UnfoldStore=*/false,
1192 NewMIs);
1193 (void)Success;
1194 assert(Success &&
1195 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1196 "succeeded!");
1197 assert(NewMIs.size() == 2 &&
1198 "Unfolded a load into multiple instructions!");
1199 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001200 MachineBasicBlock::iterator Pos = MI;
1201 MBB->insert(Pos, NewMIs[0]);
1202 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001203 // If unfolding produced a load that wasn't loop-invariant or profitable to
1204 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001205 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001206 NewMIs[0]->eraseFromParent();
1207 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001208 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001209 }
Evan Cheng87066f02010-10-20 22:03:58 +00001210
1211 // Update register pressure for the unfolded instruction.
1212 UpdateRegPressure(NewMIs[1]);
1213
Dan Gohman104f57c2009-10-29 17:47:20 +00001214 // Otherwise we successfully unfolded a load that we can hoist.
1215 MI->eraseFromParent();
1216 return NewMIs[0];
1217}
1218
Sanjay Patel87c6c072015-12-10 16:34:21 +00001219/// Initialize the CSE map with instructions that are in the current loop
1220/// preheader that may become duplicates of instructions that are hoisted
1221/// out of the loop.
Evan Chengf42b5af2009-11-03 21:40:02 +00001222void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
1223 for (MachineBasicBlock::iterator I = BB->begin(),E = BB->end(); I != E; ++I) {
1224 const MachineInstr *MI = &*I;
Evan Chengb8b0ad82011-01-20 08:34:58 +00001225 unsigned Opcode = MI->getOpcode();
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001226 CSEMap[Opcode].push_back(MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001227 }
1228}
1229
Sanjay Patel87c6c072015-12-10 16:34:21 +00001230/// Find an instruction amount PrevMIs that is a duplicate of MI.
1231/// Return this instruction if it's found.
Evan Cheng7ff83192009-11-07 03:52:02 +00001232const MachineInstr*
1233MachineLICM::LookForDuplicate(const MachineInstr *MI,
1234 std::vector<const MachineInstr*> &PrevMIs) {
Evan Cheng921152f2009-11-05 00:51:13 +00001235 for (unsigned i = 0, e = PrevMIs.size(); i != e; ++i) {
1236 const MachineInstr *PrevMI = PrevMIs[i];
Craig Topperc0196b12014-04-14 00:51:57 +00001237 if (TII->produceSameValue(MI, PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001238 return PrevMI;
1239 }
Craig Topperc0196b12014-04-14 00:51:57 +00001240 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001241}
1242
Sanjay Patel87c6c072015-12-10 16:34:21 +00001243/// Given a LICM'ed instruction, look for an instruction on the preheader that
1244/// computes the same value. If it's found, do a RAU on with the definition of
1245/// the existing instruction rather than hoisting the instruction to the
1246/// preheader.
Evan Cheng921152f2009-11-05 00:51:13 +00001247bool MachineLICM::EliminateCSE(MachineInstr *MI,
1248 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001249 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1250 // the undef property onto uses.
1251 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001252 return false;
1253
1254 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene55cf95c2010-01-05 00:03:48 +00001255 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001256
1257 // Replace virtual registers defined by MI by their counterparts defined
1258 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001259 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001260 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1261 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001262
1263 // Physical registers may not differ here.
1264 assert((!MO.isReg() || MO.getReg() == 0 ||
1265 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1266 MO.getReg() == Dup->getOperand(i).getReg()) &&
1267 "Instructions with different phys regs are not identical!");
1268
1269 if (MO.isReg() && MO.isDef() &&
Evan Chengaa563df2011-10-17 19:50:12 +00001270 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1271 Defs.push_back(i);
1272 }
1273
1274 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1275 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1276 unsigned Idx = Defs[i];
1277 unsigned Reg = MI->getOperand(Idx).getReg();
1278 unsigned DupReg = Dup->getOperand(Idx).getReg();
1279 OrigRCs.push_back(MRI->getRegClass(DupReg));
1280
1281 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1282 // Restore old RCs if more than one defs.
1283 for (unsigned j = 0; j != i; ++j)
1284 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1285 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001286 }
Evan Cheng921152f2009-11-05 00:51:13 +00001287 }
Evan Chengaa563df2011-10-17 19:50:12 +00001288
1289 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1290 unsigned Idx = Defs[i];
1291 unsigned Reg = MI->getOperand(Idx).getReg();
1292 unsigned DupReg = Dup->getOperand(Idx).getReg();
1293 MRI->replaceRegWith(Reg, DupReg);
1294 MRI->clearKillFlags(DupReg);
1295 }
1296
Evan Cheng7ff83192009-11-07 03:52:02 +00001297 MI->eraseFromParent();
1298 ++NumCSEed;
1299 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001300 }
1301 return false;
1302}
1303
Sanjay Patel87c6c072015-12-10 16:34:21 +00001304/// Return true if the given instruction will be CSE'd if it's hoisted out of
1305/// the loop.
Evan Chengaf138952011-10-12 00:09:14 +00001306bool MachineLICM::MayCSE(MachineInstr *MI) {
1307 unsigned Opcode = MI->getOpcode();
1308 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1309 CI = CSEMap.find(Opcode);
1310 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1311 // the undef property onto uses.
1312 if (CI == CSEMap.end() || MI->isImplicitDef())
1313 return false;
1314
Craig Topperc0196b12014-04-14 00:51:57 +00001315 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001316}
1317
Sanjay Patel87c6c072015-12-10 16:34:21 +00001318/// When an instruction is found to use only loop invariant operands
Bill Wendling70613b82008-05-12 19:38:32 +00001319/// that are safe to hoist, this instruction is called to do the dirty work.
Sanjay Patel87c6c072015-12-10 16:34:21 +00001320/// It returns true if the instruction is hoisted.
Evan Cheng87066f02010-10-20 22:03:58 +00001321bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman1b44f102009-10-28 03:21:57 +00001322 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001323 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001324 // If not, try unfolding a hoistable load.
1325 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001326 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001327 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001328
Dan Gohman79618d12009-01-15 22:01:38 +00001329 // Now move the instructions to the predecessor, inserting it before any
1330 // terminator instructions.
1331 DEBUG({
David Greene55cf95c2010-01-05 00:03:48 +00001332 dbgs() << "Hoisting " << *MI;
Dan Gohman3570f812010-06-22 17:25:57 +00001333 if (Preheader->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001334 dbgs() << " to MachineBasicBlock "
Dan Gohman3570f812010-06-22 17:25:57 +00001335 << Preheader->getName();
Dan Gohman1b44f102009-10-28 03:21:57 +00001336 if (MI->getParent()->getBasicBlock())
David Greene55cf95c2010-01-05 00:03:48 +00001337 dbgs() << " from MachineBasicBlock "
Jakob Stoklund Olesen2bbeaa82009-11-20 01:17:03 +00001338 << MI->getParent()->getName();
David Greene55cf95c2010-01-05 00:03:48 +00001339 dbgs() << "\n";
Dan Gohman79618d12009-01-15 22:01:38 +00001340 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001341
Evan Chengf42b5af2009-11-03 21:40:02 +00001342 // If this is the first instruction being hoisted to the preheader,
1343 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001344 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001345 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001346 FirstInLoop = false;
1347 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001348
Evan Cheng399660c2009-02-05 08:45:46 +00001349 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001350 unsigned Opcode = MI->getOpcode();
1351 DenseMap<unsigned, std::vector<const MachineInstr*> >::iterator
1352 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001353 if (!EliminateCSE(MI, CI)) {
1354 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001355 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001356
Evan Cheng87066f02010-10-20 22:03:58 +00001357 // Update register pressure for BBs from header to this block.
1358 UpdateBackTraceRegPressure(MI);
1359
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001360 // Clear the kill flags of any register this instruction defines,
1361 // since they may need to be live throughout the entire loop
1362 // rather than just live for part of it.
1363 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1364 MachineOperand &MO = MI->getOperand(i);
1365 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001366 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001367 }
1368
Evan Cheng399660c2009-02-05 08:45:46 +00001369 // Add to the CSE map.
1370 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001371 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001372 else
1373 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001374 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001375
Dan Gohman79618d12009-01-15 22:01:38 +00001376 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001377 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001378
1379 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001380}
Dan Gohman3570f812010-06-22 17:25:57 +00001381
Sanjay Patel87c6c072015-12-10 16:34:21 +00001382/// Get the preheader for the current loop, splitting a critical edge if needed.
Dan Gohman3570f812010-06-22 17:25:57 +00001383MachineBasicBlock *MachineLICM::getCurPreheader() {
1384 // Determine the block to which to hoist instructions. If we can't find a
1385 // suitable loop predecessor, we can't do any hoisting.
1386
1387 // If we've tried to get a preheader and failed, don't try again.
1388 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001389 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001390
1391 if (!CurPreheader) {
1392 CurPreheader = CurLoop->getLoopPreheader();
1393 if (!CurPreheader) {
1394 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1395 if (!Pred) {
1396 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001397 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001398 }
1399
1400 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), this);
1401 if (!CurPreheader) {
1402 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001403 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001404 }
1405 }
1406 }
1407 return CurPreheader;
1408}