blob: b866b25db4b04c0384407e5b8ac2fb64c2799235 [file] [log] [blame]
Chris Lattner6ec05f52002-05-10 22:44:58 +00001//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner6ec05f52002-05-10 22:44:58 +00009//
Chris Lattnerc0517682003-12-09 17:18:00 +000010// This pass performs loop invariant code motion, attempting to remove as much
11// code from the body of a loop as possible. It does this by either hoisting
12// code into the preheader block, or by sinking code to the exit blocks if it is
13// safe. This pass also promotes must-aliased memory locations in the loop to
Chris Lattner547192d62003-12-19 07:22:45 +000014// live in registers, thus hoisting and sinking "invariant" loads and stores.
Chris Lattnerc0517682003-12-09 17:18:00 +000015//
16// This pass uses alias analysis for two purposes:
Chris Lattner45d67d62003-02-24 03:52:32 +000017//
Chris Lattner289ba2a2004-05-23 21:20:19 +000018// 1. Moving loop invariant loads and calls out of loops. If we can determine
19// that a load or call inside of a loop never aliases anything stored to,
20// we can hoist it or sink it like any other instruction.
Chris Lattner45d67d62003-02-24 03:52:32 +000021// 2. Scalar Promotion of Memory - If there is a store instruction inside of
22// the loop, we try to move the store to happen AFTER the loop instead of
23// inside of the loop. This can only happen if a few conditions are true:
24// A. The pointer stored through is loop invariant
25// B. There are no stores or loads in the loop which _may_ alias the
26// pointer. There are no calls in the loop which mod/ref the pointer.
27// If these conditions are true, we can promote the loads and stores in the
28// loop of the pointer to use a temporary alloca'd variable. We then use
Chris Lattner1dc98b42010-08-29 06:43:52 +000029// the SSAUpdater to construct the appropriate SSA form for the value.
Chris Lattner6ec05f52002-05-10 22:44:58 +000030//
Chris Lattner6ec05f52002-05-10 22:44:58 +000031//===----------------------------------------------------------------------===//
32
33#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/ADT/Statistic.h"
Chris Lattnera51fa882002-08-22 21:39:55 +000035#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0592bb72003-03-03 23:32:45 +000036#include "llvm/Analysis/AliasSetTracker.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000037#include "llvm/Analysis/BasicAliasAnalysis.h"
Chris Lattner030f0202010-08-31 23:00:16 +000038#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000039#include "llvm/Analysis/GlobalsModRef.h"
Chris Lattner030f0202010-08-31 23:00:16 +000040#include "llvm/Analysis/LoopInfo.h"
41#include "llvm/Analysis/LoopPass.h"
Chandler Carruthabfa3e52014-01-24 01:59:49 +000042#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000043#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000044#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000045#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000046#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Constants.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000050#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Instructions.h"
52#include "llvm/IR/IntrinsicInst.h"
53#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000054#include "llvm/IR/Metadata.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000055#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000056#include "llvm/Support/CommandLine.h"
57#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000058#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000059#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000060#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000061#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000062#include <algorithm>
Chris Lattnerc0517682003-12-09 17:18:00 +000063using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000064
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "licm"
66
Chris Lattner79a42ac2006-12-19 21:40:18 +000067STATISTIC(NumSunk , "Number of instructions sunk out of loop");
68STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
69STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
70STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
71STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
72
Dan Gohmand78c4002008-05-13 00:00:25 +000073static cl::opt<bool>
74DisablePromotion("disable-licm-promotion", cl::Hidden,
75 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000076
Hal Finkel3d4269a2015-02-22 18:35:32 +000077static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
David Majnemer42a07302016-01-04 03:37:39 +000078static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
79 const LICMSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +000080static bool hoist(Instruction &I, BasicBlock *Preheader);
Pete Cooper0cabcf22015-05-13 01:12:18 +000081static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +000082 const Loop *CurLoop, AliasSetTracker *CurAST,
83 const LICMSafetyInfo *SafetyInfo);
Pete Cooper0cabcf22015-05-13 01:12:18 +000084static bool isGuaranteedToExecute(const Instruction &Inst,
85 const DominatorTree *DT,
86 const Loop *CurLoop,
87 const LICMSafetyInfo *SafetyInfo);
88static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
89 const DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +000090 const TargetLibraryInfo *TLI,
Pete Cooper0cabcf22015-05-13 01:12:18 +000091 const Loop *CurLoop,
Philip Reamesb47b9c22015-05-22 02:14:05 +000092 const LICMSafetyInfo *SafetyInfo,
93 const Instruction *CtxI = nullptr);
Hal Finkel3d4269a2015-02-22 18:35:32 +000094static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
95 const AAMDNodes &AAInfo,
96 AliasSetTracker *CurAST);
David Majnemer42a07302016-01-04 03:37:39 +000097static Instruction *
98CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
99 const LoopInfo *LI,
100 const LICMSafetyInfo *SafetyInfo);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000101static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000102 DominatorTree *DT, TargetLibraryInfo *TLI,
103 Loop *CurLoop, AliasSetTracker *CurAST,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000104 LICMSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000105
Dan Gohmand78c4002008-05-13 00:00:25 +0000106namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +0000107 struct LICM : public LoopPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000108 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000109 LICM() : LoopPass(ID) {
110 initializeLICMPass(*PassRegistry::getPassRegistry());
111 }
Devang Patel09f162c2007-05-01 21:15:47 +0000112
Craig Topper3e4c6972014-03-05 09:10:37 +0000113 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000114
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000115 /// This transformation requires natural loop information & requires that
116 /// loop preheaders be inserted into the CFG...
117 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000118 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattner820d9712002-10-21 20:00:28 +0000119 AU.setPreservesCFG();
Chandler Carruth73523022014-01-13 13:07:17 +0000120 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000121 AU.addRequired<LoopInfoWrapperPass>();
Dan Gohmanefd7f9c2010-07-16 17:58:45 +0000122 AU.addRequiredID(LoopSimplifyID);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000123 AU.addPreservedID(LoopSimplifyID);
124 AU.addRequiredID(LCSSAID);
125 AU.addPreservedID(LCSSAID);
Chandler Carruth7b560d42015-09-09 17:55:00 +0000126 AU.addRequired<AAResultsWrapperPass>();
127 AU.addPreserved<AAResultsWrapperPass>();
128 AU.addPreserved<BasicAAWrapperPass>();
129 AU.addPreserved<GlobalsAAWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000130 AU.addPreserved<ScalarEvolutionWrapperPass>();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000131 AU.addPreserved<SCEVAAWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000132 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chris Lattner6ec05f52002-05-10 22:44:58 +0000133 }
134
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000135 using llvm::Pass::doFinalization;
136
Craig Topper3e4c6972014-03-05 09:10:37 +0000137 bool doFinalization() override {
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000138 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
Devang Patel69730c92007-03-07 04:41:30 +0000139 return false;
140 }
141
Chris Lattner6ec05f52002-05-10 22:44:58 +0000142 private:
Chris Lattner45d67d62003-02-24 03:52:32 +0000143 AliasAnalysis *AA; // Current AliasAnalysis information
Chris Lattnerc0517682003-12-09 17:18:00 +0000144 LoopInfo *LI; // Current LoopInfo
Chris Lattnerabe61ef2010-08-29 06:49:44 +0000145 DominatorTree *DT; // Dominator Tree for the current Loop.
Chris Lattnerc0517682003-12-09 17:18:00 +0000146
Chad Rosier43a33062011-12-02 01:26:24 +0000147 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding.
148
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000149 // State that is updated as we process loops.
Chris Lattner45d67d62003-02-24 03:52:32 +0000150 bool Changed; // Set to true when we change anything.
151 BasicBlock *Preheader; // The preheader block of the current loop...
152 Loop *CurLoop; // The current loop we are working on...
Chris Lattner0592bb72003-03-03 23:32:45 +0000153 AliasSetTracker *CurAST; // AliasSet information for the current loop...
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000154 DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000155
Devang Patelb98a0972007-07-31 08:01:41 +0000156 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
Craig Topper3e4c6972014-03-05 09:10:37 +0000157 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
158 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000159
160 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
161 /// set.
Craig Topper3e4c6972014-03-05 09:10:37 +0000162 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000163
David Peixotto0d4d5e62014-09-24 16:48:31 +0000164 /// Simple Analysis hook. Delete loop L from alias set map.
165 void deleteAnalysisLoop(Loop *L) override;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000166 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000167}
Chris Lattner6ec05f52002-05-10 22:44:58 +0000168
Dan Gohmand78c4002008-05-13 00:00:25 +0000169char LICM::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000170INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000171INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000172INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000173INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000174INITIALIZE_PASS_DEPENDENCY(LCSSA)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000175INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000176INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000177INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
178INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
179INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
180INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000181INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000182
Daniel Dunbar7f39e2d2008-10-22 23:32:42 +0000183Pass *llvm::createLICMPass() { return new LICM(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000184
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000185/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000186/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000187/// times on one loop.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000188///
Devang Patel69730c92007-03-07 04:41:30 +0000189bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000190 if (skipOptnoneFunction(L))
191 return false;
192
Chris Lattner45d67d62003-02-24 03:52:32 +0000193 Changed = false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000194
Chris Lattner45d67d62003-02-24 03:52:32 +0000195 // Get our Loop and Alias Analysis information...
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000196 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000197 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth73523022014-01-13 13:07:17 +0000198 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnera51fa882002-08-22 21:39:55 +0000199
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000200 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +0000201
Chandler Carruthfc258542014-02-11 12:52:27 +0000202 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
203
Devang Patel69730c92007-03-07 04:41:30 +0000204 CurAST = new AliasSetTracker(*AA);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000205 // Collect Alias info from subloops.
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000206 for (Loop *InnerL : L->getSubLoops()) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000207 AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
208 assert(InnerAST && "Where is my AST?");
Devang Patel69730c92007-03-07 04:41:30 +0000209
210 // What if InnerLoop was modified by other passes ?
211 CurAST->add(*InnerAST);
Tobias Grossera3928f52011-07-06 19:20:02 +0000212
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000213 // Once we've incorporated the inner loop's AST into ours, we don't need the
214 // subloop's anymore.
215 delete InnerAST;
216 LoopToAliasSetMap.erase(InnerL);
Chris Lattner45d67d62003-02-24 03:52:32 +0000217 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000218
Chris Lattner6ec05f52002-05-10 22:44:58 +0000219 CurLoop = L;
220
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000221 // Get the preheader block to move instructions into...
222 Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000223
Chris Lattner45d67d62003-02-24 03:52:32 +0000224 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chris Lattner0592bb72003-03-03 23:32:45 +0000225 // Because subloops have already been incorporated into AST, we skip blocks in
Chris Lattner45d67d62003-02-24 03:52:32 +0000226 // subloops.
227 //
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000228 for (BasicBlock *BB : L->blocks()) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000229 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
Dan Gohman90071072008-06-22 20:18:58 +0000230 CurAST->add(*BB); // Incorporate the specified basic block
231 }
Chris Lattner45d67d62003-02-24 03:52:32 +0000232
Hal Finkel3d4269a2015-02-22 18:35:32 +0000233 // Compute loop safety information.
234 LICMSafetyInfo SafetyInfo;
235 computeLICMSafetyInfo(&SafetyInfo, CurLoop);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000236
Chris Lattner6ec05f52002-05-10 22:44:58 +0000237 // We want to visit all of the instructions in this loop... that are not parts
238 // of our subloops (they have already had their invariants hoisted out of
239 // their loop, into this loop, so there is no need to process the BODIES of
240 // the subloops).
241 //
Chris Lattner64437692002-09-29 21:46:09 +0000242 // Traverse the body of the loop in depth first order on the dominator tree so
243 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000244 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000245 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000246 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000247 if (L->hasDedicatedExits())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000248 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, CurLoop,
249 CurAST, &SafetyInfo);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000250 if (Preheader)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000251 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI,
Hal Finkel3d4269a2015-02-22 18:35:32 +0000252 CurLoop, CurAST, &SafetyInfo);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000253
Chris Lattner45d67d62003-02-24 03:52:32 +0000254 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000255 // memory references to scalars that we can.
Chandler Carruthcc497b62014-01-24 02:24:47 +0000256 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
Dan Gohmanb9487362012-08-08 00:00:26 +0000257 SmallVector<BasicBlock *, 8> ExitBlocks;
258 SmallVector<Instruction *, 8> InsertPts;
Chandler Carruthfc258542014-02-11 12:52:27 +0000259 PredIteratorCache PIC;
Dan Gohmanb9487362012-08-08 00:00:26 +0000260
Chris Lattner1dc98b42010-08-29 06:43:52 +0000261 // Loop over all of the alias sets in the tracker object.
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000262 for (AliasSet &AS : *CurAST)
263 Changed |= promoteLoopAccessesToScalars(AS, ExitBlocks, InsertPts,
Hal Finkel3d4269a2015-02-22 18:35:32 +0000264 PIC, LI, DT, CurLoop,
265 CurAST, &SafetyInfo);
Chandler Carruth16651522014-02-01 13:35:14 +0000266
267 // Once we have promoted values across the loop body we have to recursively
268 // reform LCSSA as any nested loop may now have values defined within the
269 // loop used in the outer loop.
270 // FIXME: This is really heavy handed. It would be a bit better to use an
271 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
272 // it as it went.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000273 if (Changed) {
274 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
275 formLCSSARecursively(*L, *DT, LI, SEWP ? &SEWP->getSE() : nullptr);
276 }
Chris Lattner1dc98b42010-08-29 06:43:52 +0000277 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000278
Chandler Carruthfc258542014-02-11 12:52:27 +0000279 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
280 // specifically moving instructions across the loop boundary and so it is
281 // especially in need of sanity checking here.
282 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
283 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
284 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000285
Chris Lattner6ec05f52002-05-10 22:44:58 +0000286 // Clear out loops state information for the next iteration
Craig Topperf40110f2014-04-25 05:29:35 +0000287 CurLoop = nullptr;
288 Preheader = nullptr;
Devang Patel69730c92007-03-07 04:41:30 +0000289
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000290 // If this loop is nested inside of another one, save the alias information
291 // for when we process the outer loop.
292 if (L->getParentLoop())
293 LoopToAliasSetMap[L] = CurAST;
294 else
295 delete CurAST;
Devang Patel69730c92007-03-07 04:41:30 +0000296 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000297}
298
Hal Finkel3d4269a2015-02-22 18:35:32 +0000299/// Walk the specified region of the CFG (defined by all blocks dominated by
300/// the specified block, and that are in the current loop) in reverse depth
301/// first order w.r.t the DominatorTree. This allows us to visit uses before
302/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000303///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000304bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
305 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
306 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Chris Lattner547192d62003-12-19 07:22:45 +0000307
Hal Finkel3d4269a2015-02-22 18:35:32 +0000308 // Verify inputs.
309 assert(N != nullptr && AA != nullptr && LI != nullptr &&
310 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
311 SafetyInfo != nullptr && "Unexpected input to sinkRegion");
312
Hal Finkel3d4269a2015-02-22 18:35:32 +0000313 BasicBlock *BB = N->getBlock();
Chris Lattner547192d62003-12-19 07:22:45 +0000314 // If this subregion is not in the top level loop at all, exit.
Sanjay Patel99133222016-01-13 23:01:57 +0000315 if (!CurLoop->contains(BB)) return false;
Chris Lattner547192d62003-12-19 07:22:45 +0000316
Chris Lattner263f8042010-08-29 18:22:25 +0000317 // We are processing blocks in reverse dfo, so process children first.
Sanjay Patel99133222016-01-13 23:01:57 +0000318 bool Changed = false;
Devang Patelbdd1aae2007-06-04 00:32:22 +0000319 const std::vector<DomTreeNode*> &Children = N->getChildren();
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000320 for (DomTreeNode *Child : Children)
321 Changed |= sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
322
Chris Lattner547192d62003-12-19 07:22:45 +0000323 // Only need to process the contents of this block if it is not part of a
324 // subloop (which would already have been processed).
Hal Finkel3d4269a2015-02-22 18:35:32 +0000325 if (inSubLoop(BB,CurLoop,LI)) return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000326
Chris Lattner91846012003-12-19 08:18:16 +0000327 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
328 Instruction &I = *--II;
Tobias Grossera3928f52011-07-06 19:20:02 +0000329
Chris Lattner263f8042010-08-29 18:22:25 +0000330 // If the instruction is dead, we would try to sink it because it isn't used
331 // in the loop, instead, just delete it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000332 if (isInstructionTriviallyDead(&I, TLI)) {
Chris Lattnerf58382e2010-08-29 18:42:23 +0000333 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
Chris Lattner263f8042010-08-29 18:22:25 +0000334 ++II;
335 CurAST->deleteValue(&I);
336 I.eraseFromParent();
337 Changed = true;
338 continue;
339 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000340
Chris Lattner547192d62003-12-19 07:22:45 +0000341 // Check to see if we can sink this instruction to the exit blocks
342 // of the loop. We can do this if the all users of the instruction are
343 // outside of the loop. In this case, it doesn't even matter if the
344 // operands of the instruction are loop invariant.
345 //
David Majnemer42a07302016-01-04 03:37:39 +0000346 if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000347 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) {
Chris Lattner91846012003-12-19 08:18:16 +0000348 ++II;
David Majnemer42a07302016-01-04 03:37:39 +0000349 Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo);
Chris Lattner91846012003-12-19 08:18:16 +0000350 }
Chris Lattner547192d62003-12-19 07:22:45 +0000351 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000352 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000353}
354
Hal Finkel3d4269a2015-02-22 18:35:32 +0000355/// Walk the specified region of the CFG (defined by all blocks dominated by
356/// the specified block, and that are in the current loop) in depth first
357/// order w.r.t the DominatorTree. This allows us to visit definitions before
358/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000359///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000360bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
361 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
362 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000363 // Verify inputs.
364 assert(N != nullptr && AA != nullptr && LI != nullptr &&
365 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
366 SafetyInfo != nullptr && "Unexpected input to hoistRegion");
Sanjay Patel99133222016-01-13 23:01:57 +0000367
Owen Andersonc24701e2007-04-24 06:40:39 +0000368 BasicBlock *BB = N->getBlock();
Sanjay Patel99133222016-01-13 23:01:57 +0000369
Chris Lattner05e86302002-09-29 22:26:07 +0000370 // If this subregion is not in the top level loop at all, exit.
Sanjay Patel99133222016-01-13 23:01:57 +0000371 if (!CurLoop->contains(BB)) return false;
372
Chris Lattneraaaea512003-12-10 06:41:05 +0000373 // Only need to process the contents of this block if it is not part of a
374 // subloop (which would already have been processed).
Sanjay Patel99133222016-01-13 23:01:57 +0000375 bool Changed = false;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000376 if (!inSubLoop(BB, CurLoop, LI))
Chris Lattneraaaea512003-12-10 06:41:05 +0000377 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
378 Instruction &I = *II++;
Chris Lattner030f0202010-08-31 23:00:16 +0000379 // Try constant folding this instruction. If all the operands are
380 // constants, it is technically hoistable, but it would be better to just
381 // fold it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000382 if (Constant *C = ConstantFoldInstruction(
383 &I, I.getModule()->getDataLayout(), TLI)) {
Chris Lattner030f0202010-08-31 23:00:16 +0000384 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
385 CurAST->copyValue(&I, C);
386 CurAST->deleteValue(&I);
387 I.replaceAllUsesWith(C);
388 I.eraseFromParent();
389 continue;
390 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000391
Chris Lattner547192d62003-12-19 07:22:45 +0000392 // Try hoisting the instruction out to the preheader. We can only do this
393 // if all of the operands of the instruction are loop invariant and if it
394 // is safe to hoist the instruction.
395 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000396 if (CurLoop->hasLoopInvariantOperands(&I) &&
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000397 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) &&
Philip Reamesb47b9c22015-05-22 02:14:05 +0000398 isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
399 CurLoop->getLoopPreheader()->getTerminator()))
Hal Finkel3d4269a2015-02-22 18:35:32 +0000400 Changed |= hoist(I, CurLoop->getLoopPreheader());
Chris Lattner030f0202010-08-31 23:00:16 +0000401 }
Chris Lattner64437692002-09-29 21:46:09 +0000402
Devang Patelbdd1aae2007-06-04 00:32:22 +0000403 const std::vector<DomTreeNode*> &Children = N->getChildren();
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000404 for (DomTreeNode *Child : Children)
405 Changed |= hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000406 return Changed;
407}
408
409/// Computes loop safety information, checks loop body & header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000410/// for the possibility of may throw exception.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000411///
412void llvm::computeLICMSafetyInfo(LICMSafetyInfo * SafetyInfo, Loop * CurLoop) {
413 assert(CurLoop != nullptr && "CurLoop cant be null");
414 BasicBlock *Header = CurLoop->getHeader();
415 // Setting default safety values.
416 SafetyInfo->MayThrow = false;
417 SafetyInfo->HeaderMayThrow = false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000418 // Iterate over header and compute safety info.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000419 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
420 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
421 SafetyInfo->HeaderMayThrow |= I->mayThrow();
422
423 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
424 // Iterate over loop instructions and compute safety info.
425 for (Loop::block_iterator BB = CurLoop->block_begin(),
426 BBE = CurLoop->block_end(); (BB != BBE) && !SafetyInfo->MayThrow ; ++BB)
427 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
428 (I != E) && !SafetyInfo->MayThrow; ++I)
429 SafetyInfo->MayThrow |= I->mayThrow();
David Majnemer42a07302016-01-04 03:37:39 +0000430
431 // Compute funclet colors if we might sink/hoist in a function with a funclet
432 // personality routine.
433 Function *Fn = CurLoop->getHeader()->getParent();
434 if (Fn->hasPersonalityFn())
435 if (Constant *PersonalityFn = Fn->getPersonalityFn())
436 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
437 SafetyInfo->BlockColors = colorEHFunclets(*Fn);
Chris Lattner64437692002-09-29 21:46:09 +0000438}
439
Chris Lattneraaaea512003-12-10 06:41:05 +0000440/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
441/// instruction.
442///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000443bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000444 TargetLibraryInfo *TLI, Loop *CurLoop,
445 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Chris Lattner65c11932003-12-09 19:32:44 +0000446 // Loads have extra constraints we have to verify before we can hoist them.
447 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000448 if (!LI->isUnordered())
449 return false; // Don't hoist volatile/atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000450
Chris Lattner8a8fb902008-07-23 05:06:28 +0000451 // Loads from constant memory are always safe to move, even if they end up
452 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000453 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000454 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000455 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000456 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000457
Chris Lattner65c11932003-12-09 19:32:44 +0000458 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000459 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000460 if (LI->getType()->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000461 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000462
463 AAMDNodes AAInfo;
464 LI->getAAMetadata(AAInfo);
465
Hal Finkel3d4269a2015-02-22 18:35:32 +0000466 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
Chris Lattner20cda262004-03-15 04:11:30 +0000467 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000468 // Don't sink or hoist dbg info; it's legal, but not useful.
469 if (isa<DbgInfoIntrinsic>(I))
470 return false;
471
David Majnemer42a07302016-01-04 03:37:39 +0000472 // Don't sink calls which can throw.
473 if (CI->mayThrow())
474 return false;
475
Eli Friedman942e1c12011-05-27 18:37:52 +0000476 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000477 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
478 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000479 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000480 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Philip Reames5f994232015-09-21 22:27:59 +0000481 // A readonly argmemonly function only reads from memory pointed to by
482 // it's arguments with arbitrary offsets. If we can prove there are no
483 // writes to this memory in the loop, we can hoist or sink.
484 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
485 for (Value *Op : CI->arg_operands())
486 if (Op->getType()->isPointerTy() &&
487 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
488 AAMDNodes(), CurAST))
489 return false;
490 return true;
491 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000492 // If this call only reads from memory and there are no writes to memory
493 // in the loop, we can hoist or sink the call as appropriate.
494 bool FoundMod = false;
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000495 for (AliasSet &AS : *CurAST) {
Duncan Sands68b6f502007-12-01 07:51:45 +0000496 if (!AS.isForwardingAliasSet() && AS.isMod()) {
497 FoundMod = true;
498 break;
Chris Lattner20cda262004-03-15 04:11:30 +0000499 }
Chris Lattner20cda262004-03-15 04:11:30 +0000500 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000501 if (!FoundMod) return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000502 }
503
Nadav Rotem03dcd852012-09-04 10:25:04 +0000504 // FIXME: This should use mod/ref information to see if we can hoist or
505 // sink the call.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000506
Chris Lattner20cda262004-03-15 04:11:30 +0000507 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000508 }
509
Nadav Rotem03dcd852012-09-04 10:25:04 +0000510 // Only these instructions are hoistable/sinkable.
Benjamin Kramer130fcde2013-01-09 18:12:03 +0000511 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
512 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
513 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
514 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
515 !isa<InsertValueInst>(I))
516 return false;
Nadav Rotem03dcd852012-09-04 10:25:04 +0000517
Philip Reamesb47b9c22015-05-22 02:14:05 +0000518 // TODO: Plumb the context instruction through to make hoisting and sinking
519 // more powerful. Hoisting of loads already works due to the special casing
520 // above.
521 return isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
522 nullptr);
Chris Lattneraaaea512003-12-10 06:41:05 +0000523}
524
Hal Finkel3d4269a2015-02-22 18:35:32 +0000525/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000526/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000527/// This is true when all incoming values are that instruction.
528/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000529///
Pete Cooper47e80cd2015-05-12 20:05:20 +0000530static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000531 for (const Value *IncValue : PN.incoming_values())
532 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000533 return false;
534
535 return true;
536}
537
Hal Finkel3d4269a2015-02-22 18:35:32 +0000538/// Return true if the only users of this instruction are outside of
539/// the loop. If this is true, we can sink the instruction to the exit
540/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000541///
David Majnemer42a07302016-01-04 03:37:39 +0000542static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
543 const LICMSafetyInfo *SafetyInfo) {
544 const auto &BlockColors = SafetyInfo->BlockColors;
Pete Cooper0cabcf22015-05-13 01:12:18 +0000545 for (const User *U : I.users()) {
546 const Instruction *UI = cast<Instruction>(U);
547 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Majnemer42a07302016-01-04 03:37:39 +0000548 const BasicBlock *BB = PN->getParent();
549 // We cannot sink uses in catchswitches.
550 if (isa<CatchSwitchInst>(BB->getTerminator()))
551 return false;
552
553 // We need to sink a callsite to a unique funclet. Avoid sinking if the
554 // phi use is too muddled.
555 if (isa<CallInst>(I))
556 if (!BlockColors.empty() &&
557 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
558 return false;
559
Chandler Carruth8765cf72014-01-25 04:07:24 +0000560 // A PHI node where all of the incoming values are this instruction are
561 // special -- they can just be RAUW'ed with the instruction and thus
562 // don't require a use in the predecessor. This is a particular important
563 // special case because it is the pattern found in LCSSA form.
564 if (isTriviallyReplacablePHI(*PN, I)) {
565 if (CurLoop->contains(PN))
566 return false;
567 else
568 continue;
569 }
570
571 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
572 // values. Check for such a use being inside the loop.
Chris Lattner34399dd2003-12-11 22:23:32 +0000573 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
574 if (PN->getIncomingValue(i) == &I)
575 if (CurLoop->contains(PN->getIncomingBlock(i)))
576 return false;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000577
578 continue;
Chris Lattner34399dd2003-12-11 22:23:32 +0000579 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000580
Chandler Carruthcdf47882014-03-09 03:16:01 +0000581 if (CurLoop->contains(UI))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000582 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000583 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000584 return true;
585}
586
David Majnemer42a07302016-01-04 03:37:39 +0000587static Instruction *
588CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
589 const LoopInfo *LI,
590 const LICMSafetyInfo *SafetyInfo) {
591 Instruction *New;
592 if (auto *CI = dyn_cast<CallInst>(&I)) {
593 const auto &BlockColors = SafetyInfo->BlockColors;
594
595 // Sinking call-sites need to be handled differently from other
596 // instructions. The cloned call-site needs a funclet bundle operand
597 // appropriate for it's location in the CFG.
598 SmallVector<OperandBundleDef, 1> OpBundles;
599 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
600 BundleIdx != BundleEnd; ++BundleIdx) {
601 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
602 if (Bundle.getTagID() == LLVMContext::OB_funclet)
603 continue;
604
605 OpBundles.emplace_back(Bundle);
606 }
607
608 if (!BlockColors.empty()) {
609 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
610 assert(CV.size() == 1 && "non-unique color for exit block!");
611 BasicBlock *BBColor = CV.front();
612 Instruction *EHPad = BBColor->getFirstNonPHI();
613 if (EHPad->isEHPad())
614 OpBundles.emplace_back("funclet", EHPad);
615 }
616
617 New = CallInst::Create(CI, OpBundles);
618 } else {
619 New = I.clone();
620 }
621
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000622 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
623 if (!I.getName().empty()) New->setName(I.getName() + ".le");
624
625 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
626 // particularly cheap because we can rip off the PHI node that we're
627 // replacing for the number and blocks of the predecessors.
628 // OPT: If this shows up in a profile, we can instead finish sinking all
629 // invariant instructions, and then walk their operands to re-establish
630 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
631 // sinking bottom-up.
632 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
633 ++OI)
634 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
635 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
636 if (!OLoop->contains(&PN)) {
637 PHINode *OpPN =
638 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000639 OInst->getName() + ".lcssa", &ExitBlock.front());
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000640 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
641 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
642 *OI = OpPN;
643 }
644 return New;
645}
646
Hal Finkel3d4269a2015-02-22 18:35:32 +0000647/// When an instruction is found to only be used outside of the loop, this
648/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000649/// This method is guaranteed to remove the original instruction from its
650/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000651///
Pete Cooper0cabcf22015-05-13 01:12:18 +0000652static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +0000653 const Loop *CurLoop, AliasSetTracker *CurAST,
654 const LICMSafetyInfo *SafetyInfo) {
Nick Lewycky299c6df2010-07-30 20:27:01 +0000655 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000656 bool Changed = false;
Chris Lattner55c21132003-12-10 20:43:29 +0000657 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000658 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000659 ++NumSunk;
660 Changed = true;
661
Chandler Carruthfc258542014-02-11 12:52:27 +0000662#ifndef NDEBUG
663 SmallVector<BasicBlock *, 32> ExitBlocks;
664 CurLoop->getUniqueExitBlocks(ExitBlocks);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000665 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
666 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +0000667#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +0000668
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000669 // Clones of this instruction. Don't create more than one per exit block!
670 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
671
Chandler Carruthfc258542014-02-11 12:52:27 +0000672 // If this instruction is only used outside of the loop, then all users are
673 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
674 // the instruction.
675 while (!I.use_empty()) {
David Majnemer6bc83e02015-07-12 03:53:05 +0000676 Value::user_iterator UI = I.user_begin();
677 auto *User = cast<Instruction>(*UI);
David Majnemer49428102014-09-02 16:22:00 +0000678 if (!DT->isReachableFromEntry(User->getParent())) {
679 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
680 continue;
681 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000682 // The user must be a PHI node.
David Majnemer49428102014-09-02 16:22:00 +0000683 PHINode *PN = cast<PHINode>(User);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000684
David Majnemer6bc83e02015-07-12 03:53:05 +0000685 // Surprisingly, instructions can be used outside of loops without any
686 // exits. This can only happen in PHI nodes if the incoming block is
687 // unreachable.
688 Use &U = UI.getUse();
689 BasicBlock *BB = PN->getIncomingBlock(U);
690 if (!DT->isReachableFromEntry(BB)) {
691 U = UndefValue::get(I.getType());
692 continue;
693 }
694
Chandler Carruthfc258542014-02-11 12:52:27 +0000695 BasicBlock *ExitBlock = PN->getParent();
696 assert(ExitBlockSet.count(ExitBlock) &&
697 "The LCSSA PHI is not in an exit block!");
698
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000699 Instruction *New;
700 auto It = SunkCopies.find(ExitBlock);
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000701 if (It != SunkCopies.end())
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000702 New = It->second;
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000703 else
704 New = SunkCopies[ExitBlock] =
David Majnemer42a07302016-01-04 03:37:39 +0000705 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo);
Chandler Carruthfc258542014-02-11 12:52:27 +0000706
707 PN->replaceAllUsesWith(New);
708 PN->eraseFromParent();
Chris Lattnercd96b4d2010-08-29 04:28:20 +0000709 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000710
Chris Lattner1a1ed692010-08-29 18:00:00 +0000711 CurAST->deleteValue(&I);
Chandler Carruthfc258542014-02-11 12:52:27 +0000712 I.eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000713 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000714}
Chris Lattner64437692002-09-29 21:46:09 +0000715
Hal Finkel3d4269a2015-02-22 18:35:32 +0000716/// When an instruction is found to only use loop invariant operands that
717/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000718///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000719static bool hoist(Instruction &I, BasicBlock *Preheader) {
David Greene0fd86222010-01-05 01:27:30 +0000720 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
Evan Chengf8158612009-10-12 22:25:23 +0000721 << I << "\n");
Chris Lattner6ac06592010-08-29 18:18:40 +0000722 // Move the new node to the Preheader, before its terminator.
723 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000724
Igor Laevsky7310c682015-11-18 14:50:18 +0000725 // Metadata can be dependent on the condition we are hoisting above.
726 // Conservatively strip all metadata on the instruction.
727 I.dropUnknownNonDebugMetadata();
728
Chris Lattneraaaea512003-12-10 06:41:05 +0000729 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000730 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000731 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000732 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000733}
734
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000735/// Only sink or hoist an instruction if it is not a trapping instruction,
736/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000737/// or if it is a trapping instruction and is guaranteed to execute.
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000738static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000739 const DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000740 const TargetLibraryInfo *TLI,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000741 const Loop *CurLoop,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000742 const LICMSafetyInfo *SafetyInfo,
743 const Instruction *CtxI) {
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000744 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000745 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000746
Hal Finkel3d4269a2015-02-22 18:35:32 +0000747 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
Eli Friedman0cdc1482011-07-20 21:37:47 +0000748}
749
Pete Cooper0cabcf22015-05-13 01:12:18 +0000750static bool isGuaranteedToExecute(const Instruction &Inst,
751 const DominatorTree *DT,
752 const Loop *CurLoop,
753 const LICMSafetyInfo * SafetyInfo) {
Nadav Rotem03dcd852012-09-04 10:25:04 +0000754
Philip Reamesb35f46c2014-12-29 23:00:57 +0000755 // We have to check to make sure that the instruction dominates all
Chris Lattnerc0517682003-12-09 17:18:00 +0000756 // of the exit blocks. If it doesn't, then there is a path out of the loop
757 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000758
Chris Lattnerc0517682003-12-09 17:18:00 +0000759 // If the instruction is in the header block for the loop (which is very
760 // common), it is always guaranteed to dominate the exit blocks. Since this
761 // is a common case, and can save some work, check it now.
Chris Lattneraaaea512003-12-10 06:41:05 +0000762 if (Inst.getParent() == CurLoop->getHeader())
Philip Reamesb35f46c2014-12-29 23:00:57 +0000763 // If there's a throw in the header block, we can't guarantee we'll reach
764 // Inst.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000765 return !SafetyInfo->HeaderMayThrow;
Philip Reamesb35f46c2014-12-29 23:00:57 +0000766
767 // Somewhere in this loop there is an instruction which may throw and make us
768 // exit the loop.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000769 if (SafetyInfo->MayThrow)
Philip Reamesb35f46c2014-12-29 23:00:57 +0000770 return false;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000771
Chris Lattnerc0517682003-12-09 17:18:00 +0000772 // Get the exit blocks for the current loop.
Devang Patelb5933bb2007-08-21 00:31:24 +0000773 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner35eaa552004-04-18 22:15:13 +0000774 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerc0517682003-12-09 17:18:00 +0000775
Chris Lattner27497ec2011-01-02 18:45:39 +0000776 // Verify that the block dominates each of the exit blocks of the loop.
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000777 for (BasicBlock *ExitBlock : ExitBlocks)
778 if (!DT->dominates(Inst.getParent(), ExitBlock))
Chris Lattneraaaea512003-12-10 06:41:05 +0000779 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000780
Nick Lewycky78ee67e2012-05-01 04:03:01 +0000781 // As a degenerate case, if the loop is statically infinite then we haven't
782 // proven anything since there are no exit blocks.
783 if (ExitBlocks.empty())
784 return false;
785
Tanya Lattner57c03df2003-08-05 18:45:46 +0000786 return true;
787}
788
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000789namespace {
790 class LoopPromoter : public LoadAndStorePromoter {
791 Value *SomePtr; // Designated pointer to store to.
Craig Topper71b7b682014-08-21 05:55:13 +0000792 SmallPtrSetImpl<Value*> &PointerMustAliases;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000793 SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
Dan Gohmanb9487362012-08-08 00:00:26 +0000794 SmallVectorImpl<Instruction*> &LoopInsertPts;
Chandler Carruthfc258542014-02-11 12:52:27 +0000795 PredIteratorCache &PredCache;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000796 AliasSetTracker &AST;
Chandler Carruthfc258542014-02-11 12:52:27 +0000797 LoopInfo &LI;
Eli Friedmanddf7f552011-05-27 20:31:51 +0000798 DebugLoc DL;
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000799 int Alignment;
Hal Finkelcc39b672014-07-24 12:16:19 +0000800 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +0000801
802 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
803 if (Instruction *I = dyn_cast<Instruction>(V))
804 if (Loop *L = LI.getLoopFor(I->getParent()))
805 if (!L->contains(BB)) {
806 // We need to create an LCSSA PHI node for the incoming value and
807 // store that.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000808 PHINode *PN =
809 PHINode::Create(I->getType(), PredCache.size(BB),
810 I->getName() + ".lcssa", &BB->front());
Daniel Berlinb4e7a4a2015-04-21 21:11:50 +0000811 for (BasicBlock *Pred : PredCache.get(BB))
812 PN->addIncoming(I, Pred);
Chandler Carruthfc258542014-02-11 12:52:27 +0000813 return PN;
814 }
815 return V;
816 }
817
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000818 public:
Pete Cooper41e0ee32015-05-13 01:12:16 +0000819 LoopPromoter(Value *SP,
820 ArrayRef<const Instruction *> Insts,
Craig Topper71b7b682014-08-21 05:55:13 +0000821 SSAUpdater &S, SmallPtrSetImpl<Value *> &PMA,
Chandler Carruthfc258542014-02-11 12:52:27 +0000822 SmallVectorImpl<BasicBlock *> &LEB,
823 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
824 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
Hal Finkelcc39b672014-07-24 12:16:19 +0000825 const AAMDNodes &AATags)
Chandler Carruthfc258542014-02-11 12:52:27 +0000826 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
827 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Hal Finkelcc39b672014-07-24 12:16:19 +0000828 LI(li), DL(dl), Alignment(alignment), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +0000829
Craig Topper3e4c6972014-03-05 09:10:37 +0000830 bool isInstInList(Instruction *I,
831 const SmallVectorImpl<Instruction*> &) const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000832 Value *Ptr;
833 if (LoadInst *LI = dyn_cast<LoadInst>(I))
834 Ptr = LI->getOperand(0);
835 else
836 Ptr = cast<StoreInst>(I)->getPointerOperand();
837 return PointerMustAliases.count(Ptr);
838 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000839
Craig Topper3e4c6972014-03-05 09:10:37 +0000840 void doExtraRewritesBeforeFinalDeletion() const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000841 // Insert stores after in the loop exit blocks. Each exit block gets a
842 // store of the live-out values that feed them. Since we've already told
843 // the SSA updater about the defs in the loop and the preheader
844 // definition, it is all set and we can start using it.
845 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
846 BasicBlock *ExitBlock = LoopExitBlocks[i];
847 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
Chandler Carruthfc258542014-02-11 12:52:27 +0000848 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
849 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
Dan Gohmanb9487362012-08-08 00:00:26 +0000850 Instruction *InsertPos = LoopInsertPts[i];
Chandler Carruthfc258542014-02-11 12:52:27 +0000851 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000852 NewSI->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +0000853 NewSI->setDebugLoc(DL);
Hal Finkelcc39b672014-07-24 12:16:19 +0000854 if (AATags) NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000855 }
856 }
857
Craig Topper3e4c6972014-03-05 09:10:37 +0000858 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000859 // Update alias analysis.
860 AST.copyValue(LI, V);
861 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000862 void instructionDeleted(Instruction *I) const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000863 AST.deleteValue(I);
864 }
865 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000866} // end anon namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000867
Hal Finkel3d4269a2015-02-22 18:35:32 +0000868/// Try to promote memory values to scalars by sinking stores out of the
869/// loop and moving loads to before the loop. We do this by looping over
870/// the stores in the loop, looking for stores to Must pointers which are
871/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +0000872///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000873bool llvm::promoteLoopAccessesToScalars(AliasSet &AS,
874 SmallVectorImpl<BasicBlock*>&ExitBlocks,
875 SmallVectorImpl<Instruction*>&InsertPts,
876 PredIteratorCache &PIC, LoopInfo *LI,
877 DominatorTree *DT, Loop *CurLoop,
878 AliasSetTracker *CurAST,
879 LICMSafetyInfo * SafetyInfo) {
880 // Verify inputs.
881 assert(LI != nullptr && DT != nullptr &&
882 CurLoop != nullptr && CurAST != nullptr &&
883 SafetyInfo != nullptr &&
884 "Unexpected Input to promoteLoopAccessesToScalars");
Sanjay Patel99133222016-01-13 23:01:57 +0000885
Chris Lattner1dc98b42010-08-29 06:43:52 +0000886 // We can promote this alias set if it has a store, if it is a "Must" alias
887 // set, if the pointer is loop invariant, and if we are not eliminating any
888 // volatile loads or stores.
889 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
890 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
Sanjay Patel99133222016-01-13 23:01:57 +0000891 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +0000892
Chris Lattner1dc98b42010-08-29 06:43:52 +0000893 assert(!AS.empty() &&
894 "Must alias set should have at least one pointer element in it!");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000895
Chris Lattner1dc98b42010-08-29 06:43:52 +0000896 Value *SomePtr = AS.begin()->getValue();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000897 BasicBlock * Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +0000898
Chris Lattner1dc98b42010-08-29 06:43:52 +0000899 // It isn't safe to promote a load/store from the loop if the load/store is
900 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +0000901 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000902 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +0000903 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000904 // into:
905 //
906 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
907 //
908 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +0000909 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000910 // It is safe to promote P if all uses are direct load/stores and if at
911 // least one is guaranteed to be executed.
912 bool GuaranteedToExecute = false;
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000913
Chris Lattner1dc98b42010-08-29 06:43:52 +0000914 SmallVector<Instruction*, 64> LoopUses;
915 SmallPtrSet<Value*, 4> PointerMustAliases;
Chris Lattner45d67d62003-02-24 03:52:32 +0000916
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000917 // We start with an alignment of one and try to find instructions that allow
918 // us to prove better alignment.
919 unsigned Alignment = 1;
Hal Finkelcc39b672014-07-24 12:16:19 +0000920 AAMDNodes AATags;
Bruno Cardoso Lopes46d5bf22014-11-28 19:47:46 +0000921 bool HasDedicatedExits = CurLoop->hasDedicatedExits();
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000922
Chris Lattner1dc98b42010-08-29 06:43:52 +0000923 // Check that all of the pointers in the alias set have the same type. We
924 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +0000925 // different sizes. While we are at it, collect alignment and AA info.
Sanjay Patel99133222016-01-13 23:01:57 +0000926 bool Changed = false;
Chris Lattner1dc98b42010-08-29 06:43:52 +0000927 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
928 Value *ASIV = ASI->getValue();
929 PointerMustAliases.insert(ASIV);
Tobias Grossera3928f52011-07-06 19:20:02 +0000930
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000931 // Check that all of the pointers in the alias set have the same type. We
932 // cannot (yet) promote a memory location that is loaded and stored in
933 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +0000934 if (SomePtr->getType() != ASIV->getType())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000935 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000936
Chandler Carruthcdf47882014-03-09 03:16:01 +0000937 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +0000938 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000939 Instruction *UI = dyn_cast<Instruction>(U);
940 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000941 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +0000942
Chris Lattner1dc98b42010-08-29 06:43:52 +0000943 // If there is an non-load/store instruction in the loop, we can't promote
944 // it.
Sanjay Patel9f49b682016-01-08 22:05:03 +0000945 if (const LoadInst *Load = dyn_cast<LoadInst>(UI)) {
946 assert(!Load->isVolatile() && "AST broken");
947 if (!Load->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000948 return Changed;
Sanjay Patel9f49b682016-01-08 22:05:03 +0000949 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +0000950 // Stores *of* the pointer are not interesting, only stores *to* the
951 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000952 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +0000953 continue;
Sanjay Patel9f49b682016-01-08 22:05:03 +0000954 assert(!Store->isVolatile() && "AST broken");
955 if (!Store->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000956 return Changed;
Bruno Cardoso Lopes46d5bf22014-11-28 19:47:46 +0000957 // Don't sink stores from loops without dedicated block exits. Exits
958 // containing indirect branches are not transformed by loop simplify,
Bruno Cardoso Lopesd035fbb2014-12-02 14:22:34 +0000959 // make sure we catch that. An additional load may be generated in the
960 // preheader for SSA updater, so also avoid sinking when no preheader
961 // is available.
962 if (!HasDedicatedExits || !Preheader)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000963 return Changed;
Eli Friedman0cdc1482011-07-20 21:37:47 +0000964
965 // Note that we only check GuaranteedToExecute inside the store case
966 // so that we do not introduce stores where they did not exist before
967 // (which would break the LLVM concurrency model).
968
969 // If the alignment of this instruction allows us to specify a more
970 // restrictive (and performant) alignment and if we are sure this
971 // instruction will be executed, update the alignment.
972 // Larger is better, with the exception of 0 being the best alignment.
Sanjay Patel9f49b682016-01-08 22:05:03 +0000973 unsigned InstAlignment = Store->getAlignment();
Chris Lattnerf5cca682012-12-31 08:37:17 +0000974 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000975 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Eli Friedman0cdc1482011-07-20 21:37:47 +0000976 GuaranteedToExecute = true;
977 Alignment = InstAlignment;
978 }
979
980 if (!GuaranteedToExecute)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000981 GuaranteedToExecute = isGuaranteedToExecute(*UI, DT,
982 CurLoop, SafetyInfo);
Eli Friedman0cdc1482011-07-20 21:37:47 +0000983
Chris Lattnerbe901902010-09-06 05:11:24 +0000984 } else
Hal Finkel3d4269a2015-02-22 18:35:32 +0000985 return Changed; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000986
Hal Finkelcc39b672014-07-24 12:16:19 +0000987 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +0000988 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +0000989 // On the first load/store, just take its AA tags.
990 UI->getAAMetadata(AATags);
991 } else if (AATags) {
992 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +0000993 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000994
995 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +0000996 }
997 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000998
Chris Lattner1dc98b42010-08-29 06:43:52 +0000999 // If there isn't a guaranteed-to-execute instruction, we can't promote.
1000 if (!GuaranteedToExecute)
Hal Finkel3d4269a2015-02-22 18:35:32 +00001001 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +00001002
David Majnemer219055f2016-01-04 17:42:19 +00001003 // Figure out the loop exits and their insertion points, if this is the
1004 // first promotion.
1005 if (ExitBlocks.empty()) {
1006 CurLoop->getUniqueExitBlocks(ExitBlocks);
1007 InsertPts.clear();
1008 InsertPts.reserve(ExitBlocks.size());
David Majnemerb33f3a22016-01-04 23:16:22 +00001009 for (BasicBlock *ExitBlock : ExitBlocks)
David Majnemer219055f2016-01-04 17:42:19 +00001010 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
David Majnemer219055f2016-01-04 17:42:19 +00001011 }
1012
David Majnemerb33f3a22016-01-04 23:16:22 +00001013 // Can't insert into a catchswitch.
1014 for (BasicBlock *ExitBlock : ExitBlocks)
1015 if (isa<CatchSwitchInst>(ExitBlock->getTerminator()))
1016 return Changed;
1017
Chris Lattner1dc98b42010-08-29 06:43:52 +00001018 // Otherwise, this is safe to promote, lets do it!
Tobias Grossera3928f52011-07-06 19:20:02 +00001019 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
Chris Lattner1dc98b42010-08-29 06:43:52 +00001020 Changed = true;
1021 ++NumPromoted;
1022
Eli Friedmanddf7f552011-05-27 20:31:51 +00001023 // Grab a debug location for the inserted loads/stores; given that the
1024 // inserted loads/stores have little relation to the original loads/stores,
1025 // this code just arbitrarily picks a location from one, since any debug
1026 // location is better than none.
1027 DebugLoc DL = LoopUses[0]->getDebugLoc();
1028
Chris Lattner1dc98b42010-08-29 06:43:52 +00001029 // We use the SSAUpdater interface to insert phi nodes as required.
1030 SmallVector<PHINode*, 16> NewPHIs;
1031 SSAUpdater SSA(&NewPHIs);
Pete Cooper7c4d7b82015-05-13 22:43:09 +00001032 LoopPromoter Promoter(SomePtr, LoopUses, SSA,
Pete Cooper41e0ee32015-05-13 01:12:16 +00001033 PointerMustAliases, ExitBlocks,
Hal Finkelcc39b672014-07-24 12:16:19 +00001034 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +00001035
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001036 // Set up the preheader to have a definition of the value. It is the live-out
1037 // value from the preheader that uses in the loop will use.
1038 LoadInst *PreheaderLoad =
1039 new LoadInst(SomePtr, SomePtr->getName()+".promoted",
1040 Preheader->getTerminator());
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001041 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +00001042 PreheaderLoad->setDebugLoc(DL);
Hal Finkelcc39b672014-07-24 12:16:19 +00001043 if (AATags) PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001044 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1045
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001046 // Rewrite all the loads in the loop and remember all the definitions from
1047 // stores in the loop.
1048 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +00001049
1050 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1051 if (PreheaderLoad->use_empty())
1052 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +00001053
1054 return Changed;
Chris Lattnera51fa882002-08-22 21:39:55 +00001055}
Devang Patelb98a0972007-07-31 08:01:41 +00001056
Ashutosh Nema47802622015-08-13 11:18:35 +00001057/// Simple analysis hook. Clone alias set info.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001058///
Devang Patelb98a0972007-07-31 08:01:41 +00001059void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +00001060 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001061 if (!AST)
1062 return;
1063
1064 AST->copyValue(From, To);
1065}
1066
Hal Finkel3d4269a2015-02-22 18:35:32 +00001067/// Simple Analysis hook. Delete value V from alias set
1068///
Devang Patelb98a0972007-07-31 08:01:41 +00001069void LICM::deleteAnalysisValue(Value *V, Loop *L) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +00001070 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001071 if (!AST)
1072 return;
1073
1074 AST->deleteValue(V);
1075}
David Peixotto0d4d5e62014-09-24 16:48:31 +00001076
1077/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001078///
David Peixotto0d4d5e62014-09-24 16:48:31 +00001079void LICM::deleteAnalysisLoop(Loop *L) {
1080 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
1081 if (!AST)
1082 return;
1083
1084 delete AST;
1085 LoopToAliasSetMap.erase(L);
1086}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001087
1088
1089/// Return true if the body of this loop may store into the memory
1090/// location pointed to by V.
1091///
1092static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
1093 const AAMDNodes &AAInfo,
1094 AliasSetTracker *CurAST) {
1095 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1096 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1097}
1098
1099/// Little predicate that returns true if the specified basic block is in
1100/// a subloop of the current one, not the current one itself.
1101///
1102static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1103 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1104 return LI->getLoopFor(BB) != CurLoop;
1105}
1106