blob: efb5c3371de2b21cedd569822562e06587258159 [file] [log] [blame]
Eugene Zelenkof1933322017-09-22 23:46:57 +00001//===- MachineLICM.cpp - Machine Loop Invariant Code Motion Pass ----------===//
Bill Wendlingfb706bc2007-12-07 21:42:31 +00002//
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
Eugene Zelenkof1933322017-09-22 23:46:57 +000019#include "llvm/ADT/BitVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/DenseMap.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000021#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/SmallSet.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000023#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/Statistic.h"
25#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000026#include "llvm/CodeGen/MachineBasicBlock.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000027#include "llvm/CodeGen/MachineDominators.h"
Evan Cheng6ea59492010-04-07 00:41:17 +000028#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFunctionPass.h"
31#include "llvm/CodeGen/MachineInstr.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000032#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000033#include "llvm/CodeGen/MachineMemOperand.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000034#include "llvm/CodeGen/MachineOperand.h"
Bill Wendling5da19452008-01-02 19:32:43 +000035#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000036#include "llvm/CodeGen/PseudoSourceValue.h"
Matthias Braun88e21312015-06-13 03:42:11 +000037#include "llvm/CodeGen/TargetSchedule.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000038#include "llvm/IR/DebugLoc.h"
39#include "llvm/MC/MCInstrDesc.h"
40#include "llvm/MC/MCRegisterInfo.h"
41#include "llvm/Pass.h"
42#include "llvm/Support/Casting.h"
Evan Chengb35afca2011-10-12 21:33:49 +000043#include "llvm/Support/CommandLine.h"
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000044#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000045#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000046#include "llvm/Target/TargetInstrInfo.h"
47#include "llvm/Target/TargetLowering.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000048#include "llvm/Target/TargetRegisterInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000049#include "llvm/Target/TargetSubtargetInfo.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000050#include <algorithm>
51#include <cassert>
52#include <limits>
53#include <vector>
54
Bill Wendlingfb706bc2007-12-07 21:42:31 +000055using namespace llvm;
56
Matthias Braun1527baa2017-05-25 21:26:32 +000057#define DEBUG_TYPE "machinelicm"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000058
Evan Chengb35afca2011-10-12 21:33:49 +000059static cl::opt<bool>
60AvoidSpeculation("avoid-speculation",
61 cl::desc("MachineLICM should avoid speculation"),
Evan Cheng73133372011-10-26 01:26:57 +000062 cl::init(true), cl::Hidden);
Evan Chengb35afca2011-10-12 21:33:49 +000063
Hal Finkel0709f512015-01-08 22:10:48 +000064static cl::opt<bool>
65HoistCheapInsts("hoist-cheap-insts",
66 cl::desc("MachineLICM should hoist even cheap instructions"),
67 cl::init(false), cl::Hidden);
68
Daniel Jasper15e69542015-03-14 10:58:38 +000069static cl::opt<bool>
70SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
71 cl::desc("MachineLICM should sink instructions into "
72 "loops to avoid register spills"),
73 cl::init(false), cl::Hidden);
74
Evan Cheng44436302010-10-16 02:20:26 +000075STATISTIC(NumHoisted,
76 "Number of machine instructions hoisted out of loops");
77STATISTIC(NumLowRP,
78 "Number of instructions hoisted in low reg pressure situation");
79STATISTIC(NumHighLatency,
80 "Number of high latency instructions hoisted");
81STATISTIC(NumCSEed,
82 "Number of hoisted machine instructions CSEed");
Evan Cheng6ea59492010-04-07 00:41:17 +000083STATISTIC(NumPostRAHoisted,
84 "Number of machine instructions hoisted out of loops post regalloc");
Bill Wendling43751732007-12-08 01:47:01 +000085
Bill Wendlingfb706bc2007-12-07 21:42:31 +000086namespace {
Eugene Zelenkof1933322017-09-22 23:46:57 +000087
Nick Lewycky02d5f772009-10-25 06:33:48 +000088 class MachineLICM : public MachineFunctionPass {
Bill Wendling38236ef2007-12-11 23:27:51 +000089 const TargetInstrInfo *TII;
Benjamin Kramer56b31bd2013-01-11 20:05:37 +000090 const TargetLoweringBase *TLI;
Dan Gohmane30d63f2009-09-25 23:58:45 +000091 const TargetRegisterInfo *TRI;
Evan Cheng6ea59492010-04-07 00:41:17 +000092 const MachineFrameInfo *MFI;
Evan Chengd62719c2010-10-14 01:16:09 +000093 MachineRegisterInfo *MRI;
Matthias Braun88e21312015-06-13 03:42:11 +000094 TargetSchedModel SchedModel;
Eugene Zelenkof1933322017-09-22 23:46:57 +000095 bool PreRegAlloc = true;
Bill Wendlingb678ae72007-12-11 19:40:06 +000096
Bill Wendlingfb706bc2007-12-07 21:42:31 +000097 // Various analyses that we use...
Dan Gohmanbe8137b2009-10-07 17:38:06 +000098 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng058b9f02010-04-08 01:03:47 +000099 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendling70613b82008-05-12 19:38:32 +0000100 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000101
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000102 // State that is updated as we process loops
Bill Wendling70613b82008-05-12 19:38:32 +0000103 bool Changed; // True if a loop is changed.
Evan Cheng032f3262010-05-29 00:06:36 +0000104 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendling70613b82008-05-12 19:38:32 +0000105 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohman79618d12009-01-15 22:01:38 +0000106 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Cheng399660c2009-02-05 08:45:46 +0000107
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000108 // Exit blocks for CurLoop.
Eugene Zelenkof1933322017-09-22 23:46:57 +0000109 SmallVector<MachineBasicBlock *, 8> ExitBlocks;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000110
111 bool isExitBlock(const MachineBasicBlock *MBB) const {
David Majnemer0d955d02016-08-11 22:21:41 +0000112 return is_contained(ExitBlocks, MBB);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000113 }
114
Evan Chengd62719c2010-10-14 01:16:09 +0000115 // Track 'estimated' register pressure.
Evan Cheng44436302010-10-16 02:20:26 +0000116 SmallSet<unsigned, 32> RegSeen;
Evan Chengd62719c2010-10-14 01:16:09 +0000117 SmallVector<unsigned, 8> RegPressure;
Evan Cheng44436302010-10-16 02:20:26 +0000118
Daniel Jasper274928f2015-04-14 11:56:25 +0000119 // Register pressure "limit" per register pressure set. If the pressure
Evan Cheng44436302010-10-16 02:20:26 +0000120 // is higher than the limit, then it's considered high.
Evan Chengd62719c2010-10-14 01:16:09 +0000121 SmallVector<unsigned, 8> RegLimit;
122
Evan Cheng44436302010-10-16 02:20:26 +0000123 // Register pressure on path leading from loop preheader to current BB.
124 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
125
Dale Johannesen329d4742010-07-29 17:45:24 +0000126 // For each opcode, keep a list of potential CSE instructions.
Eugene Zelenkof1933322017-09-22 23:46:57 +0000127 DenseMap<unsigned, std::vector<const MachineInstr *>> CSEMap;
Evan Cheng6ea59492010-04-07 00:41:17 +0000128
Evan Chengf192ca02011-10-11 23:48:44 +0000129 enum {
130 SpeculateFalse = 0,
131 SpeculateTrue = 1,
132 SpeculateUnknown = 2
133 };
134
Devang Patel453d4012011-10-11 18:09:58 +0000135 // If a MBB does not dominate loop exiting blocks then it may not safe
136 // to hoist loads from this block.
Evan Chengf192ca02011-10-11 23:48:44 +0000137 // Tri-state: 0 - false, 1 - true, 2 - unknown
138 unsigned SpeculationState;
Devang Patel453d4012011-10-11 18:09:58 +0000139
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000140 public:
141 static char ID; // Pass identification, replacement for typeid
Evan Cheng6ea59492010-04-07 00:41:17 +0000142
Eugene Zelenkof1933322017-09-22 23:46:57 +0000143 MachineLICM() : MachineFunctionPass(ID) {
144 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
145 }
146
147 explicit MachineLICM(bool PreRA)
148 : MachineFunctionPass(ID), PreRegAlloc(PreRA) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000149 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
Eugene Zelenkof1933322017-09-22 23:46:57 +0000150 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000151
Craig Topper4584cd52014-03-07 09:26:03 +0000152 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000153
Craig Topper4584cd52014-03-07 09:26:03 +0000154 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000155 AU.addRequired<MachineLoopInfo>();
156 AU.addRequired<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000157 AU.addRequired<AAResultsWrapperPass>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000158 AU.addPreserved<MachineLoopInfo>();
159 AU.addPreserved<MachineDominatorTree>();
160 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000161 }
Evan Cheng399660c2009-02-05 08:45:46 +0000162
Craig Topper4584cd52014-03-07 09:26:03 +0000163 void releaseMemory() override {
Evan Cheng44436302010-10-16 02:20:26 +0000164 RegSeen.clear();
Evan Chengd62719c2010-10-14 01:16:09 +0000165 RegPressure.clear();
166 RegLimit.clear();
Evan Cheng63c76082010-10-19 18:58:51 +0000167 BackTrace.clear();
Evan Cheng399660c2009-02-05 08:45:46 +0000168 CSEMap.clear();
169 }
170
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000171 private:
Sanjay Patel87c6c072015-12-10 16:34:21 +0000172 /// Keep track of information about hoisting candidates.
Evan Cheng058b9f02010-04-08 01:03:47 +0000173 struct CandidateInfo {
174 MachineInstr *MI;
Evan Cheng058b9f02010-04-08 01:03:47 +0000175 unsigned Def;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000176 int FI;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000177
Evan Cheng0a2aff22010-04-13 18:16:00 +0000178 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
179 : MI(mi), Def(def), FI(fi) {}
Evan Cheng058b9f02010-04-08 01:03:47 +0000180 };
181
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000182 void HoistRegionPostRA();
Evan Cheng058b9f02010-04-08 01:03:47 +0000183
Evan Cheng058b9f02010-04-08 01:03:47 +0000184 void HoistPostRA(MachineInstr *MI, unsigned Def);
185
Sanjay Patel87c6c072015-12-10 16:34:21 +0000186 void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
187 BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000188 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng058b9f02010-04-08 01:03:47 +0000189
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000190 void AddToLiveIns(unsigned Reg);
Evan Cheng058b9f02010-04-08 01:03:47 +0000191
Evan Cheng0a2aff22010-04-13 18:16:00 +0000192 bool IsLICMCandidate(MachineInstr &I);
193
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000194 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000195
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000196 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengef42bea2011-04-11 21:09:18 +0000197
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
Daniel Jasperefece522015-04-03 16:19:48 +0000203 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
204 bool Cheap);
Evan Cheng87066f02010-10-20 22:03:58 +0000205
Evan Cheng87066f02010-10-20 22:03:58 +0000206 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng44436302010-10-16 02:20:26 +0000207
Evan Cheng73f9a9e2009-11-20 23:31:34 +0000208 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000209
Devang Patel453d4012011-10-11 18:09:58 +0000210 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
211
Pete Cooper1eed5b52011-12-22 02:05:40 +0000212 void EnterScope(MachineBasicBlock *MBB);
213
214 void ExitScope(MachineBasicBlock *MBB);
215
Sanjay Patel87c6c072015-12-10 16:34:21 +0000216 void ExitScopeIfDone(
217 MachineDomTreeNode *Node,
218 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
219 DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
Pete Cooper1eed5b52011-12-22 02:05:40 +0000220
Pete Cooper1eed5b52011-12-22 02:05:40 +0000221 void HoistOutOfLoop(MachineDomTreeNode *LoopHeaderNode);
Sanjay Patel87c6c072015-12-10 16:34:21 +0000222
Pete Cooper1eed5b52011-12-22 02:05:40 +0000223 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000224
Daniel Jasper15e69542015-03-14 10:58:38 +0000225 void SinkIntoLoop();
226
Evan Chengd62719c2010-10-14 01:16:09 +0000227 void InitRegPressure(MachineBasicBlock *BB);
228
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000229 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
230 bool ConsiderSeen,
231 bool ConsiderUnseenAsDef);
232
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000233 void UpdateRegPressure(const MachineInstr *MI,
234 bool ConsiderUnseenAsDef = false);
Evan Chengd62719c2010-10-14 01:16:09 +0000235
Dan Gohman104f57c2009-10-29 17:47:20 +0000236 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
237
Sanjay Patel87c6c072015-12-10 16:34:21 +0000238 const MachineInstr *
239 LookForDuplicate(const MachineInstr *MI,
240 std::vector<const MachineInstr *> &PrevMIs);
Evan Cheng7ff83192009-11-07 03:52:02 +0000241
Sanjay Patel87c6c072015-12-10 16:34:21 +0000242 bool EliminateCSE(
243 MachineInstr *MI,
244 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI);
Evan Cheng921152f2009-11-05 00:51:13 +0000245
Evan Chengaf138952011-10-12 00:09:14 +0000246 bool MayCSE(MachineInstr *MI);
247
Evan Cheng87066f02010-10-20 22:03:58 +0000248 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Chengf42b5af2009-11-03 21:40:02 +0000249
Evan Chengf42b5af2009-11-03 21:40:02 +0000250 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman3570f812010-06-22 17:25:57 +0000251
Dan Gohman3570f812010-06-22 17:25:57 +0000252 MachineBasicBlock *getCurPreheader();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000253 };
Eugene Zelenkof1933322017-09-22 23:46:57 +0000254
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000255} // end anonymous namespace
256
Dan Gohmand78c4002008-05-13 00:00:25 +0000257char MachineLICM::ID = 0;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000258
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000259char &llvm::MachineLICMID = MachineLICM::ID;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000260
Matthias Braun1527baa2017-05-25 21:26:32 +0000261INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
262 "Machine Loop Invariant Code Motion", false, false)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000263INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
264INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000265INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000266INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
267 "Machine Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000268
Sanjay Patel87c6c072015-12-10 16:34:21 +0000269/// Test if the given loop is the outer-most loop that has a unique predecessor.
Dan Gohman3570f812010-06-22 17:25:57 +0000270static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohman7929c442010-07-09 18:49:45 +0000271 // Check whether this loop even has a unique predecessor.
272 if (!CurLoop->getLoopPredecessor())
273 return false;
274 // Ok, now check to see if any of its outer loops do.
Dan Gohman79618d12009-01-15 22:01:38 +0000275 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman3570f812010-06-22 17:25:57 +0000276 if (L->getLoopPredecessor())
Dan Gohman79618d12009-01-15 22:01:38 +0000277 return false;
Dan Gohman7929c442010-07-09 18:49:45 +0000278 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohman79618d12009-01-15 22:01:38 +0000279 return true;
280}
281
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000282bool MachineLICM::runOnMachineFunction(MachineFunction &MF) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000283 if (skipFunction(*MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000284 return false;
285
Evan Cheng032f3262010-05-29 00:06:36 +0000286 Changed = FirstInLoop = false;
Matthias Braun88e21312015-06-13 03:42:11 +0000287 const TargetSubtargetInfo &ST = MF.getSubtarget();
288 TII = ST.getInstrInfo();
289 TLI = ST.getTargetLowering();
290 TRI = ST.getRegisterInfo();
Matthias Braun941a7052016-07-28 18:40:00 +0000291 MFI = &MF.getFrameInfo();
Evan Chengd62719c2010-10-14 01:16:09 +0000292 MRI = &MF.getRegInfo();
Matthias Braun88e21312015-06-13 03:42:11 +0000293 SchedModel.init(ST.getSchedModel(), &ST, TII);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000294
Andrew Trickc40815d2012-02-08 21:23:03 +0000295 PreRegAlloc = MRI->isSSA();
296
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000297 if (PreRegAlloc)
298 DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
299 else
300 DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
Craig Toppera538d832012-08-22 06:07:19 +0000301 DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000302
Evan Chengd62719c2010-10-14 01:16:09 +0000303 if (PreRegAlloc) {
304 // Estimate register pressure during pre-regalloc pass.
Daniel Jasper274928f2015-04-14 11:56:25 +0000305 unsigned NumRPS = TRI->getNumRegPressureSets();
306 RegPressure.resize(NumRPS);
Evan Chengd62719c2010-10-14 01:16:09 +0000307 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Daniel Jasper274928f2015-04-14 11:56:25 +0000308 RegLimit.resize(NumRPS);
309 for (unsigned i = 0, e = NumRPS; i != e; ++i)
310 RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
Evan Chengd62719c2010-10-14 01:16:09 +0000311 }
312
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000313 // Get our Loop information...
Evan Cheng058b9f02010-04-08 01:03:47 +0000314 MLI = &getAnalysis<MachineLoopInfo>();
315 DT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000316 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000317
Dan Gohman7929c442010-07-09 18:49:45 +0000318 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
319 while (!Worklist.empty()) {
320 CurLoop = Worklist.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000321 CurPreheader = nullptr;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000322 ExitBlocks.clear();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000323
Evan Cheng058b9f02010-04-08 01:03:47 +0000324 // If this is done before regalloc, only visit outer-most preheader-sporting
325 // loops.
Dan Gohman7929c442010-07-09 18:49:45 +0000326 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
327 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohman79618d12009-01-15 22:01:38 +0000328 continue;
Dan Gohman7929c442010-07-09 18:49:45 +0000329 }
Dan Gohman79618d12009-01-15 22:01:38 +0000330
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000331 CurLoop->getExitBlocks(ExitBlocks);
332
Evan Cheng6ea59492010-04-07 00:41:17 +0000333 if (!PreRegAlloc)
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000334 HoistRegionPostRA();
Evan Cheng6ea59492010-04-07 00:41:17 +0000335 else {
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000336 // CSEMap is initialized for loop header when the first instruction is
337 // being hoisted.
338 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng032f3262010-05-29 00:06:36 +0000339 FirstInLoop = true;
Pete Cooper1eed5b52011-12-22 02:05:40 +0000340 HoistOutOfLoop(N);
Evan Cheng6ea59492010-04-07 00:41:17 +0000341 CSEMap.clear();
Daniel Jasper15e69542015-03-14 10:58:38 +0000342
343 if (SinkInstsToAvoidSpills)
344 SinkIntoLoop();
Evan Cheng6ea59492010-04-07 00:41:17 +0000345 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000346 }
347
348 return Changed;
349}
350
Sanjay Patel87c6c072015-12-10 16:34:21 +0000351/// Return true if instruction stores to the specified frame.
Evan Cheng058b9f02010-04-08 01:03:47 +0000352static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
Philip Reames42bd26f2015-12-23 17:05:57 +0000353 // If we lost memory operands, conservatively assume that the instruction
Michael Liaoa5d45372017-04-26 05:27:20 +0000354 // writes to all slots.
Philip Reames42bd26f2015-12-23 17:05:57 +0000355 if (MI->memoperands_empty())
356 return true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000357 for (const MachineMemOperand *MemOp : MI->memoperands()) {
358 if (!MemOp->isStore() || !MemOp->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000359 continue;
360 if (const FixedStackPseudoSourceValue *Value =
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000361 dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000362 if (Value->getFrameIndex() == FI)
363 return true;
364 }
365 }
366 return false;
367}
368
Sanjay Patel87c6c072015-12-10 16:34:21 +0000369/// Examine the instruction for potentai LICM candidate. Also
Evan Cheng058b9f02010-04-08 01:03:47 +0000370/// gather register def and frame object update information.
371void MachineLICM::ProcessMI(MachineInstr *MI,
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000372 BitVector &PhysRegDefs,
373 BitVector &PhysRegClobbers,
Evan Cheng058b9f02010-04-08 01:03:47 +0000374 SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000375 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000376 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000377 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000378 unsigned Def = 0;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000379 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000380 if (MO.isFI()) {
381 // Remember if the instruction stores to the frame index.
382 int FI = MO.getIndex();
383 if (!StoredFIs.count(FI) &&
384 MFI->isSpillSlotObjectIndex(FI) &&
385 InstructionStoresToFI(MI, FI))
386 StoredFIs.insert(FI);
Evan Cheng89e74792010-04-13 20:21:05 +0000387 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000388 continue;
389 }
390
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000391 // We can't hoist an instruction defining a physreg that is clobbered in
392 // the loop.
393 if (MO.isRegMask()) {
Jakob Stoklund Olesen5e1ac452012-02-02 23:52:57 +0000394 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000395 continue;
396 }
397
Evan Cheng058b9f02010-04-08 01:03:47 +0000398 if (!MO.isReg())
399 continue;
400 unsigned Reg = MO.getReg();
401 if (!Reg)
402 continue;
403 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
404 "Not expecting virtual register!");
405
Evan Cheng0a2aff22010-04-13 18:16:00 +0000406 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000407 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-04-13 20:21:05 +0000408 // If it's using a non-loop-invariant register, then it's obviously not
409 // safe to hoist.
410 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000411 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000412 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000413
414 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000415 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
416 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000417 if (!MO.isDead())
418 // Non-dead implicit def? This cannot be hoisted.
419 RuledOut = true;
420 // No need to check if a dead implicit def is also defined by
421 // another instruction.
422 continue;
423 }
424
425 // FIXME: For now, avoid instructions with multiple defs, unless
426 // it's a dead implicit def.
427 if (Def)
428 RuledOut = true;
429 else
430 Def = Reg;
431
432 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000433 // register, then this is not safe. Two defs is indicated by setting a
434 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000435 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000436 if (PhysRegDefs.test(*AS))
437 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000438 PhysRegDefs.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000439 }
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000440 if (PhysRegClobbers.test(Reg))
441 // MI defined register is seen defined by another instruction in
442 // the loop, it cannot be a LICM candidate.
443 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000444 }
445
Evan Cheng0a2aff22010-04-13 18:16:00 +0000446 // Only consider reloads for now and remats which do not have register
447 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000448 if (Def && !RuledOut) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000449 int FI = std::numeric_limits<int>::min();
Evan Cheng89e74792010-04-13 20:21:05 +0000450 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000451 (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
Evan Cheng0a2aff22010-04-13 18:16:00 +0000452 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000453 }
454}
455
Sanjay Patel87c6c072015-12-10 16:34:21 +0000456/// Walk the specified region of the CFG and hoist loop invariants out to the
457/// preheader.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000458void MachineLICM::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000459 MachineBasicBlock *Preheader = getCurPreheader();
460 if (!Preheader)
461 return;
462
Evan Cheng6ea59492010-04-07 00:41:17 +0000463 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000464 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
465 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000466
Evan Cheng058b9f02010-04-08 01:03:47 +0000467 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000468 SmallSet<int, 32> StoredFIs;
469
470 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000471 // collect potential LICM candidates.
Benjamin Kramer7d605262013-09-15 22:04:42 +0000472 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000473 for (MachineBasicBlock *BB : Blocks) {
Bill Wendling918cea22011-10-12 02:58:01 +0000474 // If the header of the loop containing this basic block is a landing pad,
475 // then don't try to hoist instructions out of this loop.
476 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000477 if (ML && ML->getHeader()->isEHPad()) continue;
Bill Wendling918cea22011-10-12 02:58:01 +0000478
Evan Cheng6ea59492010-04-07 00:41:17 +0000479 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000480 // FIXME: That means a reload that're reused in successor block(s) will not
481 // be LICM'ed.
Matthias Braund9da1622015-09-09 18:08:03 +0000482 for (const auto &LI : BB->liveins()) {
483 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000484 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000485 }
486
Evan Chengf192ca02011-10-11 23:48:44 +0000487 SpeculationState = SpeculateUnknown;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000488 for (MachineInstr &MI : *BB)
489 ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000490 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000491
Evan Cheng7fede872012-03-27 01:50:58 +0000492 // Gather the registers read / clobbered by the terminator.
493 BitVector TermRegs(NumRegs);
494 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
495 if (TI != Preheader->end()) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000496 for (const MachineOperand &MO : TI->operands()) {
Evan Cheng7fede872012-03-27 01:50:58 +0000497 if (!MO.isReg())
498 continue;
499 unsigned Reg = MO.getReg();
500 if (!Reg)
501 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000502 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
503 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000504 }
505 }
506
Evan Cheng6ea59492010-04-07 00:41:17 +0000507 // Now evaluate whether the potential candidates qualify.
508 // 1. Check if the candidate defined register is defined by another
509 // instruction in the loop.
510 // 2. If the candidate is a load from stack slot (always true for now),
511 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000512 // 3. Make sure candidate def should not clobber
513 // registers read by the terminator. Similarly its def should not be
514 // clobbered by the terminator.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000515 for (CandidateInfo &Candidate : Candidates) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000516 if (Candidate.FI != std::numeric_limits<int>::min() &&
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000517 StoredFIs.count(Candidate.FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000518 continue;
519
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000520 unsigned Def = Candidate.Def;
Evan Cheng7fede872012-03-27 01:50:58 +0000521 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000522 bool Safe = true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000523 MachineInstr *MI = Candidate.MI;
524 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng87585d72010-04-13 22:13:34 +0000525 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000526 continue;
Evan Cheng7fede872012-03-27 01:50:58 +0000527 unsigned Reg = MO.getReg();
528 if (PhysRegDefs.test(Reg) ||
529 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000530 // If it's using a non-loop-invariant register, then it's obviously
531 // not safe to hoist.
532 Safe = false;
533 break;
534 }
535 }
536 if (Safe)
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000537 HoistPostRA(MI, Candidate.Def);
Evan Cheng89e74792010-04-13 20:21:05 +0000538 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000539 }
540}
541
Sanjay Patel87c6c072015-12-10 16:34:21 +0000542/// Add register 'Reg' to the livein sets of BBs in the current loop, and make
543/// sure it is not killed by any instructions in the loop.
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000544void MachineLICM::AddToLiveIns(unsigned Reg) {
Benjamin Kramer7d605262013-09-15 22:04:42 +0000545 const std::vector<MachineBasicBlock *> &Blocks = CurLoop->getBlocks();
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000546 for (MachineBasicBlock *BB : Blocks) {
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000547 if (!BB->isLiveIn(Reg))
548 BB->addLiveIn(Reg);
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000549 for (MachineInstr &MI : *BB) {
550 for (MachineOperand &MO : MI.operands()) {
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000551 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
552 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
553 MO.setIsKill(false);
554 }
555 }
556 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000557}
558
Sanjay Patel87c6c072015-12-10 16:34:21 +0000559/// When an instruction is found to only use loop invariant operands that is
560/// safe to hoist, this instruction is called to do the dirty work.
Evan Cheng058b9f02010-04-08 01:03:47 +0000561void MachineLICM::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000562 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000563
Evan Cheng6ea59492010-04-07 00:41:17 +0000564 // Now move the instructions to the predecessor, inserting it before any
565 // terminator instructions.
Jakob Stoklund Olesen90823532012-01-23 21:01:11 +0000566 DEBUG(dbgs() << "Hoisting to BB#" << Preheader->getNumber() << " from BB#"
567 << MI->getParent()->getNumber() << ": " << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000568
569 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000570 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000571 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000572
Andrew Trick5209c732012-02-08 21:23:00 +0000573 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000574 // loop invariant must be kept live throughout the whole loop. This is
575 // important to ensure later passes do not scavenge the def register.
576 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000577
578 ++NumPostRAHoisted;
579 Changed = true;
580}
581
Sanjay Patel87c6c072015-12-10 16:34:21 +0000582/// Check if this mbb is guaranteed to execute. If not then a load from this mbb
583/// may not be safe to hoist.
Devang Patel453d4012011-10-11 18:09:58 +0000584bool MachineLICM::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000585 if (SpeculationState != SpeculateUnknown)
586 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000587
Devang Patel453d4012011-10-11 18:09:58 +0000588 if (BB != CurLoop->getHeader()) {
589 // Check loop exiting blocks.
590 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
591 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000592 for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
593 if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000594 SpeculationState = SpeculateTrue;
595 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000596 }
597 }
598
Evan Chengf192ca02011-10-11 23:48:44 +0000599 SpeculationState = SpeculateFalse;
600 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000601}
602
Pete Cooper1eed5b52011-12-22 02:05:40 +0000603void MachineLICM::EnterScope(MachineBasicBlock *MBB) {
Justin Lebarf6f4a2a2016-05-23 18:56:07 +0000604 DEBUG(dbgs() << "Entering BB#" << MBB->getNumber() << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000605
Pete Cooper1eed5b52011-12-22 02:05:40 +0000606 // Remember livein register pressure.
607 BackTrace.push_back(RegPressure);
608}
Bill Wendling918cea22011-10-12 02:58:01 +0000609
Pete Cooper1eed5b52011-12-22 02:05:40 +0000610void MachineLICM::ExitScope(MachineBasicBlock *MBB) {
Justin Lebarf6f4a2a2016-05-23 18:56:07 +0000611 DEBUG(dbgs() << "Exiting BB#" << MBB->getNumber() << '\n');
Pete Cooper1eed5b52011-12-22 02:05:40 +0000612 BackTrace.pop_back();
613}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000614
Sanjay Patel87c6c072015-12-10 16:34:21 +0000615/// Destroy scope for the MBB that corresponds to the given dominator tree node
616/// if its a leaf or all of its children are done. Walk up the dominator tree to
617/// destroy ancestors which are now done.
Pete Cooper1eed5b52011-12-22 02:05:40 +0000618void MachineLICM::ExitScopeIfDone(MachineDomTreeNode *Node,
Evan Chengda468322012-01-10 22:27:32 +0000619 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
620 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000621 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000622 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000623
Pete Cooper1eed5b52011-12-22 02:05:40 +0000624 // Pop scope.
625 ExitScope(Node->getBlock());
626
627 // Now traverse upwards to pop ancestors whose offsprings are all done.
628 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
629 unsigned Left = --OpenChildren[Parent];
630 if (Left != 0)
631 break;
632 ExitScope(Parent->getBlock());
633 Node = Parent;
634 }
635}
636
Sanjay Patel87c6c072015-12-10 16:34:21 +0000637/// Walk the specified loop in the CFG (defined by all blocks dominated by the
638/// specified header block, and that are in the current loop) in depth first
639/// order w.r.t the DominatorTree. This allows us to visit definitions before
640/// uses, allowing us to hoist a loop body in one pass without iteration.
Pete Cooper1eed5b52011-12-22 02:05:40 +0000641void MachineLICM::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000642 MachineBasicBlock *Preheader = getCurPreheader();
643 if (!Preheader)
644 return;
645
Pete Cooper1eed5b52011-12-22 02:05:40 +0000646 SmallVector<MachineDomTreeNode*, 32> Scopes;
647 SmallVector<MachineDomTreeNode*, 8> WorkList;
648 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
649 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
650
651 // Perform a DFS walk to determine the order of visit.
652 WorkList.push_back(HeaderN);
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000653 while (!WorkList.empty()) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000654 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000655 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000656 MachineBasicBlock *BB = Node->getBlock();
657
658 // If the header of the loop containing this basic block is a landing pad,
659 // then don't try to hoist instructions out of this loop.
660 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000661 if (ML && ML->getHeader()->isEHPad())
Pete Cooper1eed5b52011-12-22 02:05:40 +0000662 continue;
663
664 // If this subregion is not in the top level loop at all, exit.
665 if (!CurLoop->contains(BB))
666 continue;
667
668 Scopes.push_back(Node);
669 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
670 unsigned NumChildren = Children.size();
671
672 // Don't hoist things out of a large switch statement. This often causes
673 // code to be hoisted that wasn't going to be executed, and increases
674 // register pressure in a situation where it's likely to matter.
675 if (BB->succ_size() >= 25)
676 NumChildren = 0;
677
678 OpenChildren[Node] = NumChildren;
679 // Add children in reverse order as then the next popped worklist node is
680 // the first child of this node. This means we ultimately traverse the
681 // DOM tree in exactly the same order as if we'd recursed.
682 for (int i = (int)NumChildren-1; i >= 0; --i) {
683 MachineDomTreeNode *Child = Children[i];
684 ParentMap[Child] = Node;
685 WorkList.push_back(Child);
686 }
Daniel Dunbar418204e2010-10-19 17:14:24 +0000687 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000688
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000689 if (Scopes.size() == 0)
690 return;
691
692 // Compute registers which are livein into the loop headers.
693 RegSeen.clear();
694 BackTrace.clear();
695 InitRegPressure(Preheader);
696
Pete Cooper1eed5b52011-12-22 02:05:40 +0000697 // Now perform LICM.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000698 for (MachineDomTreeNode *Node : Scopes) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000699 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000700
Pete Cooper1eed5b52011-12-22 02:05:40 +0000701 EnterScope(MBB);
702
703 // Process the block
704 SpeculationState = SpeculateUnknown;
705 for (MachineBasicBlock::iterator
706 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
707 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
708 MachineInstr *MI = &*MII;
709 if (!Hoist(MI, Preheader))
710 UpdateRegPressure(MI);
711 MII = NextMII;
712 }
713
714 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
715 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000716 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000717}
718
Sanjay Patel87c6c072015-12-10 16:34:21 +0000719/// Sink instructions into loops if profitable. This especially tries to prevent
720/// register spills caused by register pressure if there is little to no
721/// overhead moving instructions into loops.
Daniel Jasper15e69542015-03-14 10:58:38 +0000722void MachineLICM::SinkIntoLoop() {
723 MachineBasicBlock *Preheader = getCurPreheader();
724 if (!Preheader)
725 return;
726
727 SmallVector<MachineInstr *, 8> Candidates;
728 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
729 I != Preheader->instr_end(); ++I) {
730 // We need to ensure that we can safely move this instruction into the loop.
Michael Liaoa5d45372017-04-26 05:27:20 +0000731 // 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 +0000732 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
733 Candidates.push_back(&*I);
Daniel Jasper15e69542015-03-14 10:58:38 +0000734 }
735
736 for (MachineInstr *I : Candidates) {
737 const MachineOperand &MO = I->getOperand(0);
738 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
739 continue;
740 if (!MRI->hasOneDef(MO.getReg()))
741 continue;
742 bool CanSink = true;
743 MachineBasicBlock *B = nullptr;
744 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
745 // FIXME: Come up with a proper cost model that estimates whether sinking
746 // the instruction (and thus possibly executing it on every loop
747 // iteration) is more expensive than a register.
748 // For now assumes that copies are cheap and thus almost always worth it.
749 if (!MI.isCopy()) {
750 CanSink = false;
751 break;
752 }
753 if (!B) {
754 B = MI.getParent();
755 continue;
756 }
757 B = DT->findNearestCommonDominator(B, MI.getParent());
758 if (!B) {
759 CanSink = false;
760 break;
761 }
762 }
763 if (!CanSink || !B || B == Preheader)
764 continue;
765 B->splice(B->getFirstNonPHI(), Preheader, I);
766 }
767}
768
Evan Cheng87066f02010-10-20 22:03:58 +0000769static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
770 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
771}
772
Sanjay Patel87c6c072015-12-10 16:34:21 +0000773/// Find all virtual register references that are liveout of the preheader to
774/// initialize the starting "register pressure". Note this does not count live
775/// through (livein but not used) registers.
Evan Chengd62719c2010-10-14 01:16:09 +0000776void MachineLICM::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000777 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000778
Evan Cheng87066f02010-10-20 22:03:58 +0000779 // If the preheader has only a single predecessor and it ends with a
780 // fallthrough or an unconditional branch, then scan its predecessor for live
781 // defs as well. This happens whenever the preheader is created by splitting
782 // the critical edge from the loop predecessor to the loop header.
783 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000784 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000785 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000786 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
Evan Cheng87066f02010-10-20 22:03:58 +0000787 InitRegPressure(*BB->pred_begin());
788 }
789
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000790 for (const MachineInstr &MI : *BB)
791 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
Evan Chengd62719c2010-10-14 01:16:09 +0000792}
793
Sanjay Patel87c6c072015-12-10 16:34:21 +0000794/// Update estimate of register pressure after the specified instruction.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000795void MachineLICM::UpdateRegPressure(const MachineInstr *MI,
796 bool ConsiderUnseenAsDef) {
797 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
Daniel Jasper274928f2015-04-14 11:56:25 +0000798 for (const auto &RPIdAndCost : Cost) {
799 unsigned Class = RPIdAndCost.first;
800 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000801 RegPressure[Class] = 0;
802 else
Daniel Jasper274928f2015-04-14 11:56:25 +0000803 RegPressure[Class] += RPIdAndCost.second;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000804 }
805}
Evan Chengd62719c2010-10-14 01:16:09 +0000806
Sanjay Patel87c6c072015-12-10 16:34:21 +0000807/// Calculate the additional register pressure that the registers used in MI
808/// cause.
809///
810/// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
811/// figure out which usages are live-ins.
812/// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000813DenseMap<unsigned, int>
814MachineLICM::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
815 bool ConsiderUnseenAsDef) {
816 DenseMap<unsigned, int> Cost;
817 if (MI->isImplicitDef())
818 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000819 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
820 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000821 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000822 continue;
823 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000824 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000825 continue;
826
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000827 // FIXME: It seems bad to use RegSeen only for some of these calculations.
828 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
Daniel Jasper274928f2015-04-14 11:56:25 +0000829 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
830
831 RegClassWeight W = TRI->getRegClassWeight(RC);
832 int RCCost = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000833 if (MO.isDef())
Daniel Jasper274928f2015-04-14 11:56:25 +0000834 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000835 else {
836 bool isKill = isOperandKill(MO, MRI);
837 if (isNew && !isKill && ConsiderUnseenAsDef)
838 // Haven't seen this, it must be a livein.
Daniel Jasper274928f2015-04-14 11:56:25 +0000839 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000840 else if (!isNew && isKill)
Daniel Jasper274928f2015-04-14 11:56:25 +0000841 RCCost = -W.RegWeight;
842 }
843 if (RCCost == 0)
844 continue;
845 const int *PS = TRI->getRegClassPressureSets(RC);
846 for (; *PS != -1; ++PS) {
847 if (Cost.find(*PS) == Cost.end())
848 Cost[*PS] = RCCost;
849 else
850 Cost[*PS] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000851 }
Evan Chengd62719c2010-10-14 01:16:09 +0000852 }
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000853 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000854}
855
Sanjay Patel87c6c072015-12-10 16:34:21 +0000856/// Return true if this machine instruction loads from global offset table or
857/// constant pool.
Philip Reames42bd26f2015-12-23 17:05:57 +0000858static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000859 assert(MI.mayLoad() && "Expected MI that loads!");
Michael Liaoa5d45372017-04-26 05:27:20 +0000860
Philip Reames42bd26f2015-12-23 17:05:57 +0000861 // If we lost memory operands, conservatively assume that the instruction
Michael Liaoa5d45372017-04-26 05:27:20 +0000862 // reads from everything..
Philip Reames42bd26f2015-12-23 17:05:57 +0000863 if (MI.memoperands_empty())
864 return true;
865
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000866 for (MachineMemOperand *MemOp : MI.memoperands())
867 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
Alex Lorenze40c8a22015-08-11 23:09:45 +0000868 if (PSV->isGOT() || PSV->isConstantPool())
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000869 return true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000870
Devang Patel69a45652011-10-17 17:35:01 +0000871 return false;
872}
873
Sanjay Patel87c6c072015-12-10 16:34:21 +0000874/// Returns true if the instruction may be a suitable candidate for LICM.
875/// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
Evan Cheng0a2aff22010-04-13 18:16:00 +0000876bool MachineLICM::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +0000877 // Check if it's safe to move the instruction.
878 bool DontMoveAcrossStore = true;
Matthias Braun07066cc2015-05-19 21:22:20 +0000879 if (!I.isSafeToMove(AA, DontMoveAcrossStore))
Chris Lattnerc8226f32008-01-10 23:08:24 +0000880 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000881
882 // If it is load then check if it is guaranteed to execute by making sure that
883 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +0000884 // the loop which does not execute this load, so we can't hoist it. Loads
885 // from constant memory are not safe to speculate all the time, for example
886 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +0000887 // Stores and side effects are already checked by isSafeToMove.
Philip Reames42bd26f2015-12-23 17:05:57 +0000888 if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +0000889 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +0000890 return false;
891
Evan Cheng0a2aff22010-04-13 18:16:00 +0000892 return true;
893}
894
Sanjay Patel87c6c072015-12-10 16:34:21 +0000895/// Returns true if the instruction is loop invariant.
896/// I.e., all virtual register operands are defined outside of the loop,
897/// physical registers aren't accessed explicitly, and there are no side
Evan Cheng0a2aff22010-04-13 18:16:00 +0000898/// effects that aren't captured by the operands or other flags.
Evan Cheng0a2aff22010-04-13 18:16:00 +0000899bool MachineLICM::IsLoopInvariantInst(MachineInstr &I) {
900 if (!IsLICMCandidate(I))
901 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +0000902
Bill Wendling70613b82008-05-12 19:38:32 +0000903 // The instruction is loop invariant if all of its operands are.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000904 for (const MachineOperand &MO : I.operands()) {
Dan Gohman0d1e9a82008-10-03 15:45:36 +0000905 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +0000906 continue;
907
Dan Gohman79618d12009-01-15 22:01:38 +0000908 unsigned Reg = MO.getReg();
909 if (Reg == 0) continue;
910
911 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmane30d63f2009-09-25 23:58:45 +0000912 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +0000913 if (MO.isUse()) {
914 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +0000915 // and we can freely move its uses. Alternatively, if it's allocatable,
916 // it could get allocated to something with a def during allocation.
Lei Huangb4733ca2017-06-15 18:29:59 +0000917 // However, if the physreg is known to always be caller saved/restored
918 // then this use is safe to hoist.
919 if (!MRI->isConstantPhysReg(Reg) &&
Justin Bognerfdf9bf42017-10-10 23:50:49 +0000920 !(TRI->isCallerPreservedPhysReg(Reg, *I.getMF())))
921 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000922 // Otherwise it's safe to move.
923 continue;
924 } else if (!MO.isDead()) {
925 // A def that isn't dead. We can't move it.
926 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +0000927 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
928 // If the reg is live into the loop, we can't hoist an instruction
929 // which would clobber it.
930 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +0000931 }
932 }
Bill Wendlingcd01e892008-08-20 20:32:05 +0000933
934 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000935 continue;
936
Evan Chengd62719c2010-10-14 01:16:09 +0000937 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +0000938 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000939
940 // If the loop contains the definition of an operand, then the instruction
941 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +0000942 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000943 return false;
944 }
945
946 // If we got this far, the instruction is loop invariant!
947 return true;
948}
949
Sanjay Patel87c6c072015-12-10 16:34:21 +0000950/// Return true if the specified instruction is used by a phi node and hoisting
951/// it could cause a copy to be inserted.
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000952bool MachineLICM::HasLoopPHIUse(const MachineInstr *MI) const {
953 SmallVector<const MachineInstr*, 8> Work(1, MI);
954 do {
955 MI = Work.pop_back_val();
Matthias Braune41e1462015-05-29 02:56:46 +0000956 for (const MachineOperand &MO : MI->operands()) {
957 if (!MO.isReg() || !MO.isDef())
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000958 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000959 unsigned Reg = MO.getReg();
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000960 if (!TargetRegisterInfo::isVirtualRegister(Reg))
961 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000962 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000963 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +0000964 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000965 // A PHI inside the loop causes a copy because the live range of Reg is
966 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +0000967 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000968 return true;
969 // A PHI in an exit block can cause a copy to be inserted if the PHI
970 // has multiple predecessors in the loop with different values.
971 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +0000972 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000973 return true;
974 continue;
975 }
976 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +0000977 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
978 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000979 }
Evan Chengef42bea2011-04-11 21:09:18 +0000980 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000981 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +0000982 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000983}
984
Sanjay Patel87c6c072015-12-10 16:34:21 +0000985/// Compute operand latency between a def of 'Reg' and an use in the current
986/// loop, return true if the target considered it high.
Evan Cheng63c76082010-10-19 18:58:51 +0000987bool MachineLICM::HasHighOperandLatency(MachineInstr &MI,
Evan Chenge96b8d72010-10-26 02:08:50 +0000988 unsigned DefIdx, unsigned Reg) const {
Matthias Braun88e21312015-06-13 03:42:11 +0000989 if (MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +0000990 return false;
Evan Chengd62719c2010-10-14 01:16:09 +0000991
Owen Andersonb36376e2014-03-17 19:36:09 +0000992 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
993 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +0000994 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000995 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +0000996 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +0000997 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
998 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +0000999 if (!MO.isReg() || !MO.isUse())
1000 continue;
1001 unsigned MOReg = MO.getReg();
1002 if (MOReg != Reg)
1003 continue;
1004
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001005 if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +00001006 return true;
Evan Chengd62719c2010-10-14 01:16:09 +00001007 }
1008
Evan Cheng63c76082010-10-19 18:58:51 +00001009 // Only look at the first in loop use.
1010 break;
Evan Chengd62719c2010-10-14 01:16:09 +00001011 }
1012
Evan Cheng63c76082010-10-19 18:58:51 +00001013 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001014}
1015
Sanjay Patel87c6c072015-12-10 16:34:21 +00001016/// Return true if the instruction is marked "cheap" or the operand latency
1017/// between its def and a use is one or less.
Evan Chenge96b8d72010-10-26 02:08:50 +00001018bool MachineLICM::IsCheapInstruction(MachineInstr &MI) const {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001019 if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001020 return true;
Evan Chenge96b8d72010-10-26 02:08:50 +00001021
1022 bool isCheap = false;
1023 unsigned NumDefs = MI.getDesc().getNumDefs();
1024 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1025 MachineOperand &DefMO = MI.getOperand(i);
1026 if (!DefMO.isReg() || !DefMO.isDef())
1027 continue;
1028 --NumDefs;
1029 unsigned Reg = DefMO.getReg();
1030 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1031 continue;
1032
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001033 if (!TII->hasLowDefLatency(SchedModel, MI, i))
Evan Chenge96b8d72010-10-26 02:08:50 +00001034 return false;
1035 isCheap = true;
1036 }
1037
1038 return isCheap;
1039}
1040
Sanjay Patel87c6c072015-12-10 16:34:21 +00001041/// Visit BBs from header to current BB, check if hoisting an instruction of the
1042/// given cost matrix can cause high register pressure.
Daniel Jasperefece522015-04-03 16:19:48 +00001043bool MachineLICM::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001044 bool CheapInstr) {
Daniel Jasper274928f2015-04-14 11:56:25 +00001045 for (const auto &RPIdAndCost : Cost) {
1046 if (RPIdAndCost.second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001047 continue;
1048
Daniel Jasper274928f2015-04-14 11:56:25 +00001049 unsigned Class = RPIdAndCost.first;
Daniel Jasperefece522015-04-03 16:19:48 +00001050 int Limit = RegLimit[Class];
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001051
1052 // Don't hoist cheap instructions if they would increase register pressure,
1053 // even if we're under the limit.
Hal Finkel0709f512015-01-08 22:10:48 +00001054 if (CheapInstr && !HoistCheapInsts)
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001055 return true;
1056
Daniel Jasperefece522015-04-03 16:19:48 +00001057 for (const auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001058 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001059 return true;
Evan Cheng44436302010-10-16 02:20:26 +00001060 }
1061
1062 return false;
1063}
1064
Sanjay Patel87c6c072015-12-10 16:34:21 +00001065/// Traverse the back trace from header to the current block and update their
1066/// register pressures to reflect the effect of hoisting MI from the current
1067/// block to the preheader.
Evan Cheng87066f02010-10-20 22:03:58 +00001068void MachineLICM::UpdateBackTraceRegPressure(const MachineInstr *MI) {
Evan Cheng87066f02010-10-20 22:03:58 +00001069 // First compute the 'cost' of the instruction, i.e. its contribution
1070 // to register pressure.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001071 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1072 /*ConsiderUnseenAsDef=*/false);
Evan Cheng87066f02010-10-20 22:03:58 +00001073
1074 // Update register pressure of blocks from loop header to current block.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001075 for (auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001076 for (const auto &RPIdAndCost : Cost)
1077 RP[RPIdAndCost.first] += RPIdAndCost.second;
Evan Cheng87066f02010-10-20 22:03:58 +00001078}
1079
Sanjay Patel87c6c072015-12-10 16:34:21 +00001080/// Return true if it is potentially profitable to hoist the given loop
1081/// invariant.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001082bool MachineLICM::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001083 if (MI.isImplicitDef())
1084 return true;
1085
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001086 // Besides removing computation from the loop, hoisting an instruction has
1087 // these effects:
1088 //
1089 // - The value defined by the instruction becomes live across the entire
1090 // loop. This increases register pressure in the loop.
1091 //
1092 // - If the value is used by a PHI in the loop, a copy will be required for
1093 // lowering the PHI after extending the live range.
1094 //
1095 // - When hoisting the last use of a value in the loop, that value no longer
1096 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001097
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001098 bool CheapInstr = IsCheapInstruction(MI);
1099 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001100
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001101 // Don't hoist a cheap instruction if it would create a copy in the loop.
1102 if (CheapInstr && CreatesCopy) {
1103 DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
1104 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001105 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001106
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001107 // Rematerializable instructions should always be hoisted since the register
1108 // allocator can just pull them down again when needed.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001109 if (TII->isTriviallyReMaterializable(MI, AA))
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001110 return true;
1111
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001112 // FIXME: If there are long latency loop-invariant instructions inside the
1113 // loop at this point, why didn't the optimizer's LICM hoist them?
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001114 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1115 const MachineOperand &MO = MI.getOperand(i);
1116 if (!MO.isReg() || MO.isImplicit())
1117 continue;
1118 unsigned Reg = MO.getReg();
1119 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1120 continue;
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001121 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
1122 DEBUG(dbgs() << "Hoist High Latency: " << MI);
1123 ++NumHighLatency;
1124 return true;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001125 }
1126 }
1127
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001128 // Estimate register pressure to determine whether to LICM the instruction.
1129 // In low register pressure situation, we can be more aggressive about
1130 // hoisting. Also, favors hoisting long latency instructions even in
1131 // moderately high pressure situation.
1132 // Cheap instructions will only be hoisted if they don't increase register
1133 // pressure at all.
1134 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1135 /*ConsiderUnseenAsDef=*/false);
1136
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001137 // Visit BBs from header to current BB, if hoisting this doesn't cause
1138 // high register pressure, then it's safe to proceed.
1139 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
1140 DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
1141 ++NumLowRP;
1142 return true;
1143 }
1144
1145 // Don't risk increasing register pressure if it would create copies.
1146 if (CreatesCopy) {
1147 DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001148 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001149 }
1150
1151 // Do not "speculate" in high register pressure situation. If an
1152 // instruction is not guaranteed to be executed in the loop, it's best to be
1153 // conservative.
1154 if (AvoidSpeculation &&
1155 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
1156 DEBUG(dbgs() << "Won't speculate: " << MI);
1157 return false;
1158 }
1159
1160 // High register pressure situation, only hoist if the instruction is going
1161 // to be remat'ed.
Justin Lebard98cf002016-09-10 01:03:20 +00001162 if (!TII->isTriviallyReMaterializable(MI, AA) &&
1163 !MI.isDereferenceableInvariantLoad(AA)) {
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001164 DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
1165 return false;
1166 }
Evan Cheng399660c2009-02-05 08:45:46 +00001167
1168 return true;
1169}
1170
Sanjay Patel87c6c072015-12-10 16:34:21 +00001171/// Unfold a load from the given machineinstr if the load itself could be
1172/// hoisted. Return the unfolded and hoistable load, or null if the load
1173/// couldn't be unfolded or if it wouldn't be hoistable.
Dan Gohman104f57c2009-10-29 17:47:20 +00001174MachineInstr *MachineLICM::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001175 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001176 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001177 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001178
Dan Gohman104f57c2009-10-29 17:47:20 +00001179 // If not, we may be able to unfold a load and hoist that.
1180 // First test whether the instruction is loading from an amenable
1181 // memory location.
Justin Lebard98cf002016-09-10 01:03:20 +00001182 if (!MI->isDereferenceableInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001183 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001184
Dan Gohman104f57c2009-10-29 17:47:20 +00001185 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001186 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001187 unsigned NewOpc =
1188 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1189 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001190 /*UnfoldStore=*/false,
1191 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001192 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001193 const MCInstrDesc &MID = TII->get(NewOpc);
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001194 MachineFunction &MF = *MI->getMF();
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001195 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001196 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Chengd62719c2010-10-14 01:16:09 +00001197 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001198
Dan Gohman104f57c2009-10-29 17:47:20 +00001199 SmallVector<MachineInstr *, 2> NewMIs;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001200 bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1201 /*UnfoldLoad=*/true,
1202 /*UnfoldStore=*/false, NewMIs);
Dan Gohman104f57c2009-10-29 17:47:20 +00001203 (void)Success;
1204 assert(Success &&
1205 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1206 "succeeded!");
1207 assert(NewMIs.size() == 2 &&
1208 "Unfolded a load into multiple instructions!");
1209 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001210 MachineBasicBlock::iterator Pos = MI;
1211 MBB->insert(Pos, NewMIs[0]);
1212 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001213 // If unfolding produced a load that wasn't loop-invariant or profitable to
1214 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001215 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001216 NewMIs[0]->eraseFromParent();
1217 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001218 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001219 }
Evan Cheng87066f02010-10-20 22:03:58 +00001220
1221 // Update register pressure for the unfolded instruction.
1222 UpdateRegPressure(NewMIs[1]);
1223
Dan Gohman104f57c2009-10-29 17:47:20 +00001224 // Otherwise we successfully unfolded a load that we can hoist.
1225 MI->eraseFromParent();
1226 return NewMIs[0];
1227}
1228
Sanjay Patel87c6c072015-12-10 16:34:21 +00001229/// Initialize the CSE map with instructions that are in the current loop
1230/// preheader that may become duplicates of instructions that are hoisted
1231/// out of the loop.
Evan Chengf42b5af2009-11-03 21:40:02 +00001232void MachineLICM::InitCSEMap(MachineBasicBlock *BB) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001233 for (MachineInstr &MI : *BB)
1234 CSEMap[MI.getOpcode()].push_back(&MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001235}
1236
Sanjay Patel87c6c072015-12-10 16:34:21 +00001237/// Find an instruction amount PrevMIs that is a duplicate of MI.
1238/// Return this instruction if it's found.
Evan Cheng7ff83192009-11-07 03:52:02 +00001239const MachineInstr*
1240MachineLICM::LookForDuplicate(const MachineInstr *MI,
1241 std::vector<const MachineInstr*> &PrevMIs) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001242 for (const MachineInstr *PrevMI : PrevMIs)
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001243 if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001244 return PrevMI;
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001245
Craig Topperc0196b12014-04-14 00:51:57 +00001246 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001247}
1248
Sanjay Patel87c6c072015-12-10 16:34:21 +00001249/// Given a LICM'ed instruction, look for an instruction on the preheader that
1250/// computes the same value. If it's found, do a RAU on with the definition of
1251/// the existing instruction rather than hoisting the instruction to the
1252/// preheader.
Evan Cheng921152f2009-11-05 00:51:13 +00001253bool MachineLICM::EliminateCSE(MachineInstr *MI,
Eugene Zelenkof1933322017-09-22 23:46:57 +00001254 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001255 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1256 // the undef property onto uses.
1257 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001258 return false;
1259
1260 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
David Greene55cf95c2010-01-05 00:03:48 +00001261 DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001262
1263 // Replace virtual registers defined by MI by their counterparts defined
1264 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001265 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001266 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1267 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001268
1269 // Physical registers may not differ here.
1270 assert((!MO.isReg() || MO.getReg() == 0 ||
1271 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1272 MO.getReg() == Dup->getOperand(i).getReg()) &&
1273 "Instructions with different phys regs are not identical!");
1274
1275 if (MO.isReg() && MO.isDef() &&
Evan Chengaa563df2011-10-17 19:50:12 +00001276 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1277 Defs.push_back(i);
1278 }
1279
1280 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1281 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1282 unsigned Idx = Defs[i];
1283 unsigned Reg = MI->getOperand(Idx).getReg();
1284 unsigned DupReg = Dup->getOperand(Idx).getReg();
1285 OrigRCs.push_back(MRI->getRegClass(DupReg));
1286
1287 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1288 // Restore old RCs if more than one defs.
1289 for (unsigned j = 0; j != i; ++j)
1290 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1291 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001292 }
Evan Cheng921152f2009-11-05 00:51:13 +00001293 }
Evan Chengaa563df2011-10-17 19:50:12 +00001294
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001295 for (unsigned Idx : Defs) {
Evan Chengaa563df2011-10-17 19:50:12 +00001296 unsigned Reg = MI->getOperand(Idx).getReg();
1297 unsigned DupReg = Dup->getOperand(Idx).getReg();
1298 MRI->replaceRegWith(Reg, DupReg);
1299 MRI->clearKillFlags(DupReg);
1300 }
1301
Evan Cheng7ff83192009-11-07 03:52:02 +00001302 MI->eraseFromParent();
1303 ++NumCSEed;
1304 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001305 }
1306 return false;
1307}
1308
Sanjay Patel87c6c072015-12-10 16:34:21 +00001309/// Return true if the given instruction will be CSE'd if it's hoisted out of
1310/// the loop.
Evan Chengaf138952011-10-12 00:09:14 +00001311bool MachineLICM::MayCSE(MachineInstr *MI) {
1312 unsigned Opcode = MI->getOpcode();
Eugene Zelenkof1933322017-09-22 23:46:57 +00001313 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
Evan Chengaf138952011-10-12 00:09:14 +00001314 CI = CSEMap.find(Opcode);
1315 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1316 // the undef property onto uses.
1317 if (CI == CSEMap.end() || MI->isImplicitDef())
1318 return false;
1319
Craig Topperc0196b12014-04-14 00:51:57 +00001320 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001321}
1322
Sanjay Patel87c6c072015-12-10 16:34:21 +00001323/// When an instruction is found to use only loop invariant operands
Bill Wendling70613b82008-05-12 19:38:32 +00001324/// that are safe to hoist, this instruction is called to do the dirty work.
Sanjay Patel87c6c072015-12-10 16:34:21 +00001325/// It returns true if the instruction is hoisted.
Evan Cheng87066f02010-10-20 22:03:58 +00001326bool MachineLICM::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman1b44f102009-10-28 03:21:57 +00001327 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001328 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001329 // If not, try unfolding a hoistable load.
1330 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001331 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001332 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001333
Dan Gohman79618d12009-01-15 22:01:38 +00001334 // Now move the instructions to the predecessor, inserting it before any
1335 // terminator instructions.
1336 DEBUG({
David Greene55cf95c2010-01-05 00:03:48 +00001337 dbgs() << "Hoisting " << *MI;
Dan Gohman1b44f102009-10-28 03:21:57 +00001338 if (MI->getParent()->getBasicBlock())
Justin Lebarf6f4a2a2016-05-23 18:56:07 +00001339 dbgs() << " from BB#" << MI->getParent()->getNumber();
1340 if (Preheader->getBasicBlock())
1341 dbgs() << " to BB#" << Preheader->getNumber();
David Greene55cf95c2010-01-05 00:03:48 +00001342 dbgs() << "\n";
Dan Gohman79618d12009-01-15 22:01:38 +00001343 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001344
Evan Chengf42b5af2009-11-03 21:40:02 +00001345 // If this is the first instruction being hoisted to the preheader,
1346 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001347 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001348 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001349 FirstInLoop = false;
1350 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001351
Evan Cheng399660c2009-02-05 08:45:46 +00001352 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001353 unsigned Opcode = MI->getOpcode();
Eugene Zelenkof1933322017-09-22 23:46:57 +00001354 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
Evan Chengf42b5af2009-11-03 21:40:02 +00001355 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001356 if (!EliminateCSE(MI, CI)) {
1357 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001358 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001359
Wolfgang Pieb42f92a72016-12-02 00:37:57 +00001360 // Since we are moving the instruction out of its basic block, we do not
Michael Liaoa5d45372017-04-26 05:27:20 +00001361 // retain its debug location. Doing so would degrade the debugging
Wolfgang Pieb42f92a72016-12-02 00:37:57 +00001362 // experience and adversely affect the accuracy of profiling information.
1363 MI->setDebugLoc(DebugLoc());
1364
Evan Cheng87066f02010-10-20 22:03:58 +00001365 // Update register pressure for BBs from header to this block.
1366 UpdateBackTraceRegPressure(MI);
1367
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001368 // Clear the kill flags of any register this instruction defines,
1369 // since they may need to be live throughout the entire loop
1370 // rather than just live for part of it.
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001371 for (MachineOperand &MO : MI->operands())
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001372 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001373 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001374
Evan Cheng399660c2009-02-05 08:45:46 +00001375 // Add to the CSE map.
1376 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001377 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001378 else
1379 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001380 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001381
Dan Gohman79618d12009-01-15 22:01:38 +00001382 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001383 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001384
1385 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001386}
Dan Gohman3570f812010-06-22 17:25:57 +00001387
Sanjay Patel87c6c072015-12-10 16:34:21 +00001388/// Get the preheader for the current loop, splitting a critical edge if needed.
Dan Gohman3570f812010-06-22 17:25:57 +00001389MachineBasicBlock *MachineLICM::getCurPreheader() {
1390 // Determine the block to which to hoist instructions. If we can't find a
1391 // suitable loop predecessor, we can't do any hoisting.
1392
1393 // If we've tried to get a preheader and failed, don't try again.
1394 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001395 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001396
1397 if (!CurPreheader) {
1398 CurPreheader = CurLoop->getLoopPreheader();
1399 if (!CurPreheader) {
1400 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1401 if (!Pred) {
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
Quentin Colombet23341a82016-04-21 21:01:13 +00001406 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
Dan Gohman3570f812010-06-22 17:25:57 +00001407 if (!CurPreheader) {
1408 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001409 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001410 }
1411 }
1412 }
1413 return CurPreheader;
1414}