blob: 1107e609c2580deeec7b0484c3cde0aca561aae9 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Bill Wendlingfb706bc2007-12-07 21:42:31 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass performs loop invariant code motion on machine instructions. We
10// attempt to remove as much code from the body of a loop as possible.
11//
Dan Gohman79618d12009-01-15 22:01:38 +000012// This pass is not intended to be a replacement or a complete alternative
13// for the LLVM-IR-level LICM pass. It is only designed to hoist simple
14// constructs that are not exposed before lowering and instruction selection.
15//
Bill Wendlingfb706bc2007-12-07 21:42:31 +000016//===----------------------------------------------------------------------===//
17
Eugene Zelenkof1933322017-09-22 23:46:57 +000018#include "llvm/ADT/BitVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/DenseMap.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000020#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SmallSet.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000022#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/AliasAnalysis.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000025#include "llvm/CodeGen/MachineBasicBlock.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000026#include "llvm/CodeGen/MachineDominators.h"
Evan Cheng6ea59492010-04-07 00:41:17 +000027#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000028#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFunctionPass.h"
30#include "llvm/CodeGen/MachineInstr.h"
Bill Wendlingfb706bc2007-12-07 21:42:31 +000031#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000032#include "llvm/CodeGen/MachineMemOperand.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000033#include "llvm/CodeGen/MachineOperand.h"
Bill Wendling5da19452008-01-02 19:32:43 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman1b44f102009-10-28 03:21:57 +000035#include "llvm/CodeGen/PseudoSourceValue.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000036#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000037#include "llvm/CodeGen/TargetLowering.h"
38#include "llvm/CodeGen/TargetRegisterInfo.h"
Matthias Braun88e21312015-06-13 03:42:11 +000039#include "llvm/CodeGen/TargetSchedule.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000040#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000041#include "llvm/IR/DebugLoc.h"
42#include "llvm/MC/MCInstrDesc.h"
43#include "llvm/MC/MCRegisterInfo.h"
44#include "llvm/Pass.h"
45#include "llvm/Support/Casting.h"
Evan Chengb35afca2011-10-12 21:33:49 +000046#include "llvm/Support/CommandLine.h"
Chris Lattnerb5c1d9b2008-01-04 06:41:45 +000047#include "llvm/Support/Debug.h"
Daniel Dunbar0dd5e1e2009-07-25 00:23:56 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenkof1933322017-09-22 23:46:57 +000049#include <algorithm>
50#include <cassert>
51#include <limits>
52#include <vector>
53
Bill Wendlingfb706bc2007-12-07 21:42:31 +000054using namespace llvm;
55
Matthias Braun1527baa2017-05-25 21:26:32 +000056#define DEBUG_TYPE "machinelicm"
Chandler Carruth1b9dde02014-04-22 02:02:50 +000057
Evan Chengb35afca2011-10-12 21:33:49 +000058static cl::opt<bool>
59AvoidSpeculation("avoid-speculation",
60 cl::desc("MachineLICM should avoid speculation"),
Evan Cheng73133372011-10-26 01:26:57 +000061 cl::init(true), cl::Hidden);
Evan Chengb35afca2011-10-12 21:33:49 +000062
Hal Finkel0709f512015-01-08 22:10:48 +000063static cl::opt<bool>
64HoistCheapInsts("hoist-cheap-insts",
65 cl::desc("MachineLICM should hoist even cheap instructions"),
66 cl::init(false), cl::Hidden);
67
Daniel Jasper15e69542015-03-14 10:58:38 +000068static cl::opt<bool>
69SinkInstsToAvoidSpills("sink-insts-to-avoid-spills",
70 cl::desc("MachineLICM should sink instructions into "
71 "loops to avoid register spills"),
72 cl::init(false), cl::Hidden);
Zaara Syeda65359932018-03-23 15:28:15 +000073static cl::opt<bool>
74HoistConstStores("hoist-const-stores",
75 cl::desc("Hoist invariant stores"),
Zaara Syeda935474fe2018-04-09 14:50:02 +000076 cl::init(true), cl::Hidden);
Daniel Jasper15e69542015-03-14 10:58:38 +000077
Evan Cheng44436302010-10-16 02:20:26 +000078STATISTIC(NumHoisted,
79 "Number of machine instructions hoisted out of loops");
80STATISTIC(NumLowRP,
81 "Number of instructions hoisted in low reg pressure situation");
82STATISTIC(NumHighLatency,
83 "Number of high latency instructions hoisted");
84STATISTIC(NumCSEed,
85 "Number of hoisted machine instructions CSEed");
Evan Cheng6ea59492010-04-07 00:41:17 +000086STATISTIC(NumPostRAHoisted,
87 "Number of machine instructions hoisted out of loops post regalloc");
Zaara Syeda65359932018-03-23 15:28:15 +000088STATISTIC(NumStoreConst,
89 "Number of stores of const phys reg hoisted out of loops");
Bill Wendling43751732007-12-08 01:47:01 +000090
Bill Wendlingfb706bc2007-12-07 21:42:31 +000091namespace {
Eugene Zelenkof1933322017-09-22 23:46:57 +000092
Matthias Braun4a7c8e72018-01-19 06:46:10 +000093 class MachineLICMBase : public MachineFunctionPass {
Bill Wendling38236ef2007-12-11 23:27:51 +000094 const TargetInstrInfo *TII;
Benjamin Kramer56b31bd2013-01-11 20:05:37 +000095 const TargetLoweringBase *TLI;
Dan Gohmane30d63f2009-09-25 23:58:45 +000096 const TargetRegisterInfo *TRI;
Evan Cheng6ea59492010-04-07 00:41:17 +000097 const MachineFrameInfo *MFI;
Evan Chengd62719c2010-10-14 01:16:09 +000098 MachineRegisterInfo *MRI;
Matthias Braun88e21312015-06-13 03:42:11 +000099 TargetSchedModel SchedModel;
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000100 bool PreRegAlloc;
Bill Wendlingb678ae72007-12-11 19:40:06 +0000101
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000102 // Various analyses that we use...
Dan Gohmanbe8137b2009-10-07 17:38:06 +0000103 AliasAnalysis *AA; // Alias analysis info.
Evan Cheng058b9f02010-04-08 01:03:47 +0000104 MachineLoopInfo *MLI; // Current MachineLoopInfo
Bill Wendling70613b82008-05-12 19:38:32 +0000105 MachineDominatorTree *DT; // Machine dominator tree for the cur loop
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000106
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000107 // State that is updated as we process loops
Bill Wendling70613b82008-05-12 19:38:32 +0000108 bool Changed; // True if a loop is changed.
Evan Cheng032f3262010-05-29 00:06:36 +0000109 bool FirstInLoop; // True if it's the first LICM in the loop.
Bill Wendling70613b82008-05-12 19:38:32 +0000110 MachineLoop *CurLoop; // The current loop we are working on.
Dan Gohman79618d12009-01-15 22:01:38 +0000111 MachineBasicBlock *CurPreheader; // The preheader for CurLoop.
Evan Cheng399660c2009-02-05 08:45:46 +0000112
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000113 // Exit blocks for CurLoop.
Eugene Zelenkof1933322017-09-22 23:46:57 +0000114 SmallVector<MachineBasicBlock *, 8> ExitBlocks;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000115
116 bool isExitBlock(const MachineBasicBlock *MBB) const {
David Majnemer0d955d02016-08-11 22:21:41 +0000117 return is_contained(ExitBlocks, MBB);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000118 }
119
Evan Chengd62719c2010-10-14 01:16:09 +0000120 // Track 'estimated' register pressure.
Evan Cheng44436302010-10-16 02:20:26 +0000121 SmallSet<unsigned, 32> RegSeen;
Evan Chengd62719c2010-10-14 01:16:09 +0000122 SmallVector<unsigned, 8> RegPressure;
Evan Cheng44436302010-10-16 02:20:26 +0000123
Daniel Jasper274928f2015-04-14 11:56:25 +0000124 // Register pressure "limit" per register pressure set. If the pressure
Evan Cheng44436302010-10-16 02:20:26 +0000125 // is higher than the limit, then it's considered high.
Evan Chengd62719c2010-10-14 01:16:09 +0000126 SmallVector<unsigned, 8> RegLimit;
127
Evan Cheng44436302010-10-16 02:20:26 +0000128 // Register pressure on path leading from loop preheader to current BB.
129 SmallVector<SmallVector<unsigned, 8>, 16> BackTrace;
130
Dale Johannesen329d4742010-07-29 17:45:24 +0000131 // For each opcode, keep a list of potential CSE instructions.
Eugene Zelenkof1933322017-09-22 23:46:57 +0000132 DenseMap<unsigned, std::vector<const MachineInstr *>> CSEMap;
Evan Cheng6ea59492010-04-07 00:41:17 +0000133
Evan Chengf192ca02011-10-11 23:48:44 +0000134 enum {
135 SpeculateFalse = 0,
136 SpeculateTrue = 1,
137 SpeculateUnknown = 2
138 };
139
Devang Patel453d4012011-10-11 18:09:58 +0000140 // If a MBB does not dominate loop exiting blocks then it may not safe
141 // to hoist loads from this block.
Evan Chengf192ca02011-10-11 23:48:44 +0000142 // Tri-state: 0 - false, 1 - true, 2 - unknown
143 unsigned SpeculationState;
Devang Patel453d4012011-10-11 18:09:58 +0000144
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000145 public:
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000146 MachineLICMBase(char &PassID, bool PreRegAlloc)
147 : MachineFunctionPass(PassID), PreRegAlloc(PreRegAlloc) {}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000148
Craig Topper4584cd52014-03-07 09:26:03 +0000149 bool runOnMachineFunction(MachineFunction &MF) override;
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000150
Craig Topper4584cd52014-03-07 09:26:03 +0000151 void getAnalysisUsage(AnalysisUsage &AU) const override {
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000152 AU.addRequired<MachineLoopInfo>();
153 AU.addRequired<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000154 AU.addRequired<AAResultsWrapperPass>();
Bill Wendling3bf56032008-01-04 08:48:49 +0000155 AU.addPreserved<MachineLoopInfo>();
156 AU.addPreserved<MachineDominatorTree>();
157 MachineFunctionPass::getAnalysisUsage(AU);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000158 }
Evan Cheng399660c2009-02-05 08:45:46 +0000159
Craig Topper4584cd52014-03-07 09:26:03 +0000160 void releaseMemory() override {
Evan Cheng44436302010-10-16 02:20:26 +0000161 RegSeen.clear();
Evan Chengd62719c2010-10-14 01:16:09 +0000162 RegPressure.clear();
163 RegLimit.clear();
Evan Cheng63c76082010-10-19 18:58:51 +0000164 BackTrace.clear();
Evan Cheng399660c2009-02-05 08:45:46 +0000165 CSEMap.clear();
166 }
167
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000168 private:
Sanjay Patel87c6c072015-12-10 16:34:21 +0000169 /// Keep track of information about hoisting candidates.
Evan Cheng058b9f02010-04-08 01:03:47 +0000170 struct CandidateInfo {
171 MachineInstr *MI;
Evan Cheng058b9f02010-04-08 01:03:47 +0000172 unsigned Def;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000173 int FI;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000174
Evan Cheng0a2aff22010-04-13 18:16:00 +0000175 CandidateInfo(MachineInstr *mi, unsigned def, int fi)
176 : MI(mi), Def(def), FI(fi) {}
Evan Cheng058b9f02010-04-08 01:03:47 +0000177 };
178
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000179 void HoistRegionPostRA();
Evan Cheng058b9f02010-04-08 01:03:47 +0000180
Evan Cheng058b9f02010-04-08 01:03:47 +0000181 void HoistPostRA(MachineInstr *MI, unsigned Def);
182
Sanjay Patel87c6c072015-12-10 16:34:21 +0000183 void ProcessMI(MachineInstr *MI, BitVector &PhysRegDefs,
184 BitVector &PhysRegClobbers, SmallSet<int, 32> &StoredFIs,
Craig Topper2cd5ff82013-07-11 16:22:38 +0000185 SmallVectorImpl<CandidateInfo> &Candidates);
Evan Cheng058b9f02010-04-08 01:03:47 +0000186
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000187 void AddToLiveIns(unsigned Reg);
Evan Cheng058b9f02010-04-08 01:03:47 +0000188
Evan Cheng0a2aff22010-04-13 18:16:00 +0000189 bool IsLICMCandidate(MachineInstr &I);
190
Bill Wendling3f19dfe72007-12-08 23:58:46 +0000191 bool IsLoopInvariantInst(MachineInstr &I);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000192
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000193 bool HasLoopPHIUse(const MachineInstr *MI) const;
Evan Chengef42bea2011-04-11 21:09:18 +0000194
Evan Chenge96b8d72010-10-26 02:08:50 +0000195 bool HasHighOperandLatency(MachineInstr &MI, unsigned DefIdx,
196 unsigned Reg) const;
197
198 bool IsCheapInstruction(MachineInstr &MI) const;
Evan Chengd62719c2010-10-14 01:16:09 +0000199
Daniel Jasperefece522015-04-03 16:19:48 +0000200 bool CanCauseHighRegPressure(const DenseMap<unsigned, int> &Cost,
201 bool Cheap);
Evan Cheng87066f02010-10-20 22:03:58 +0000202
Evan Cheng87066f02010-10-20 22:03:58 +0000203 void UpdateBackTraceRegPressure(const MachineInstr *MI);
Evan Cheng44436302010-10-16 02:20:26 +0000204
Evan Cheng73f9a9e2009-11-20 23:31:34 +0000205 bool IsProfitableToHoist(MachineInstr &MI);
Evan Cheng1d9f7ac2009-02-04 09:19:56 +0000206
Devang Patel453d4012011-10-11 18:09:58 +0000207 bool IsGuaranteedToExecute(MachineBasicBlock *BB);
208
Pete Cooper1eed5b52011-12-22 02:05:40 +0000209 void EnterScope(MachineBasicBlock *MBB);
210
211 void ExitScope(MachineBasicBlock *MBB);
212
Sanjay Patel87c6c072015-12-10 16:34:21 +0000213 void ExitScopeIfDone(
214 MachineDomTreeNode *Node,
215 DenseMap<MachineDomTreeNode *, unsigned> &OpenChildren,
216 DenseMap<MachineDomTreeNode *, MachineDomTreeNode *> &ParentMap);
Pete Cooper1eed5b52011-12-22 02:05:40 +0000217
Fangrui Songcb0bab82018-07-16 18:51:40 +0000218 void HoistOutOfLoop(MachineDomTreeNode *HeaderN);
Sanjay Patel87c6c072015-12-10 16:34:21 +0000219
Pete Cooper1eed5b52011-12-22 02:05:40 +0000220 void HoistRegion(MachineDomTreeNode *N, bool IsHeader);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000221
Daniel Jasper15e69542015-03-14 10:58:38 +0000222 void SinkIntoLoop();
223
Evan Chengd62719c2010-10-14 01:16:09 +0000224 void InitRegPressure(MachineBasicBlock *BB);
225
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000226 DenseMap<unsigned, int> calcRegisterCost(const MachineInstr *MI,
227 bool ConsiderSeen,
228 bool ConsiderUnseenAsDef);
229
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000230 void UpdateRegPressure(const MachineInstr *MI,
231 bool ConsiderUnseenAsDef = false);
Evan Chengd62719c2010-10-14 01:16:09 +0000232
Dan Gohman104f57c2009-10-29 17:47:20 +0000233 MachineInstr *ExtractHoistableLoad(MachineInstr *MI);
234
Sanjay Patel87c6c072015-12-10 16:34:21 +0000235 const MachineInstr *
236 LookForDuplicate(const MachineInstr *MI,
237 std::vector<const MachineInstr *> &PrevMIs);
Evan Cheng7ff83192009-11-07 03:52:02 +0000238
Sanjay Patel87c6c072015-12-10 16:34:21 +0000239 bool EliminateCSE(
240 MachineInstr *MI,
241 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI);
Evan Cheng921152f2009-11-05 00:51:13 +0000242
Evan Chengaf138952011-10-12 00:09:14 +0000243 bool MayCSE(MachineInstr *MI);
244
Evan Cheng87066f02010-10-20 22:03:58 +0000245 bool Hoist(MachineInstr *MI, MachineBasicBlock *Preheader);
Evan Chengf42b5af2009-11-03 21:40:02 +0000246
Evan Chengf42b5af2009-11-03 21:40:02 +0000247 void InitCSEMap(MachineBasicBlock *BB);
Dan Gohman3570f812010-06-22 17:25:57 +0000248
Dan Gohman3570f812010-06-22 17:25:57 +0000249 MachineBasicBlock *getCurPreheader();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000250 };
Eugene Zelenkof1933322017-09-22 23:46:57 +0000251
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000252 class MachineLICM : public MachineLICMBase {
253 public:
254 static char ID;
255 MachineLICM() : MachineLICMBase(ID, false) {
256 initializeMachineLICMPass(*PassRegistry::getPassRegistry());
257 }
258 };
259
260 class EarlyMachineLICM : public MachineLICMBase {
261 public:
262 static char ID;
263 EarlyMachineLICM() : MachineLICMBase(ID, true) {
264 initializeEarlyMachineLICMPass(*PassRegistry::getPassRegistry());
265 }
266 };
267
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000268} // end anonymous namespace
269
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000270char MachineLICM::ID;
271char EarlyMachineLICM::ID;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000272
Andrew Trick1fa5bcb2012-02-08 21:23:13 +0000273char &llvm::MachineLICMID = MachineLICM::ID;
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000274char &llvm::EarlyMachineLICMID = EarlyMachineLICM::ID;
Eugene Zelenkof1933322017-09-22 23:46:57 +0000275
Matthias Braun1527baa2017-05-25 21:26:32 +0000276INITIALIZE_PASS_BEGIN(MachineLICM, DEBUG_TYPE,
277 "Machine Loop Invariant Code Motion", false, false)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000278INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
279INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000280INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000281INITIALIZE_PASS_END(MachineLICM, DEBUG_TYPE,
282 "Machine Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000283
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000284INITIALIZE_PASS_BEGIN(EarlyMachineLICM, "early-machinelicm",
285 "Early Machine Loop Invariant Code Motion", false, false)
286INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
287INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
288INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
289INITIALIZE_PASS_END(EarlyMachineLICM, "early-machinelicm",
290 "Early Machine Loop Invariant Code Motion", false, false)
291
Sanjay Patel87c6c072015-12-10 16:34:21 +0000292/// Test if the given loop is the outer-most loop that has a unique predecessor.
Dan Gohman3570f812010-06-22 17:25:57 +0000293static bool LoopIsOuterMostWithPredecessor(MachineLoop *CurLoop) {
Dan Gohman7929c442010-07-09 18:49:45 +0000294 // Check whether this loop even has a unique predecessor.
295 if (!CurLoop->getLoopPredecessor())
296 return false;
297 // Ok, now check to see if any of its outer loops do.
Dan Gohman79618d12009-01-15 22:01:38 +0000298 for (MachineLoop *L = CurLoop->getParentLoop(); L; L = L->getParentLoop())
Dan Gohman3570f812010-06-22 17:25:57 +0000299 if (L->getLoopPredecessor())
Dan Gohman79618d12009-01-15 22:01:38 +0000300 return false;
Dan Gohman7929c442010-07-09 18:49:45 +0000301 // None of them did, so this is the outermost with a unique predecessor.
Dan Gohman79618d12009-01-15 22:01:38 +0000302 return true;
303}
304
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000305bool MachineLICMBase::runOnMachineFunction(MachineFunction &MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +0000306 if (skipFunction(MF.getFunction()))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000307 return false;
308
Evan Cheng032f3262010-05-29 00:06:36 +0000309 Changed = FirstInLoop = false;
Matthias Braun88e21312015-06-13 03:42:11 +0000310 const TargetSubtargetInfo &ST = MF.getSubtarget();
311 TII = ST.getInstrInfo();
312 TLI = ST.getTargetLowering();
313 TRI = ST.getRegisterInfo();
Matthias Braun941a7052016-07-28 18:40:00 +0000314 MFI = &MF.getFrameInfo();
Evan Chengd62719c2010-10-14 01:16:09 +0000315 MRI = &MF.getRegInfo();
Sanjay Patel0d7df362018-04-08 19:56:04 +0000316 SchedModel.init(&ST);
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000317
Andrew Trickc40815d2012-02-08 21:23:03 +0000318 PreRegAlloc = MRI->isSSA();
319
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000320 if (PreRegAlloc)
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000321 LLVM_DEBUG(dbgs() << "******** Pre-regalloc Machine LICM: ");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000322 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000323 LLVM_DEBUG(dbgs() << "******** Post-regalloc Machine LICM: ");
324 LLVM_DEBUG(dbgs() << MF.getName() << " ********\n");
Jakob Stoklund Olesenc8046c02012-02-11 00:40:36 +0000325
Evan Chengd62719c2010-10-14 01:16:09 +0000326 if (PreRegAlloc) {
327 // Estimate register pressure during pre-regalloc pass.
Daniel Jasper274928f2015-04-14 11:56:25 +0000328 unsigned NumRPS = TRI->getNumRegPressureSets();
329 RegPressure.resize(NumRPS);
Evan Chengd62719c2010-10-14 01:16:09 +0000330 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Daniel Jasper274928f2015-04-14 11:56:25 +0000331 RegLimit.resize(NumRPS);
332 for (unsigned i = 0, e = NumRPS; i != e; ++i)
333 RegLimit[i] = TRI->getRegPressureSetLimit(MF, i);
Evan Chengd62719c2010-10-14 01:16:09 +0000334 }
335
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000336 // Get our Loop information...
Evan Cheng058b9f02010-04-08 01:03:47 +0000337 MLI = &getAnalysis<MachineLoopInfo>();
338 DT = &getAnalysis<MachineDominatorTree>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000339 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000340
Dan Gohman7929c442010-07-09 18:49:45 +0000341 SmallVector<MachineLoop *, 8> Worklist(MLI->begin(), MLI->end());
342 while (!Worklist.empty()) {
343 CurLoop = Worklist.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000344 CurPreheader = nullptr;
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000345 ExitBlocks.clear();
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000346
Evan Cheng058b9f02010-04-08 01:03:47 +0000347 // If this is done before regalloc, only visit outer-most preheader-sporting
348 // loops.
Dan Gohman7929c442010-07-09 18:49:45 +0000349 if (PreRegAlloc && !LoopIsOuterMostWithPredecessor(CurLoop)) {
350 Worklist.append(CurLoop->begin(), CurLoop->end());
Dan Gohman79618d12009-01-15 22:01:38 +0000351 continue;
Dan Gohman7929c442010-07-09 18:49:45 +0000352 }
Dan Gohman79618d12009-01-15 22:01:38 +0000353
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +0000354 CurLoop->getExitBlocks(ExitBlocks);
355
Evan Cheng6ea59492010-04-07 00:41:17 +0000356 if (!PreRegAlloc)
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000357 HoistRegionPostRA();
Evan Cheng6ea59492010-04-07 00:41:17 +0000358 else {
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000359 // CSEMap is initialized for loop header when the first instruction is
360 // being hoisted.
361 MachineDomTreeNode *N = DT->getNode(CurLoop->getHeader());
Evan Cheng032f3262010-05-29 00:06:36 +0000362 FirstInLoop = true;
Pete Cooper1eed5b52011-12-22 02:05:40 +0000363 HoistOutOfLoop(N);
Evan Cheng6ea59492010-04-07 00:41:17 +0000364 CSEMap.clear();
Daniel Jasper15e69542015-03-14 10:58:38 +0000365
366 if (SinkInstsToAvoidSpills)
367 SinkIntoLoop();
Evan Cheng6ea59492010-04-07 00:41:17 +0000368 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000369 }
370
371 return Changed;
372}
373
Sanjay Patel87c6c072015-12-10 16:34:21 +0000374/// Return true if instruction stores to the specified frame.
Evan Cheng058b9f02010-04-08 01:03:47 +0000375static bool InstructionStoresToFI(const MachineInstr *MI, int FI) {
Geoff Berry8e4958e2018-05-04 19:25:09 +0000376 // Check mayStore before memory operands so that e.g. DBG_VALUEs will return
377 // true since they have no memory operands.
378 if (!MI->mayStore())
379 return false;
Philip Reames42bd26f2015-12-23 17:05:57 +0000380 // If we lost memory operands, conservatively assume that the instruction
Michael Liaoa5d45372017-04-26 05:27:20 +0000381 // writes to all slots.
Philip Reames42bd26f2015-12-23 17:05:57 +0000382 if (MI->memoperands_empty())
383 return true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000384 for (const MachineMemOperand *MemOp : MI->memoperands()) {
385 if (!MemOp->isStore() || !MemOp->getPseudoValue())
Evan Cheng058b9f02010-04-08 01:03:47 +0000386 continue;
387 if (const FixedStackPseudoSourceValue *Value =
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000388 dyn_cast<FixedStackPseudoSourceValue>(MemOp->getPseudoValue())) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000389 if (Value->getFrameIndex() == FI)
390 return true;
391 }
392 }
393 return false;
394}
395
Sanjay Patel87c6c072015-12-10 16:34:21 +0000396/// Examine the instruction for potentai LICM candidate. Also
Evan Cheng058b9f02010-04-08 01:03:47 +0000397/// gather register def and frame object update information.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000398void MachineLICMBase::ProcessMI(MachineInstr *MI,
399 BitVector &PhysRegDefs,
400 BitVector &PhysRegClobbers,
401 SmallSet<int, 32> &StoredFIs,
402 SmallVectorImpl<CandidateInfo> &Candidates) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000403 bool RuledOut = false;
Evan Cheng89e74792010-04-13 20:21:05 +0000404 bool HasNonInvariantUse = false;
Evan Cheng058b9f02010-04-08 01:03:47 +0000405 unsigned Def = 0;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000406 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng058b9f02010-04-08 01:03:47 +0000407 if (MO.isFI()) {
408 // Remember if the instruction stores to the frame index.
409 int FI = MO.getIndex();
410 if (!StoredFIs.count(FI) &&
411 MFI->isSpillSlotObjectIndex(FI) &&
412 InstructionStoresToFI(MI, FI))
413 StoredFIs.insert(FI);
Evan Cheng89e74792010-04-13 20:21:05 +0000414 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000415 continue;
416 }
417
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000418 // We can't hoist an instruction defining a physreg that is clobbered in
419 // the loop.
420 if (MO.isRegMask()) {
Jakob Stoklund Olesen5e1ac452012-02-02 23:52:57 +0000421 PhysRegClobbers.setBitsNotInMask(MO.getRegMask());
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000422 continue;
423 }
424
Evan Cheng058b9f02010-04-08 01:03:47 +0000425 if (!MO.isReg())
426 continue;
427 unsigned Reg = MO.getReg();
428 if (!Reg)
429 continue;
430 assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
431 "Not expecting virtual register!");
432
Evan Cheng0a2aff22010-04-13 18:16:00 +0000433 if (!MO.isDef()) {
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000434 if (Reg && (PhysRegDefs.test(Reg) || PhysRegClobbers.test(Reg)))
Evan Cheng89e74792010-04-13 20:21:05 +0000435 // If it's using a non-loop-invariant register, then it's obviously not
436 // safe to hoist.
437 HasNonInvariantUse = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000438 continue;
Evan Cheng0a2aff22010-04-13 18:16:00 +0000439 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000440
441 if (MO.isImplicit()) {
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000442 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
443 PhysRegClobbers.set(*AI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000444 if (!MO.isDead())
445 // Non-dead implicit def? This cannot be hoisted.
446 RuledOut = true;
447 // No need to check if a dead implicit def is also defined by
448 // another instruction.
449 continue;
450 }
451
452 // FIXME: For now, avoid instructions with multiple defs, unless
453 // it's a dead implicit def.
454 if (Def)
455 RuledOut = true;
456 else
457 Def = Reg;
458
459 // If we have already seen another instruction that defines the same
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000460 // register, then this is not safe. Two defs is indicated by setting a
461 // PhysRegClobbers bit.
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000462 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS) {
Jakob Stoklund Olesen20948fa2012-01-23 21:01:15 +0000463 if (PhysRegDefs.test(*AS))
464 PhysRegClobbers.set(*AS);
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000465 }
Craig Topper69342022018-12-05 03:41:26 +0000466 // Need a second loop because MCRegAliasIterator can visit the same
467 // register twice.
468 for (MCRegAliasIterator AS(Reg, TRI, true); AS.isValid(); ++AS)
469 PhysRegDefs.set(*AS);
470
Richard Sandiford96aa93d2013-08-20 09:11:13 +0000471 if (PhysRegClobbers.test(Reg))
472 // MI defined register is seen defined by another instruction in
473 // the loop, it cannot be a LICM candidate.
474 RuledOut = true;
Evan Cheng058b9f02010-04-08 01:03:47 +0000475 }
476
Evan Cheng0a2aff22010-04-13 18:16:00 +0000477 // Only consider reloads for now and remats which do not have register
478 // operands. FIXME: Consider unfold load folding instructions.
Evan Cheng058b9f02010-04-08 01:03:47 +0000479 if (Def && !RuledOut) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000480 int FI = std::numeric_limits<int>::min();
Evan Cheng89e74792010-04-13 20:21:05 +0000481 if ((!HasNonInvariantUse && IsLICMCandidate(*MI)) ||
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000482 (TII->isLoadFromStackSlot(*MI, FI) && MFI->isSpillSlotObjectIndex(FI)))
Evan Cheng0a2aff22010-04-13 18:16:00 +0000483 Candidates.push_back(CandidateInfo(MI, Def, FI));
Evan Cheng058b9f02010-04-08 01:03:47 +0000484 }
485}
486
Sanjay Patel87c6c072015-12-10 16:34:21 +0000487/// Walk the specified region of the CFG and hoist loop invariants out to the
488/// preheader.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000489void MachineLICMBase::HoistRegionPostRA() {
Evan Cheng7fede872012-03-27 01:50:58 +0000490 MachineBasicBlock *Preheader = getCurPreheader();
491 if (!Preheader)
492 return;
493
Evan Cheng6ea59492010-04-07 00:41:17 +0000494 unsigned NumRegs = TRI->getNumRegs();
Jakob Stoklund Olesen6b17ef52012-01-20 22:27:12 +0000495 BitVector PhysRegDefs(NumRegs); // Regs defined once in the loop.
496 BitVector PhysRegClobbers(NumRegs); // Regs defined more than once.
Evan Cheng6ea59492010-04-07 00:41:17 +0000497
Evan Cheng058b9f02010-04-08 01:03:47 +0000498 SmallVector<CandidateInfo, 32> Candidates;
Evan Cheng6ea59492010-04-07 00:41:17 +0000499 SmallSet<int, 32> StoredFIs;
500
501 // Walk the entire region, count number of defs for each register, and
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000502 // collect potential LICM candidates.
Benjamin Kramer28559a22018-09-10 12:32:06 +0000503 for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
Bill Wendling918cea22011-10-12 02:58:01 +0000504 // If the header of the loop containing this basic block is a landing pad,
505 // then don't try to hoist instructions out of this loop.
506 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000507 if (ML && ML->getHeader()->isEHPad()) continue;
Bill Wendling918cea22011-10-12 02:58:01 +0000508
Evan Cheng6ea59492010-04-07 00:41:17 +0000509 // Conservatively treat live-in's as an external def.
Evan Cheng058b9f02010-04-08 01:03:47 +0000510 // FIXME: That means a reload that're reused in successor block(s) will not
511 // be LICM'ed.
Matthias Braund9da1622015-09-09 18:08:03 +0000512 for (const auto &LI : BB->liveins()) {
513 for (MCRegAliasIterator AI(LI.PhysReg, TRI, true); AI.isValid(); ++AI)
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000514 PhysRegDefs.set(*AI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000515 }
516
Evan Chengf192ca02011-10-11 23:48:44 +0000517 SpeculationState = SpeculateUnknown;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000518 for (MachineInstr &MI : *BB)
519 ProcessMI(&MI, PhysRegDefs, PhysRegClobbers, StoredFIs, Candidates);
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000520 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000521
Evan Cheng7fede872012-03-27 01:50:58 +0000522 // Gather the registers read / clobbered by the terminator.
523 BitVector TermRegs(NumRegs);
524 MachineBasicBlock::iterator TI = Preheader->getFirstTerminator();
525 if (TI != Preheader->end()) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000526 for (const MachineOperand &MO : TI->operands()) {
Evan Cheng7fede872012-03-27 01:50:58 +0000527 if (!MO.isReg())
528 continue;
529 unsigned Reg = MO.getReg();
530 if (!Reg)
531 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000532 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
533 TermRegs.set(*AI);
Evan Cheng7fede872012-03-27 01:50:58 +0000534 }
535 }
536
Evan Cheng6ea59492010-04-07 00:41:17 +0000537 // Now evaluate whether the potential candidates qualify.
538 // 1. Check if the candidate defined register is defined by another
539 // instruction in the loop.
540 // 2. If the candidate is a load from stack slot (always true for now),
541 // check if the slot is stored anywhere in the loop.
Evan Cheng7fede872012-03-27 01:50:58 +0000542 // 3. Make sure candidate def should not clobber
543 // registers read by the terminator. Similarly its def should not be
544 // clobbered by the terminator.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000545 for (CandidateInfo &Candidate : Candidates) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000546 if (Candidate.FI != std::numeric_limits<int>::min() &&
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000547 StoredFIs.count(Candidate.FI))
Evan Cheng6ea59492010-04-07 00:41:17 +0000548 continue;
549
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000550 unsigned Def = Candidate.Def;
Evan Cheng7fede872012-03-27 01:50:58 +0000551 if (!PhysRegClobbers.test(Def) && !TermRegs.test(Def)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000552 bool Safe = true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000553 MachineInstr *MI = Candidate.MI;
554 for (const MachineOperand &MO : MI->operands()) {
Evan Cheng87585d72010-04-13 22:13:34 +0000555 if (!MO.isReg() || MO.isDef() || !MO.getReg())
Evan Cheng89e74792010-04-13 20:21:05 +0000556 continue;
Evan Cheng7fede872012-03-27 01:50:58 +0000557 unsigned Reg = MO.getReg();
558 if (PhysRegDefs.test(Reg) ||
559 PhysRegClobbers.test(Reg)) {
Evan Cheng89e74792010-04-13 20:21:05 +0000560 // If it's using a non-loop-invariant register, then it's obviously
561 // not safe to hoist.
562 Safe = false;
563 break;
564 }
565 }
566 if (Safe)
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000567 HoistPostRA(MI, Candidate.Def);
Evan Cheng89e74792010-04-13 20:21:05 +0000568 }
Evan Cheng6ea59492010-04-07 00:41:17 +0000569 }
570}
571
Sanjay Patel87c6c072015-12-10 16:34:21 +0000572/// Add register 'Reg' to the livein sets of BBs in the current loop, and make
573/// sure it is not killed by any instructions in the loop.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000574void MachineLICMBase::AddToLiveIns(unsigned Reg) {
Benjamin Kramer28559a22018-09-10 12:32:06 +0000575 for (MachineBasicBlock *BB : CurLoop->getBlocks()) {
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000576 if (!BB->isLiveIn(Reg))
577 BB->addLiveIn(Reg);
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000578 for (MachineInstr &MI : *BB) {
579 for (MachineOperand &MO : MI.operands()) {
Jakob Stoklund Olesen011207a2010-04-20 18:45:47 +0000580 if (!MO.isReg() || !MO.getReg() || MO.isDef()) continue;
581 if (MO.getReg() == Reg || TRI->isSuperRegister(Reg, MO.getReg()))
582 MO.setIsKill(false);
583 }
584 }
585 }
Evan Cheng058b9f02010-04-08 01:03:47 +0000586}
587
Sanjay Patel87c6c072015-12-10 16:34:21 +0000588/// When an instruction is found to only use loop invariant operands that is
589/// safe to hoist, this instruction is called to do the dirty work.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000590void MachineLICMBase::HoistPostRA(MachineInstr *MI, unsigned Def) {
Dan Gohman3570f812010-06-22 17:25:57 +0000591 MachineBasicBlock *Preheader = getCurPreheader();
Dan Gohman3570f812010-06-22 17:25:57 +0000592
Evan Cheng6ea59492010-04-07 00:41:17 +0000593 // Now move the instructions to the predecessor, inserting it before any
594 // terminator instructions.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000595 LLVM_DEBUG(dbgs() << "Hoisting to " << printMBBReference(*Preheader)
596 << " from " << printMBBReference(*MI->getParent()) << ": "
597 << *MI);
Evan Cheng6ea59492010-04-07 00:41:17 +0000598
599 // Splice the instruction to the preheader.
Evan Cheng058b9f02010-04-08 01:03:47 +0000600 MachineBasicBlock *MBB = MI->getParent();
Dan Gohman3570f812010-06-22 17:25:57 +0000601 Preheader->splice(Preheader->getFirstTerminator(), MBB, MI);
Evan Cheng058b9f02010-04-08 01:03:47 +0000602
Andrew Trick5209c732012-02-08 21:23:00 +0000603 // Add register to livein list to all the BBs in the current loop since a
Evan Cheng5fdb57c2010-04-17 07:07:11 +0000604 // loop invariant must be kept live throughout the whole loop. This is
605 // important to ensure later passes do not scavenge the def register.
606 AddToLiveIns(Def);
Evan Cheng6ea59492010-04-07 00:41:17 +0000607
608 ++NumPostRAHoisted;
609 Changed = true;
610}
611
Sanjay Patel87c6c072015-12-10 16:34:21 +0000612/// Check if this mbb is guaranteed to execute. If not then a load from this mbb
613/// may not be safe to hoist.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000614bool MachineLICMBase::IsGuaranteedToExecute(MachineBasicBlock *BB) {
Evan Chengf192ca02011-10-11 23:48:44 +0000615 if (SpeculationState != SpeculateUnknown)
616 return SpeculationState == SpeculateFalse;
Andrew Trick5209c732012-02-08 21:23:00 +0000617
Devang Patel453d4012011-10-11 18:09:58 +0000618 if (BB != CurLoop->getHeader()) {
619 // Check loop exiting blocks.
620 SmallVector<MachineBasicBlock*, 8> CurrentLoopExitingBlocks;
621 CurLoop->getExitingBlocks(CurrentLoopExitingBlocks);
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000622 for (MachineBasicBlock *CurrentLoopExitingBlock : CurrentLoopExitingBlocks)
623 if (!DT->dominates(BB, CurrentLoopExitingBlock)) {
Nick Lewycky404feb92011-10-13 01:09:50 +0000624 SpeculationState = SpeculateTrue;
625 return false;
Devang Patel453d4012011-10-11 18:09:58 +0000626 }
627 }
628
Evan Chengf192ca02011-10-11 23:48:44 +0000629 SpeculationState = SpeculateFalse;
630 return true;
Devang Patel453d4012011-10-11 18:09:58 +0000631}
632
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000633void MachineLICMBase::EnterScope(MachineBasicBlock *MBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000634 LLVM_DEBUG(dbgs() << "Entering " << printMBBReference(*MBB) << '\n');
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000635
Pete Cooper1eed5b52011-12-22 02:05:40 +0000636 // Remember livein register pressure.
637 BackTrace.push_back(RegPressure);
638}
Bill Wendling918cea22011-10-12 02:58:01 +0000639
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000640void MachineLICMBase::ExitScope(MachineBasicBlock *MBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000641 LLVM_DEBUG(dbgs() << "Exiting " << printMBBReference(*MBB) << '\n');
Pete Cooper1eed5b52011-12-22 02:05:40 +0000642 BackTrace.pop_back();
643}
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000644
Sanjay Patel87c6c072015-12-10 16:34:21 +0000645/// Destroy scope for the MBB that corresponds to the given dominator tree node
646/// if its a leaf or all of its children are done. Walk up the dominator tree to
647/// destroy ancestors which are now done.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000648void MachineLICMBase::ExitScopeIfDone(MachineDomTreeNode *Node,
649 DenseMap<MachineDomTreeNode*, unsigned> &OpenChildren,
650 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> &ParentMap) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000651 if (OpenChildren[Node])
Evan Cheng44436302010-10-16 02:20:26 +0000652 return;
Evan Chengd62719c2010-10-14 01:16:09 +0000653
Pete Cooper1eed5b52011-12-22 02:05:40 +0000654 // Pop scope.
655 ExitScope(Node->getBlock());
656
657 // Now traverse upwards to pop ancestors whose offsprings are all done.
658 while (MachineDomTreeNode *Parent = ParentMap[Node]) {
659 unsigned Left = --OpenChildren[Parent];
660 if (Left != 0)
661 break;
662 ExitScope(Parent->getBlock());
663 Node = Parent;
664 }
665}
666
Sanjay Patel87c6c072015-12-10 16:34:21 +0000667/// Walk the specified loop in the CFG (defined by all blocks dominated by the
668/// specified header block, and that are in the current loop) in depth first
669/// order w.r.t the DominatorTree. This allows us to visit definitions before
670/// uses, allowing us to hoist a loop body in one pass without iteration.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000671void MachineLICMBase::HoistOutOfLoop(MachineDomTreeNode *HeaderN) {
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000672 MachineBasicBlock *Preheader = getCurPreheader();
673 if (!Preheader)
674 return;
675
Pete Cooper1eed5b52011-12-22 02:05:40 +0000676 SmallVector<MachineDomTreeNode*, 32> Scopes;
677 SmallVector<MachineDomTreeNode*, 8> WorkList;
678 DenseMap<MachineDomTreeNode*, MachineDomTreeNode*> ParentMap;
679 DenseMap<MachineDomTreeNode*, unsigned> OpenChildren;
680
681 // Perform a DFS walk to determine the order of visit.
682 WorkList.push_back(HeaderN);
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000683 while (!WorkList.empty()) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000684 MachineDomTreeNode *Node = WorkList.pop_back_val();
Craig Topperc0196b12014-04-14 00:51:57 +0000685 assert(Node && "Null dominator tree node?");
Pete Cooper1eed5b52011-12-22 02:05:40 +0000686 MachineBasicBlock *BB = Node->getBlock();
687
688 // If the header of the loop containing this basic block is a landing pad,
689 // then don't try to hoist instructions out of this loop.
690 const MachineLoop *ML = MLI->getLoopFor(BB);
Reid Kleckner0e288232015-08-27 23:27:47 +0000691 if (ML && ML->getHeader()->isEHPad())
Pete Cooper1eed5b52011-12-22 02:05:40 +0000692 continue;
693
694 // If this subregion is not in the top level loop at all, exit.
695 if (!CurLoop->contains(BB))
696 continue;
697
698 Scopes.push_back(Node);
699 const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
700 unsigned NumChildren = Children.size();
701
702 // Don't hoist things out of a large switch statement. This often causes
703 // code to be hoisted that wasn't going to be executed, and increases
704 // register pressure in a situation where it's likely to matter.
705 if (BB->succ_size() >= 25)
706 NumChildren = 0;
707
708 OpenChildren[Node] = NumChildren;
709 // Add children in reverse order as then the next popped worklist node is
710 // the first child of this node. This means we ultimately traverse the
711 // DOM tree in exactly the same order as if we'd recursed.
712 for (int i = (int)NumChildren-1; i >= 0; --i) {
713 MachineDomTreeNode *Child = Children[i];
714 ParentMap[Child] = Node;
715 WorkList.push_back(Child);
716 }
Daniel Dunbar418204e2010-10-19 17:14:24 +0000717 }
Evan Cheng8249dfe2010-10-19 00:55:07 +0000718
Daniel Jasper4bb224d2015-02-05 22:39:46 +0000719 if (Scopes.size() == 0)
720 return;
721
722 // Compute registers which are livein into the loop headers.
723 RegSeen.clear();
724 BackTrace.clear();
725 InitRegPressure(Preheader);
726
Pete Cooper1eed5b52011-12-22 02:05:40 +0000727 // Now perform LICM.
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000728 for (MachineDomTreeNode *Node : Scopes) {
Pete Cooper1eed5b52011-12-22 02:05:40 +0000729 MachineBasicBlock *MBB = Node->getBlock();
Evan Cheng63c76082010-10-19 18:58:51 +0000730
Pete Cooper1eed5b52011-12-22 02:05:40 +0000731 EnterScope(MBB);
732
733 // Process the block
734 SpeculationState = SpeculateUnknown;
735 for (MachineBasicBlock::iterator
736 MII = MBB->begin(), E = MBB->end(); MII != E; ) {
737 MachineBasicBlock::iterator NextMII = MII; ++NextMII;
738 MachineInstr *MI = &*MII;
739 if (!Hoist(MI, Preheader))
740 UpdateRegPressure(MI);
Zaara Syeda65359932018-03-23 15:28:15 +0000741 // If we have hoisted an instruction that may store, it can only be a
742 // constant store.
Pete Cooper1eed5b52011-12-22 02:05:40 +0000743 MII = NextMII;
744 }
745
746 // If it's a leaf node, it's done. Traverse upwards to pop ancestors.
747 ExitScopeIfDone(Node, OpenChildren, ParentMap);
Dan Gohman79618d12009-01-15 22:01:38 +0000748 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +0000749}
750
Sanjay Patel87c6c072015-12-10 16:34:21 +0000751/// Sink instructions into loops if profitable. This especially tries to prevent
752/// register spills caused by register pressure if there is little to no
753/// overhead moving instructions into loops.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000754void MachineLICMBase::SinkIntoLoop() {
Daniel Jasper15e69542015-03-14 10:58:38 +0000755 MachineBasicBlock *Preheader = getCurPreheader();
756 if (!Preheader)
757 return;
758
759 SmallVector<MachineInstr *, 8> Candidates;
760 for (MachineBasicBlock::instr_iterator I = Preheader->instr_begin();
761 I != Preheader->instr_end(); ++I) {
762 // We need to ensure that we can safely move this instruction into the loop.
Michael Liaoa5d45372017-04-26 05:27:20 +0000763 // 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 +0000764 if (IsLoopInvariantInst(*I) && !HasLoopPHIUse(&*I))
765 Candidates.push_back(&*I);
Daniel Jasper15e69542015-03-14 10:58:38 +0000766 }
767
768 for (MachineInstr *I : Candidates) {
769 const MachineOperand &MO = I->getOperand(0);
770 if (!MO.isDef() || !MO.isReg() || !MO.getReg())
771 continue;
772 if (!MRI->hasOneDef(MO.getReg()))
773 continue;
774 bool CanSink = true;
775 MachineBasicBlock *B = nullptr;
776 for (MachineInstr &MI : MRI->use_instructions(MO.getReg())) {
777 // FIXME: Come up with a proper cost model that estimates whether sinking
778 // the instruction (and thus possibly executing it on every loop
779 // iteration) is more expensive than a register.
780 // For now assumes that copies are cheap and thus almost always worth it.
781 if (!MI.isCopy()) {
782 CanSink = false;
783 break;
784 }
785 if (!B) {
786 B = MI.getParent();
787 continue;
788 }
789 B = DT->findNearestCommonDominator(B, MI.getParent());
790 if (!B) {
791 CanSink = false;
792 break;
793 }
794 }
795 if (!CanSink || !B || B == Preheader)
796 continue;
797 B->splice(B->getFirstNonPHI(), Preheader, I);
798 }
799}
800
Evan Cheng87066f02010-10-20 22:03:58 +0000801static bool isOperandKill(const MachineOperand &MO, MachineRegisterInfo *MRI) {
802 return MO.isKill() || MRI->hasOneNonDBGUse(MO.getReg());
803}
804
Sanjay Patel87c6c072015-12-10 16:34:21 +0000805/// Find all virtual register references that are liveout of the preheader to
806/// initialize the starting "register pressure". Note this does not count live
807/// through (livein but not used) registers.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000808void MachineLICMBase::InitRegPressure(MachineBasicBlock *BB) {
Evan Chengd62719c2010-10-14 01:16:09 +0000809 std::fill(RegPressure.begin(), RegPressure.end(), 0);
Evan Cheng44436302010-10-16 02:20:26 +0000810
Evan Cheng87066f02010-10-20 22:03:58 +0000811 // If the preheader has only a single predecessor and it ends with a
812 // fallthrough or an unconditional branch, then scan its predecessor for live
813 // defs as well. This happens whenever the preheader is created by splitting
814 // the critical edge from the loop predecessor to the loop header.
815 if (BB->pred_size() == 1) {
Craig Topperc0196b12014-04-14 00:51:57 +0000816 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Evan Cheng87066f02010-10-20 22:03:58 +0000817 SmallVector<MachineOperand, 4> Cond;
Jacques Pienaar71c30a12016-07-15 14:41:04 +0000818 if (!TII->analyzeBranch(*BB, TBB, FBB, Cond, false) && Cond.empty())
Evan Cheng87066f02010-10-20 22:03:58 +0000819 InitRegPressure(*BB->pred_begin());
820 }
821
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000822 for (const MachineInstr &MI : *BB)
823 UpdateRegPressure(&MI, /*ConsiderUnseenAsDef=*/true);
Evan Chengd62719c2010-10-14 01:16:09 +0000824}
825
Sanjay Patel87c6c072015-12-10 16:34:21 +0000826/// Update estimate of register pressure after the specified instruction.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000827void MachineLICMBase::UpdateRegPressure(const MachineInstr *MI,
828 bool ConsiderUnseenAsDef) {
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000829 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/true, ConsiderUnseenAsDef);
Daniel Jasper274928f2015-04-14 11:56:25 +0000830 for (const auto &RPIdAndCost : Cost) {
831 unsigned Class = RPIdAndCost.first;
832 if (static_cast<int>(RegPressure[Class]) < -RPIdAndCost.second)
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000833 RegPressure[Class] = 0;
834 else
Daniel Jasper274928f2015-04-14 11:56:25 +0000835 RegPressure[Class] += RPIdAndCost.second;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000836 }
837}
Evan Chengd62719c2010-10-14 01:16:09 +0000838
Sanjay Patel87c6c072015-12-10 16:34:21 +0000839/// Calculate the additional register pressure that the registers used in MI
840/// cause.
841///
842/// If 'ConsiderSeen' is true, updates 'RegSeen' and uses the information to
843/// figure out which usages are live-ins.
844/// FIXME: Figure out a way to consider 'RegSeen' from all code paths.
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000845DenseMap<unsigned, int>
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000846MachineLICMBase::calcRegisterCost(const MachineInstr *MI, bool ConsiderSeen,
847 bool ConsiderUnseenAsDef) {
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000848 DenseMap<unsigned, int> Cost;
849 if (MI->isImplicitDef())
850 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000851 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
852 const MachineOperand &MO = MI->getOperand(i);
Evan Cheng63c76082010-10-19 18:58:51 +0000853 if (!MO.isReg() || MO.isImplicit())
Evan Chengd62719c2010-10-14 01:16:09 +0000854 continue;
855 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2fb5b312011-01-10 02:58:51 +0000856 if (!TargetRegisterInfo::isVirtualRegister(Reg))
Evan Chengd62719c2010-10-14 01:16:09 +0000857 continue;
858
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000859 // FIXME: It seems bad to use RegSeen only for some of these calculations.
860 bool isNew = ConsiderSeen ? RegSeen.insert(Reg).second : false;
Daniel Jasper274928f2015-04-14 11:56:25 +0000861 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
862
863 RegClassWeight W = TRI->getRegClassWeight(RC);
864 int RCCost = 0;
Evan Cheng63c76082010-10-19 18:58:51 +0000865 if (MO.isDef())
Daniel Jasper274928f2015-04-14 11:56:25 +0000866 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000867 else {
868 bool isKill = isOperandKill(MO, MRI);
869 if (isNew && !isKill && ConsiderUnseenAsDef)
870 // Haven't seen this, it must be a livein.
Daniel Jasper274928f2015-04-14 11:56:25 +0000871 RCCost = W.RegWeight;
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000872 else if (!isNew && isKill)
Daniel Jasper274928f2015-04-14 11:56:25 +0000873 RCCost = -W.RegWeight;
874 }
875 if (RCCost == 0)
876 continue;
877 const int *PS = TRI->getRegClassPressureSets(RC);
878 for (; *PS != -1; ++PS) {
879 if (Cost.find(*PS) == Cost.end())
880 Cost[*PS] = RCCost;
881 else
882 Cost[*PS] += RCCost;
Evan Cheng44436302010-10-16 02:20:26 +0000883 }
Evan Chengd62719c2010-10-14 01:16:09 +0000884 }
Daniel Jaspere87e82b2015-04-07 16:42:35 +0000885 return Cost;
Evan Chengd62719c2010-10-14 01:16:09 +0000886}
887
Sanjay Patel87c6c072015-12-10 16:34:21 +0000888/// Return true if this machine instruction loads from global offset table or
889/// constant pool.
Philip Reames42bd26f2015-12-23 17:05:57 +0000890static bool mayLoadFromGOTOrConstantPool(MachineInstr &MI) {
Eugene Zelenkof1933322017-09-22 23:46:57 +0000891 assert(MI.mayLoad() && "Expected MI that loads!");
Michael Liaoa5d45372017-04-26 05:27:20 +0000892
Philip Reames42bd26f2015-12-23 17:05:57 +0000893 // If we lost memory operands, conservatively assume that the instruction
Michael Liaoa5d45372017-04-26 05:27:20 +0000894 // reads from everything..
Philip Reames42bd26f2015-12-23 17:05:57 +0000895 if (MI.memoperands_empty())
896 return true;
897
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000898 for (MachineMemOperand *MemOp : MI.memoperands())
899 if (const PseudoSourceValue *PSV = MemOp->getPseudoValue())
Alex Lorenze40c8a22015-08-11 23:09:45 +0000900 if (PSV->isGOT() || PSV->isConstantPool())
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000901 return true;
Sanjay Patel882a8ee2016-01-06 23:45:05 +0000902
Devang Patel69a45652011-10-17 17:35:01 +0000903 return false;
904}
905
Zaara Syeda65359932018-03-23 15:28:15 +0000906// This function iterates through all the operands of the input store MI and
907// checks that each register operand statisfies isCallerPreservedPhysReg.
908// This means, the value being stored and the address where it is being stored
909// is constant throughout the body of the function (not including prologue and
910// epilogue). When called with an MI that isn't a store, it returns false.
Zaara Syeda935474fe2018-04-09 14:50:02 +0000911// A future improvement can be to check if the store registers are constant
912// throughout the loop rather than throughout the funtion.
Zaara Syeda65359932018-03-23 15:28:15 +0000913static bool isInvariantStore(const MachineInstr &MI,
914 const TargetRegisterInfo *TRI,
915 const MachineRegisterInfo *MRI) {
916
Zaara Syeda935474fe2018-04-09 14:50:02 +0000917 bool FoundCallerPresReg = false;
Zaara Syeda65359932018-03-23 15:28:15 +0000918 if (!MI.mayStore() || MI.hasUnmodeledSideEffects() ||
919 (MI.getNumOperands() == 0))
920 return false;
921
922 // Check that all register operands are caller-preserved physical registers.
923 for (const MachineOperand &MO : MI.operands()) {
924 if (MO.isReg()) {
925 unsigned Reg = MO.getReg();
926 // If operand is a virtual register, check if it comes from a copy of a
927 // physical register.
928 if (TargetRegisterInfo::isVirtualRegister(Reg))
929 Reg = TRI->lookThruCopyLike(MO.getReg(), MRI);
930 if (TargetRegisterInfo::isVirtualRegister(Reg))
931 return false;
932 if (!TRI->isCallerPreservedPhysReg(Reg, *MI.getMF()))
933 return false;
Zaara Syeda935474fe2018-04-09 14:50:02 +0000934 else
935 FoundCallerPresReg = true;
936 } else if (!MO.isImm()) {
937 return false;
Zaara Syeda65359932018-03-23 15:28:15 +0000938 }
939 }
Zaara Syeda935474fe2018-04-09 14:50:02 +0000940 return FoundCallerPresReg;
Zaara Syeda65359932018-03-23 15:28:15 +0000941}
942
943// Return true if the input MI is a copy instruction that feeds an invariant
944// store instruction. This means that the src of the copy has to satisfy
945// isCallerPreservedPhysReg and atleast one of it's users should satisfy
946// isInvariantStore.
947static bool isCopyFeedingInvariantStore(const MachineInstr &MI,
948 const MachineRegisterInfo *MRI,
949 const TargetRegisterInfo *TRI) {
950
951 // FIXME: If targets would like to look through instructions that aren't
952 // pure copies, this can be updated to a query.
953 if (!MI.isCopy())
954 return false;
955
956 const MachineFunction *MF = MI.getMF();
957 // Check that we are copying a constant physical register.
958 unsigned CopySrcReg = MI.getOperand(1).getReg();
959 if (TargetRegisterInfo::isVirtualRegister(CopySrcReg))
960 return false;
961
962 if (!TRI->isCallerPreservedPhysReg(CopySrcReg, *MF))
963 return false;
964
965 unsigned CopyDstReg = MI.getOperand(0).getReg();
966 // Check if any of the uses of the copy are invariant stores.
967 assert (TargetRegisterInfo::isVirtualRegister(CopyDstReg) &&
968 "copy dst is not a virtual reg");
969
970 for (MachineInstr &UseMI : MRI->use_instructions(CopyDstReg)) {
971 if (UseMI.mayStore() && isInvariantStore(UseMI, TRI, MRI))
972 return true;
973 }
974 return false;
975}
976
Sanjay Patel87c6c072015-12-10 16:34:21 +0000977/// Returns true if the instruction may be a suitable candidate for LICM.
978/// e.g. If the instruction is a call, then it's obviously not safe to hoist it.
Matthias Braun4a7c8e72018-01-19 06:46:10 +0000979bool MachineLICMBase::IsLICMCandidate(MachineInstr &I) {
Chris Lattner0b7ae202010-07-12 00:00:35 +0000980 // Check if it's safe to move the instruction.
981 bool DontMoveAcrossStore = true;
Zaara Syeda65359932018-03-23 15:28:15 +0000982 if ((!I.isSafeToMove(AA, DontMoveAcrossStore)) &&
983 !(HoistConstStores && isInvariantStore(I, TRI, MRI))) {
Chris Lattnerc8226f32008-01-10 23:08:24 +0000984 return false;
Zaara Syeda65359932018-03-23 15:28:15 +0000985 }
Devang Patel453d4012011-10-11 18:09:58 +0000986
987 // If it is load then check if it is guaranteed to execute by making sure that
988 // it dominates all exiting blocks. If it doesn't, then there is a path out of
Devang Patel830c7762011-10-20 17:31:18 +0000989 // the loop which does not execute this load, so we can't hoist it. Loads
990 // from constant memory are not safe to speculate all the time, for example
991 // indexed load from a jump table.
Devang Patel453d4012011-10-11 18:09:58 +0000992 // Stores and side effects are already checked by isSafeToMove.
Philip Reames42bd26f2015-12-23 17:05:57 +0000993 if (I.mayLoad() && !mayLoadFromGOTOrConstantPool(I) &&
Devang Patel69a45652011-10-17 17:35:01 +0000994 !IsGuaranteedToExecute(I.getParent()))
Devang Patel453d4012011-10-11 18:09:58 +0000995 return false;
996
Evan Cheng0a2aff22010-04-13 18:16:00 +0000997 return true;
998}
999
Sanjay Patel87c6c072015-12-10 16:34:21 +00001000/// Returns true if the instruction is loop invariant.
1001/// I.e., all virtual register operands are defined outside of the loop,
1002/// physical registers aren't accessed explicitly, and there are no side
Evan Cheng0a2aff22010-04-13 18:16:00 +00001003/// effects that aren't captured by the operands or other flags.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001004bool MachineLICMBase::IsLoopInvariantInst(MachineInstr &I) {
Evan Cheng0a2aff22010-04-13 18:16:00 +00001005 if (!IsLICMCandidate(I))
1006 return false;
Bill Wendling2823eae2008-03-10 08:13:01 +00001007
Bill Wendling70613b82008-05-12 19:38:32 +00001008 // The instruction is loop invariant if all of its operands are.
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001009 for (const MachineOperand &MO : I.operands()) {
Dan Gohman0d1e9a82008-10-03 15:45:36 +00001010 if (!MO.isReg())
Bill Wendlingcd01e892008-08-20 20:32:05 +00001011 continue;
1012
Dan Gohman79618d12009-01-15 22:01:38 +00001013 unsigned Reg = MO.getReg();
1014 if (Reg == 0) continue;
1015
1016 // Don't hoist an instruction that uses or defines a physical register.
Dan Gohmane30d63f2009-09-25 23:58:45 +00001017 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohmane30d63f2009-09-25 23:58:45 +00001018 if (MO.isUse()) {
1019 // If the physreg has no defs anywhere, it's just an ambient register
Dan Gohman2f5bdcb2009-09-26 02:34:00 +00001020 // and we can freely move its uses. Alternatively, if it's allocatable,
1021 // it could get allocated to something with a def during allocation.
Lei Huangb4733ca2017-06-15 18:29:59 +00001022 // However, if the physreg is known to always be caller saved/restored
1023 // then this use is safe to hoist.
1024 if (!MRI->isConstantPhysReg(Reg) &&
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001025 !(TRI->isCallerPreservedPhysReg(Reg, *I.getMF())))
1026 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +00001027 // Otherwise it's safe to move.
1028 continue;
1029 } else if (!MO.isDead()) {
1030 // A def that isn't dead. We can't move it.
1031 return false;
Dan Gohman6fb6a592010-02-28 00:08:44 +00001032 } else if (CurLoop->getHeader()->isLiveIn(Reg)) {
1033 // If the reg is live into the loop, we can't hoist an instruction
1034 // which would clobber it.
1035 return false;
Dan Gohmane30d63f2009-09-25 23:58:45 +00001036 }
1037 }
Bill Wendlingcd01e892008-08-20 20:32:05 +00001038
1039 if (!MO.isUse())
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001040 continue;
1041
Evan Chengd62719c2010-10-14 01:16:09 +00001042 assert(MRI->getVRegDef(Reg) &&
Bill Wendling70613b82008-05-12 19:38:32 +00001043 "Machine instr not mapped for this vreg?!");
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001044
1045 // If the loop contains the definition of an operand, then the instruction
1046 // isn't loop invariant.
Evan Chengd62719c2010-10-14 01:16:09 +00001047 if (CurLoop->contains(MRI->getVRegDef(Reg)))
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001048 return false;
1049 }
1050
1051 // If we got this far, the instruction is loop invariant!
1052 return true;
1053}
1054
Sanjay Patel87c6c072015-12-10 16:34:21 +00001055/// Return true if the specified instruction is used by a phi node and hoisting
1056/// it could cause a copy to be inserted.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001057bool MachineLICMBase::HasLoopPHIUse(const MachineInstr *MI) const {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001058 SmallVector<const MachineInstr*, 8> Work(1, MI);
1059 do {
1060 MI = Work.pop_back_val();
Matthias Braune41e1462015-05-29 02:56:46 +00001061 for (const MachineOperand &MO : MI->operands()) {
1062 if (!MO.isReg() || !MO.isDef())
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001063 continue;
Matthias Braune41e1462015-05-29 02:56:46 +00001064 unsigned Reg = MO.getReg();
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001065 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1066 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001067 for (MachineInstr &UseMI : MRI->use_instructions(Reg)) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001068 // A PHI may cause a copy to be inserted.
Owen Andersonb36376e2014-03-17 19:36:09 +00001069 if (UseMI.isPHI()) {
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001070 // A PHI inside the loop causes a copy because the live range of Reg is
1071 // extended across the PHI.
Owen Andersonb36376e2014-03-17 19:36:09 +00001072 if (CurLoop->contains(&UseMI))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001073 return true;
1074 // A PHI in an exit block can cause a copy to be inserted if the PHI
1075 // has multiple predecessors in the loop with different values.
1076 // For now, approximate by rejecting all exit blocks.
Owen Andersonb36376e2014-03-17 19:36:09 +00001077 if (isExitBlock(UseMI.getParent()))
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001078 return true;
1079 continue;
1080 }
1081 // Look past copies as well.
Owen Andersonb36376e2014-03-17 19:36:09 +00001082 if (UseMI.isCopy() && CurLoop->contains(&UseMI))
1083 Work.push_back(&UseMI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001084 }
Evan Chengef42bea2011-04-11 21:09:18 +00001085 }
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001086 } while (!Work.empty());
Evan Cheng399660c2009-02-05 08:45:46 +00001087 return false;
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001088}
1089
Sanjay Patel87c6c072015-12-10 16:34:21 +00001090/// Compute operand latency between a def of 'Reg' and an use in the current
1091/// loop, return true if the target considered it high.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001092bool MachineLICMBase::HasHighOperandLatency(MachineInstr &MI,
1093 unsigned DefIdx,
1094 unsigned Reg) const {
Matthias Braun88e21312015-06-13 03:42:11 +00001095 if (MRI->use_nodbg_empty(Reg))
Evan Cheng63c76082010-10-19 18:58:51 +00001096 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001097
Owen Andersonb36376e2014-03-17 19:36:09 +00001098 for (MachineInstr &UseMI : MRI->use_nodbg_instructions(Reg)) {
1099 if (UseMI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001100 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001101 if (!CurLoop->contains(UseMI.getParent()))
Evan Chengd62719c2010-10-14 01:16:09 +00001102 continue;
Owen Andersonb36376e2014-03-17 19:36:09 +00001103 for (unsigned i = 0, e = UseMI.getNumOperands(); i != e; ++i) {
1104 const MachineOperand &MO = UseMI.getOperand(i);
Evan Chengd62719c2010-10-14 01:16:09 +00001105 if (!MO.isReg() || !MO.isUse())
1106 continue;
1107 unsigned MOReg = MO.getReg();
1108 if (MOReg != Reg)
1109 continue;
1110
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001111 if (TII->hasHighOperandLatency(SchedModel, MRI, MI, DefIdx, UseMI, i))
Evan Cheng63c76082010-10-19 18:58:51 +00001112 return true;
Evan Chengd62719c2010-10-14 01:16:09 +00001113 }
1114
Evan Cheng63c76082010-10-19 18:58:51 +00001115 // Only look at the first in loop use.
1116 break;
Evan Chengd62719c2010-10-14 01:16:09 +00001117 }
1118
Evan Cheng63c76082010-10-19 18:58:51 +00001119 return false;
Evan Chengd62719c2010-10-14 01:16:09 +00001120}
1121
Sanjay Patel87c6c072015-12-10 16:34:21 +00001122/// Return true if the instruction is marked "cheap" or the operand latency
1123/// between its def and a use is one or less.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001124bool MachineLICMBase::IsCheapInstruction(MachineInstr &MI) const {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001125 if (TII->isAsCheapAsAMove(MI) || MI.isCopyLike())
Evan Chenge96b8d72010-10-26 02:08:50 +00001126 return true;
Evan Chenge96b8d72010-10-26 02:08:50 +00001127
1128 bool isCheap = false;
1129 unsigned NumDefs = MI.getDesc().getNumDefs();
1130 for (unsigned i = 0, e = MI.getNumOperands(); NumDefs && i != e; ++i) {
1131 MachineOperand &DefMO = MI.getOperand(i);
1132 if (!DefMO.isReg() || !DefMO.isDef())
1133 continue;
1134 --NumDefs;
1135 unsigned Reg = DefMO.getReg();
1136 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1137 continue;
1138
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001139 if (!TII->hasLowDefLatency(SchedModel, MI, i))
Evan Chenge96b8d72010-10-26 02:08:50 +00001140 return false;
1141 isCheap = true;
1142 }
1143
1144 return isCheap;
1145}
1146
Sanjay Patel87c6c072015-12-10 16:34:21 +00001147/// Visit BBs from header to current BB, check if hoisting an instruction of the
1148/// given cost matrix can cause high register pressure.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001149bool
1150MachineLICMBase::CanCauseHighRegPressure(const DenseMap<unsigned, int>& Cost,
1151 bool CheapInstr) {
Daniel Jasper274928f2015-04-14 11:56:25 +00001152 for (const auto &RPIdAndCost : Cost) {
1153 if (RPIdAndCost.second <= 0)
Evan Cheng87066f02010-10-20 22:03:58 +00001154 continue;
1155
Daniel Jasper274928f2015-04-14 11:56:25 +00001156 unsigned Class = RPIdAndCost.first;
Daniel Jasperefece522015-04-03 16:19:48 +00001157 int Limit = RegLimit[Class];
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001158
1159 // Don't hoist cheap instructions if they would increase register pressure,
1160 // even if we're under the limit.
Hal Finkel0709f512015-01-08 22:10:48 +00001161 if (CheapInstr && !HoistCheapInsts)
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001162 return true;
1163
Daniel Jasperefece522015-04-03 16:19:48 +00001164 for (const auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001165 if (static_cast<int>(RP[Class]) + RPIdAndCost.second >= Limit)
Evan Cheng44436302010-10-16 02:20:26 +00001166 return true;
Evan Cheng44436302010-10-16 02:20:26 +00001167 }
1168
1169 return false;
1170}
1171
Sanjay Patel87c6c072015-12-10 16:34:21 +00001172/// Traverse the back trace from header to the current block and update their
1173/// register pressures to reflect the effect of hoisting MI from the current
1174/// block to the preheader.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001175void MachineLICMBase::UpdateBackTraceRegPressure(const MachineInstr *MI) {
Evan Cheng87066f02010-10-20 22:03:58 +00001176 // First compute the 'cost' of the instruction, i.e. its contribution
1177 // to register pressure.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001178 auto Cost = calcRegisterCost(MI, /*ConsiderSeen=*/false,
1179 /*ConsiderUnseenAsDef=*/false);
Evan Cheng87066f02010-10-20 22:03:58 +00001180
1181 // Update register pressure of blocks from loop header to current block.
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001182 for (auto &RP : BackTrace)
Daniel Jasper274928f2015-04-14 11:56:25 +00001183 for (const auto &RPIdAndCost : Cost)
1184 RP[RPIdAndCost.first] += RPIdAndCost.second;
Evan Cheng87066f02010-10-20 22:03:58 +00001185}
1186
Sanjay Patel87c6c072015-12-10 16:34:21 +00001187/// Return true if it is potentially profitable to hoist the given loop
1188/// invariant.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001189bool MachineLICMBase::IsProfitableToHoist(MachineInstr &MI) {
Evan Chengd62719c2010-10-14 01:16:09 +00001190 if (MI.isImplicitDef())
1191 return true;
1192
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001193 // Besides removing computation from the loop, hoisting an instruction has
1194 // these effects:
1195 //
1196 // - The value defined by the instruction becomes live across the entire
1197 // loop. This increases register pressure in the loop.
1198 //
1199 // - If the value is used by a PHI in the loop, a copy will be required for
1200 // lowering the PHI after extending the live range.
1201 //
1202 // - When hoisting the last use of a value in the loop, that value no longer
1203 // needs to be live in the loop. This lowers register pressure in the loop.
Evan Cheng90da66b2011-09-01 01:45:00 +00001204
Zaara Syeda65359932018-03-23 15:28:15 +00001205 if (HoistConstStores && isCopyFeedingInvariantStore(MI, MRI, TRI))
1206 return true;
1207
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001208 bool CheapInstr = IsCheapInstruction(MI);
1209 bool CreatesCopy = HasLoopPHIUse(&MI);
Evan Cheng44436302010-10-16 02:20:26 +00001210
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001211 // Don't hoist a cheap instruction if it would create a copy in the loop.
1212 if (CheapInstr && CreatesCopy) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001213 LLVM_DEBUG(dbgs() << "Won't hoist cheap instr with loop PHI use: " << MI);
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001214 return false;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001215 }
Evan Cheng1d9f7ac2009-02-04 09:19:56 +00001216
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001217 // Rematerializable instructions should always be hoisted since the register
1218 // allocator can just pull them down again when needed.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001219 if (TII->isTriviallyReMaterializable(MI, AA))
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001220 return true;
1221
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001222 // FIXME: If there are long latency loop-invariant instructions inside the
1223 // loop at this point, why didn't the optimizer's LICM hoist them?
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001224 for (unsigned i = 0, e = MI.getDesc().getNumOperands(); i != e; ++i) {
1225 const MachineOperand &MO = MI.getOperand(i);
1226 if (!MO.isReg() || MO.isImplicit())
1227 continue;
1228 unsigned Reg = MO.getReg();
1229 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1230 continue;
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001231 if (MO.isDef() && HasHighOperandLatency(MI, i, Reg)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001232 LLVM_DEBUG(dbgs() << "Hoist High Latency: " << MI);
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001233 ++NumHighLatency;
1234 return true;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001235 }
1236 }
1237
Daniel Jaspere87e82b2015-04-07 16:42:35 +00001238 // Estimate register pressure to determine whether to LICM the instruction.
1239 // In low register pressure situation, we can be more aggressive about
1240 // hoisting. Also, favors hoisting long latency instructions even in
1241 // moderately high pressure situation.
1242 // Cheap instructions will only be hoisted if they don't increase register
1243 // pressure at all.
1244 auto Cost = calcRegisterCost(&MI, /*ConsiderSeen=*/false,
1245 /*ConsiderUnseenAsDef=*/false);
1246
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001247 // Visit BBs from header to current BB, if hoisting this doesn't cause
1248 // high register pressure, then it's safe to proceed.
1249 if (!CanCauseHighRegPressure(Cost, CheapInstr)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001250 LLVM_DEBUG(dbgs() << "Hoist non-reg-pressure: " << MI);
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001251 ++NumLowRP;
1252 return true;
1253 }
1254
1255 // Don't risk increasing register pressure if it would create copies.
1256 if (CreatesCopy) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001257 LLVM_DEBUG(dbgs() << "Won't hoist instr with loop PHI use: " << MI);
Jakob Stoklund Olesena3e86a62012-04-11 00:00:26 +00001258 return false;
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001259 }
1260
1261 // Do not "speculate" in high register pressure situation. If an
1262 // instruction is not guaranteed to be executed in the loop, it's best to be
1263 // conservative.
1264 if (AvoidSpeculation &&
1265 (!IsGuaranteedToExecute(MI.getParent()) && !MayCSE(&MI))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001266 LLVM_DEBUG(dbgs() << "Won't speculate: " << MI);
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001267 return false;
1268 }
1269
1270 // High register pressure situation, only hoist if the instruction is going
1271 // to be remat'ed.
Justin Lebard98cf002016-09-10 01:03:20 +00001272 if (!TII->isTriviallyReMaterializable(MI, AA) &&
1273 !MI.isDereferenceableInvariantLoad(AA)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001274 LLVM_DEBUG(dbgs() << "Can't remat / high reg-pressure: " << MI);
Jakob Stoklund Olesen645bdd42012-04-11 00:00:28 +00001275 return false;
1276 }
Evan Cheng399660c2009-02-05 08:45:46 +00001277
1278 return true;
1279}
1280
Sanjay Patel87c6c072015-12-10 16:34:21 +00001281/// Unfold a load from the given machineinstr if the load itself could be
1282/// hoisted. Return the unfolded and hoistable load, or null if the load
1283/// couldn't be unfolded or if it wouldn't be hoistable.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001284MachineInstr *MachineLICMBase::ExtractHoistableLoad(MachineInstr *MI) {
Evan Cheng4ac0d162010-10-08 18:59:19 +00001285 // Don't unfold simple loads.
Evan Cheng7f8e5632011-12-07 07:15:52 +00001286 if (MI->canFoldAsLoad())
Craig Topperc0196b12014-04-14 00:51:57 +00001287 return nullptr;
Evan Cheng4ac0d162010-10-08 18:59:19 +00001288
Dan Gohman104f57c2009-10-29 17:47:20 +00001289 // If not, we may be able to unfold a load and hoist that.
1290 // First test whether the instruction is loading from an amenable
1291 // memory location.
Justin Lebard98cf002016-09-10 01:03:20 +00001292 if (!MI->isDereferenceableInvariantLoad(AA))
Craig Topperc0196b12014-04-14 00:51:57 +00001293 return nullptr;
Evan Chengb39a9fd2009-11-20 19:55:37 +00001294
Dan Gohman104f57c2009-10-29 17:47:20 +00001295 // Next determine the register class for a temporary register.
Dan Gohman49fa51d2009-10-30 22:18:41 +00001296 unsigned LoadRegIndex;
Dan Gohman104f57c2009-10-29 17:47:20 +00001297 unsigned NewOpc =
1298 TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(),
1299 /*UnfoldLoad=*/true,
Dan Gohman49fa51d2009-10-30 22:18:41 +00001300 /*UnfoldStore=*/false,
1301 &LoadRegIndex);
Craig Topperc0196b12014-04-14 00:51:57 +00001302 if (NewOpc == 0) return nullptr;
Evan Cheng6cc775f2011-06-28 19:10:37 +00001303 const MCInstrDesc &MID = TII->get(NewOpc);
Justin Bognerfdf9bf42017-10-10 23:50:49 +00001304 MachineFunction &MF = *MI->getMF();
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +00001305 const TargetRegisterClass *RC = TII->getRegClass(MID, LoadRegIndex, TRI, MF);
Dan Gohman104f57c2009-10-29 17:47:20 +00001306 // Ok, we're unfolding. Create a temporary register and do the unfold.
Evan Chengd62719c2010-10-14 01:16:09 +00001307 unsigned Reg = MRI->createVirtualRegister(RC);
Evan Chengb39a9fd2009-11-20 19:55:37 +00001308
Dan Gohman104f57c2009-10-29 17:47:20 +00001309 SmallVector<MachineInstr *, 2> NewMIs;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001310 bool Success = TII->unfoldMemoryOperand(MF, *MI, Reg,
1311 /*UnfoldLoad=*/true,
1312 /*UnfoldStore=*/false, NewMIs);
Dan Gohman104f57c2009-10-29 17:47:20 +00001313 (void)Success;
1314 assert(Success &&
1315 "unfoldMemoryOperand failed when getOpcodeAfterMemoryUnfold "
1316 "succeeded!");
1317 assert(NewMIs.size() == 2 &&
1318 "Unfolded a load into multiple instructions!");
1319 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng2a81dd42011-12-06 22:12:01 +00001320 MachineBasicBlock::iterator Pos = MI;
1321 MBB->insert(Pos, NewMIs[0]);
1322 MBB->insert(Pos, NewMIs[1]);
Dan Gohman104f57c2009-10-29 17:47:20 +00001323 // If unfolding produced a load that wasn't loop-invariant or profitable to
1324 // hoist, discard the new instructions and bail.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001325 if (!IsLoopInvariantInst(*NewMIs[0]) || !IsProfitableToHoist(*NewMIs[0])) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001326 NewMIs[0]->eraseFromParent();
1327 NewMIs[1]->eraseFromParent();
Craig Topperc0196b12014-04-14 00:51:57 +00001328 return nullptr;
Dan Gohman104f57c2009-10-29 17:47:20 +00001329 }
Evan Cheng87066f02010-10-20 22:03:58 +00001330
1331 // Update register pressure for the unfolded instruction.
1332 UpdateRegPressure(NewMIs[1]);
1333
Dan Gohman104f57c2009-10-29 17:47:20 +00001334 // Otherwise we successfully unfolded a load that we can hoist.
1335 MI->eraseFromParent();
1336 return NewMIs[0];
1337}
1338
Sanjay Patel87c6c072015-12-10 16:34:21 +00001339/// Initialize the CSE map with instructions that are in the current loop
1340/// preheader that may become duplicates of instructions that are hoisted
1341/// out of the loop.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001342void MachineLICMBase::InitCSEMap(MachineBasicBlock *BB) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001343 for (MachineInstr &MI : *BB)
1344 CSEMap[MI.getOpcode()].push_back(&MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001345}
1346
Sanjay Patel87c6c072015-12-10 16:34:21 +00001347/// Find an instruction amount PrevMIs that is a duplicate of MI.
1348/// Return this instruction if it's found.
Evan Cheng7ff83192009-11-07 03:52:02 +00001349const MachineInstr*
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001350MachineLICMBase::LookForDuplicate(const MachineInstr *MI,
1351 std::vector<const MachineInstr*> &PrevMIs) {
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001352 for (const MachineInstr *PrevMI : PrevMIs)
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +00001353 if (TII->produceSameValue(*MI, *PrevMI, (PreRegAlloc ? MRI : nullptr)))
Evan Cheng921152f2009-11-05 00:51:13 +00001354 return PrevMI;
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001355
Craig Topperc0196b12014-04-14 00:51:57 +00001356 return nullptr;
Evan Cheng921152f2009-11-05 00:51:13 +00001357}
1358
Sanjay Patel87c6c072015-12-10 16:34:21 +00001359/// Given a LICM'ed instruction, look for an instruction on the preheader that
1360/// computes the same value. If it's found, do a RAU on with the definition of
1361/// the existing instruction rather than hoisting the instruction to the
1362/// preheader.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001363bool MachineLICMBase::EliminateCSE(MachineInstr *MI,
1364 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator &CI) {
Evan Chengd5424142010-07-14 01:22:19 +00001365 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1366 // the undef property onto uses.
1367 if (CI == CSEMap.end() || MI->isImplicitDef())
Evan Cheng7ff83192009-11-07 03:52:02 +00001368 return false;
1369
1370 if (const MachineInstr *Dup = LookForDuplicate(MI, CI->second)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001371 LLVM_DEBUG(dbgs() << "CSEing " << *MI << " with " << *Dup);
Dan Gohman34021b72010-02-28 01:33:43 +00001372
1373 // Replace virtual registers defined by MI by their counterparts defined
1374 // by Dup.
Evan Chengaa563df2011-10-17 19:50:12 +00001375 SmallVector<unsigned, 2> Defs;
Evan Cheng7ff83192009-11-07 03:52:02 +00001376 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1377 const MachineOperand &MO = MI->getOperand(i);
Dan Gohman34021b72010-02-28 01:33:43 +00001378
1379 // Physical registers may not differ here.
1380 assert((!MO.isReg() || MO.getReg() == 0 ||
1381 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1382 MO.getReg() == Dup->getOperand(i).getReg()) &&
1383 "Instructions with different phys regs are not identical!");
1384
1385 if (MO.isReg() && MO.isDef() &&
Evan Chengaa563df2011-10-17 19:50:12 +00001386 !TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1387 Defs.push_back(i);
1388 }
1389
1390 SmallVector<const TargetRegisterClass*, 2> OrigRCs;
1391 for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
1392 unsigned Idx = Defs[i];
1393 unsigned Reg = MI->getOperand(Idx).getReg();
1394 unsigned DupReg = Dup->getOperand(Idx).getReg();
1395 OrigRCs.push_back(MRI->getRegClass(DupReg));
1396
1397 if (!MRI->constrainRegClass(DupReg, MRI->getRegClass(Reg))) {
1398 // Restore old RCs if more than one defs.
1399 for (unsigned j = 0; j != i; ++j)
1400 MRI->setRegClass(Dup->getOperand(Defs[j]).getReg(), OrigRCs[j]);
1401 return false;
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001402 }
Evan Cheng921152f2009-11-05 00:51:13 +00001403 }
Evan Chengaa563df2011-10-17 19:50:12 +00001404
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001405 for (unsigned Idx : Defs) {
Evan Chengaa563df2011-10-17 19:50:12 +00001406 unsigned Reg = MI->getOperand(Idx).getReg();
1407 unsigned DupReg = Dup->getOperand(Idx).getReg();
1408 MRI->replaceRegWith(Reg, DupReg);
1409 MRI->clearKillFlags(DupReg);
1410 }
1411
Evan Cheng7ff83192009-11-07 03:52:02 +00001412 MI->eraseFromParent();
1413 ++NumCSEed;
1414 return true;
Evan Cheng921152f2009-11-05 00:51:13 +00001415 }
1416 return false;
1417}
1418
Sanjay Patel87c6c072015-12-10 16:34:21 +00001419/// Return true if the given instruction will be CSE'd if it's hoisted out of
1420/// the loop.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001421bool MachineLICMBase::MayCSE(MachineInstr *MI) {
Evan Chengaf138952011-10-12 00:09:14 +00001422 unsigned Opcode = MI->getOpcode();
Eugene Zelenkof1933322017-09-22 23:46:57 +00001423 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
Evan Chengaf138952011-10-12 00:09:14 +00001424 CI = CSEMap.find(Opcode);
1425 // Do not CSE implicit_def so ProcessImplicitDefs can properly propagate
1426 // the undef property onto uses.
1427 if (CI == CSEMap.end() || MI->isImplicitDef())
1428 return false;
1429
Craig Topperc0196b12014-04-14 00:51:57 +00001430 return LookForDuplicate(MI, CI->second) != nullptr;
Evan Chengaf138952011-10-12 00:09:14 +00001431}
1432
Sanjay Patel87c6c072015-12-10 16:34:21 +00001433/// When an instruction is found to use only loop invariant operands
Bill Wendling70613b82008-05-12 19:38:32 +00001434/// that are safe to hoist, this instruction is called to do the dirty work.
Sanjay Patel87c6c072015-12-10 16:34:21 +00001435/// It returns true if the instruction is hoisted.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001436bool MachineLICMBase::Hoist(MachineInstr *MI, MachineBasicBlock *Preheader) {
Dan Gohman1b44f102009-10-28 03:21:57 +00001437 // First check whether we should hoist this instruction.
Evan Cheng73f9a9e2009-11-20 23:31:34 +00001438 if (!IsLoopInvariantInst(*MI) || !IsProfitableToHoist(*MI)) {
Dan Gohman104f57c2009-10-29 17:47:20 +00001439 // If not, try unfolding a hoistable load.
1440 MI = ExtractHoistableLoad(MI);
Evan Cheng87066f02010-10-20 22:03:58 +00001441 if (!MI) return false;
Dan Gohman1b44f102009-10-28 03:21:57 +00001442 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001443
Zaara Syeda65359932018-03-23 15:28:15 +00001444 // If we have hoisted an instruction that may store, it can only be a constant
1445 // store.
1446 if (MI->mayStore())
1447 NumStoreConst++;
1448
Dan Gohman79618d12009-01-15 22:01:38 +00001449 // Now move the instructions to the predecessor, inserting it before any
1450 // terminator instructions.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001451 LLVM_DEBUG({
1452 dbgs() << "Hoisting " << *MI;
1453 if (MI->getParent()->getBasicBlock())
1454 dbgs() << " from " << printMBBReference(*MI->getParent());
1455 if (Preheader->getBasicBlock())
1456 dbgs() << " to " << printMBBReference(*Preheader);
1457 dbgs() << "\n";
1458 });
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001459
Evan Chengf42b5af2009-11-03 21:40:02 +00001460 // If this is the first instruction being hoisted to the preheader,
1461 // initialize the CSE map with potential common expressions.
Evan Cheng032f3262010-05-29 00:06:36 +00001462 if (FirstInLoop) {
Dan Gohman3570f812010-06-22 17:25:57 +00001463 InitCSEMap(Preheader);
Evan Cheng032f3262010-05-29 00:06:36 +00001464 FirstInLoop = false;
1465 }
Evan Chengf42b5af2009-11-03 21:40:02 +00001466
Evan Cheng399660c2009-02-05 08:45:46 +00001467 // Look for opportunity to CSE the hoisted instruction.
Evan Chengf42b5af2009-11-03 21:40:02 +00001468 unsigned Opcode = MI->getOpcode();
Eugene Zelenkof1933322017-09-22 23:46:57 +00001469 DenseMap<unsigned, std::vector<const MachineInstr *>>::iterator
Evan Chengf42b5af2009-11-03 21:40:02 +00001470 CI = CSEMap.find(Opcode);
Evan Cheng921152f2009-11-05 00:51:13 +00001471 if (!EliminateCSE(MI, CI)) {
1472 // Otherwise, splice the instruction to the preheader.
Dan Gohman3570f812010-06-22 17:25:57 +00001473 Preheader->splice(Preheader->getFirstTerminator(),MI->getParent(),MI);
Evan Chengf42b5af2009-11-03 21:40:02 +00001474
Wolfgang Pieb42f92a72016-12-02 00:37:57 +00001475 // Since we are moving the instruction out of its basic block, we do not
Michael Liaoa5d45372017-04-26 05:27:20 +00001476 // retain its debug location. Doing so would degrade the debugging
Wolfgang Pieb42f92a72016-12-02 00:37:57 +00001477 // experience and adversely affect the accuracy of profiling information.
1478 MI->setDebugLoc(DebugLoc());
1479
Evan Cheng87066f02010-10-20 22:03:58 +00001480 // Update register pressure for BBs from header to this block.
1481 UpdateBackTraceRegPressure(MI);
1482
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001483 // Clear the kill flags of any register this instruction defines,
1484 // since they may need to be live throughout the entire loop
1485 // rather than just live for part of it.
Sanjay Patel882a8ee2016-01-06 23:45:05 +00001486 for (MachineOperand &MO : MI->operands())
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001487 if (MO.isReg() && MO.isDef() && !MO.isDead())
Evan Chengd62719c2010-10-14 01:16:09 +00001488 MRI->clearKillFlags(MO.getReg());
Dan Gohmanc90f51c2010-05-13 20:34:42 +00001489
Evan Cheng399660c2009-02-05 08:45:46 +00001490 // Add to the CSE map.
1491 if (CI != CSEMap.end())
Dan Gohman1b44f102009-10-28 03:21:57 +00001492 CI->second.push_back(MI);
Benjamin Kramere12a6ba2014-10-03 18:33:16 +00001493 else
1494 CSEMap[Opcode].push_back(MI);
Evan Cheng399660c2009-02-05 08:45:46 +00001495 }
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001496
Dan Gohman79618d12009-01-15 22:01:38 +00001497 ++NumHoisted;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001498 Changed = true;
Evan Cheng87066f02010-10-20 22:03:58 +00001499
1500 return true;
Bill Wendlingfb706bc2007-12-07 21:42:31 +00001501}
Dan Gohman3570f812010-06-22 17:25:57 +00001502
Sanjay Patel87c6c072015-12-10 16:34:21 +00001503/// Get the preheader for the current loop, splitting a critical edge if needed.
Matthias Braun4a7c8e72018-01-19 06:46:10 +00001504MachineBasicBlock *MachineLICMBase::getCurPreheader() {
Dan Gohman3570f812010-06-22 17:25:57 +00001505 // Determine the block to which to hoist instructions. If we can't find a
1506 // suitable loop predecessor, we can't do any hoisting.
1507
1508 // If we've tried to get a preheader and failed, don't try again.
1509 if (CurPreheader == reinterpret_cast<MachineBasicBlock *>(-1))
Craig Topperc0196b12014-04-14 00:51:57 +00001510 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001511
1512 if (!CurPreheader) {
1513 CurPreheader = CurLoop->getLoopPreheader();
1514 if (!CurPreheader) {
1515 MachineBasicBlock *Pred = CurLoop->getLoopPredecessor();
1516 if (!Pred) {
1517 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001518 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001519 }
1520
Quentin Colombet23341a82016-04-21 21:01:13 +00001521 CurPreheader = Pred->SplitCriticalEdge(CurLoop->getHeader(), *this);
Dan Gohman3570f812010-06-22 17:25:57 +00001522 if (!CurPreheader) {
1523 CurPreheader = reinterpret_cast<MachineBasicBlock *>(-1);
Craig Topperc0196b12014-04-14 00:51:57 +00001524 return nullptr;
Dan Gohman3570f812010-06-22 17:25:57 +00001525 }
1526 }
1527 }
1528 return CurPreheader;
1529}