blob: d2969453dffa713b9d95462f3c79e17a3df3ba01 [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
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/ADT/Statistic.h"
Chris Lattnera51fa882002-08-22 21:39:55 +000034#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0592bb72003-03-03 23:32:45 +000035#include "llvm/Analysis/AliasSetTracker.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000036#include "llvm/Analysis/BasicAliasAnalysis.h"
Philip Reamesb54c8e62016-03-09 22:59:30 +000037#include "llvm/Analysis/CaptureTracking.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"
Philip Reamese0a54542016-03-09 23:07:53 +000040#include "llvm/Analysis/Loads.h"
Chris Lattner030f0202010-08-31 23:00:16 +000041#include "llvm/Analysis/LoopInfo.h"
42#include "llvm/Analysis/LoopPass.h"
Philip Reamesb54c8e62016-03-09 22:59:30 +000043#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruthabfa3e52014-01-24 01:59:49 +000044#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000045#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000046#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000047#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000048#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/Constants.h"
50#include "llvm/IR/DataLayout.h"
51#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000052#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/Instructions.h"
54#include "llvm/IR/IntrinsicInst.h"
55#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000056#include "llvm/IR/Metadata.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000057#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000058#include "llvm/Support/CommandLine.h"
59#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include "llvm/Support/raw_ostream.h"
Dehao Chend55bc4c2016-05-05 00:54:54 +000061#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000062#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000063#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000064#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000065#include <algorithm>
Chris Lattnerc0517682003-12-09 17:18:00 +000066using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000067
Chandler Carruth964daaa2014-04-22 02:55:47 +000068#define DEBUG_TYPE "licm"
69
Dehao Chend55bc4c2016-05-05 00:54:54 +000070STATISTIC(NumSunk, "Number of instructions sunk out of loop");
71STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
Chris Lattner79a42ac2006-12-19 21:40:18 +000072STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
73STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
Dehao Chend55bc4c2016-05-05 00:54:54 +000074STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
Chris Lattner79a42ac2006-12-19 21:40:18 +000075
Dan Gohmand78c4002008-05-13 00:00:25 +000076static cl::opt<bool>
Dehao Chend55bc4c2016-05-05 00:54:54 +000077 DisablePromotion("disable-licm-promotion", cl::Hidden,
78 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000079
Hal Finkel3d4269a2015-02-22 18:35:32 +000080static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
David Majnemer42a07302016-01-04 03:37:39 +000081static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
82 const LICMSafetyInfo *SafetyInfo);
Sanjoy Das7a2e2be2016-01-28 15:51:58 +000083static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
84 const LICMSafetyInfo *SafetyInfo);
Pete Cooper0cabcf22015-05-13 01:12:18 +000085static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +000086 const Loop *CurLoop, AliasSetTracker *CurAST,
87 const LICMSafetyInfo *SafetyInfo);
Pete Cooper0cabcf22015-05-13 01:12:18 +000088static bool isGuaranteedToExecute(const Instruction &Inst,
Dehao Chend55bc4c2016-05-05 00:54:54 +000089 const DominatorTree *DT, const Loop *CurLoop,
Pete Cooper0cabcf22015-05-13 01:12:18 +000090 const LICMSafetyInfo *SafetyInfo);
91static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
92 const DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +000093 const TargetLibraryInfo *TLI,
Pete Cooper0cabcf22015-05-13 01:12:18 +000094 const Loop *CurLoop,
Philip Reamesb47b9c22015-05-22 02:14:05 +000095 const LICMSafetyInfo *SafetyInfo,
96 const Instruction *CtxI = nullptr);
Hal Finkel3d4269a2015-02-22 18:35:32 +000097static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +000098 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +000099 AliasSetTracker *CurAST);
David Majnemer42a07302016-01-04 03:37:39 +0000100static Instruction *
101CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
102 const LoopInfo *LI,
103 const LICMSafetyInfo *SafetyInfo);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000104static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000105 DominatorTree *DT, TargetLibraryInfo *TLI,
106 Loop *CurLoop, AliasSetTracker *CurAST,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000107 LICMSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000108
Dan Gohmand78c4002008-05-13 00:00:25 +0000109namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +0000110struct LICM : public LoopPass {
111 static char ID; // Pass identification, replacement for typeid
112 LICM() : LoopPass(ID) {
113 initializeLICMPass(*PassRegistry::getPassRegistry());
114 }
Devang Patel09f162c2007-05-01 21:15:47 +0000115
Dehao Chend55bc4c2016-05-05 00:54:54 +0000116 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000117
Dehao Chend55bc4c2016-05-05 00:54:54 +0000118 /// This transformation requires natural loop information & requires that
119 /// loop preheaders be inserted into the CFG...
120 ///
121 void getAnalysisUsage(AnalysisUsage &AU) const override {
122 AU.setPreservesCFG();
123 AU.addRequired<TargetLibraryInfoWrapperPass>();
124 getLoopAnalysisUsage(AU);
125 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000126
Dehao Chend55bc4c2016-05-05 00:54:54 +0000127 using llvm::Pass::doFinalization;
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000128
Dehao Chend55bc4c2016-05-05 00:54:54 +0000129 bool doFinalization() override {
130 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
131 return false;
132 }
Devang Patel69730c92007-03-07 04:41:30 +0000133
Dehao Chend55bc4c2016-05-05 00:54:54 +0000134private:
135 AliasAnalysis *AA; // Current AliasAnalysis information
136 LoopInfo *LI; // Current LoopInfo
137 DominatorTree *DT; // Dominator Tree for the current Loop.
Chris Lattnerc0517682003-12-09 17:18:00 +0000138
Dehao Chend55bc4c2016-05-05 00:54:54 +0000139 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding.
Chad Rosier43a33062011-12-02 01:26:24 +0000140
Dehao Chend55bc4c2016-05-05 00:54:54 +0000141 // State that is updated as we process loops.
142 bool Changed; // Set to true when we change anything.
143 BasicBlock *Preheader; // The preheader block of the current loop...
144 Loop *CurLoop; // The current loop we are working on...
145 AliasSetTracker *CurAST; // AliasSet information for the current loop...
146 DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000147
Dehao Chend55bc4c2016-05-05 00:54:54 +0000148 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
149 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
150 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000151
Dehao Chend55bc4c2016-05-05 00:54:54 +0000152 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
153 /// set.
154 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000155
Dehao Chend55bc4c2016-05-05 00:54:54 +0000156 /// Simple Analysis hook. Delete loop L from alias set map.
157 void deleteAnalysisLoop(Loop *L) override;
Roman Gareev036c0882016-02-15 14:48:50 +0000158
Dehao Chend55bc4c2016-05-05 00:54:54 +0000159 AliasSetTracker *collectAliasInfoForLoop(Loop *L);
160};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000161}
Chris Lattner6ec05f52002-05-10 22:44:58 +0000162
Dan Gohmand78c4002008-05-13 00:00:25 +0000163char LICM::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000164INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000165INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000166INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000167INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000168
Daniel Dunbar7f39e2d2008-10-22 23:32:42 +0000169Pass *llvm::createLICMPass() { return new LICM(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000170
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000171/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000172/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000173/// times on one loop.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000174///
Devang Patel69730c92007-03-07 04:41:30 +0000175bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000176 if (skipLoop(L))
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000177 return false;
178
Chris Lattner45d67d62003-02-24 03:52:32 +0000179 Changed = false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000180
Chris Lattner45d67d62003-02-24 03:52:32 +0000181 // Get our Loop and Alias Analysis information...
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000182 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000183 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth73523022014-01-13 13:07:17 +0000184 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnera51fa882002-08-22 21:39:55 +0000185
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000186 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chad Rosier43a33062011-12-02 01:26:24 +0000187
Chandler Carruthfc258542014-02-11 12:52:27 +0000188 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
189
Chandler Carruthad8cb382016-02-27 04:34:07 +0000190 CurAST = collectAliasInfoForLoop(L);
Tobias Grossera3928f52011-07-06 19:20:02 +0000191
Chris Lattner6ec05f52002-05-10 22:44:58 +0000192 CurLoop = L;
193
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000194 // Get the preheader block to move instructions into...
195 Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000196
Hal Finkel3d4269a2015-02-22 18:35:32 +0000197 // Compute loop safety information.
198 LICMSafetyInfo SafetyInfo;
199 computeLICMSafetyInfo(&SafetyInfo, CurLoop);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000200
Chris Lattner6ec05f52002-05-10 22:44:58 +0000201 // We want to visit all of the instructions in this loop... that are not parts
202 // of our subloops (they have already had their invariants hoisted out of
203 // their loop, into this loop, so there is no need to process the BODIES of
204 // the subloops).
205 //
Chris Lattner64437692002-09-29 21:46:09 +0000206 // Traverse the body of the loop in depth first order on the dominator tree so
207 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000208 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000209 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000210 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000211 if (L->hasDedicatedExits())
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000212 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, CurLoop,
213 CurAST, &SafetyInfo);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000214 if (Preheader)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000215 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI,
Hal Finkel3d4269a2015-02-22 18:35:32 +0000216 CurLoop, CurAST, &SafetyInfo);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000217
Chris Lattner45d67d62003-02-24 03:52:32 +0000218 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000219 // memory references to scalars that we can.
Chandler Carruthcc497b62014-01-24 02:24:47 +0000220 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
Dan Gohmanb9487362012-08-08 00:00:26 +0000221 SmallVector<BasicBlock *, 8> ExitBlocks;
222 SmallVector<Instruction *, 8> InsertPts;
Chandler Carruthfc258542014-02-11 12:52:27 +0000223 PredIteratorCache PIC;
Dan Gohmanb9487362012-08-08 00:00:26 +0000224
Chris Lattner1dc98b42010-08-29 06:43:52 +0000225 // Loop over all of the alias sets in the tracker object.
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000226 for (AliasSet &AS : *CurAST)
Dehao Chend55bc4c2016-05-05 00:54:54 +0000227 Changed |=
228 promoteLoopAccessesToScalars(AS, ExitBlocks, InsertPts, PIC, LI, DT,
229 TLI, CurLoop, CurAST, &SafetyInfo);
Chandler Carruth16651522014-02-01 13:35:14 +0000230
231 // Once we have promoted values across the loop body we have to recursively
232 // reform LCSSA as any nested loop may now have values defined within the
233 // loop used in the outer loop.
234 // FIXME: This is really heavy handed. It would be a bit better to use an
235 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
236 // it as it went.
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000237 if (Changed) {
238 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
239 formLCSSARecursively(*L, *DT, LI, SEWP ? &SEWP->getSE() : nullptr);
240 }
Chris Lattner1dc98b42010-08-29 06:43:52 +0000241 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000242
Chandler Carruthfc258542014-02-11 12:52:27 +0000243 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
244 // specifically moving instructions across the loop boundary and so it is
245 // especially in need of sanity checking here.
246 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
247 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
248 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000249
Chris Lattner6ec05f52002-05-10 22:44:58 +0000250 // Clear out loops state information for the next iteration
Craig Topperf40110f2014-04-25 05:29:35 +0000251 CurLoop = nullptr;
252 Preheader = nullptr;
Devang Patel69730c92007-03-07 04:41:30 +0000253
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000254 // If this loop is nested inside of another one, save the alias information
255 // for when we process the outer loop.
256 if (L->getParentLoop())
257 LoopToAliasSetMap[L] = CurAST;
258 else
259 delete CurAST;
Sanjoy Das4ae39202016-05-03 17:50:11 +0000260
261 if (Changed)
262 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
263 SEWP->getSE().forgetLoopDispositions(L);
Devang Patel69730c92007-03-07 04:41:30 +0000264 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000265}
266
Hal Finkel3d4269a2015-02-22 18:35:32 +0000267/// Walk the specified region of the CFG (defined by all blocks dominated by
Dehao Chend55bc4c2016-05-05 00:54:54 +0000268/// the specified block, and that are in the current loop) in reverse depth
Hal Finkel3d4269a2015-02-22 18:35:32 +0000269/// first order w.r.t the DominatorTree. This allows us to visit uses before
270/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000271///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000272bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
273 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
274 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Chris Lattner547192d62003-12-19 07:22:45 +0000275
Hal Finkel3d4269a2015-02-22 18:35:32 +0000276 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000277 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
278 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
279 "Unexpected input to sinkRegion");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000280
Hal Finkel3d4269a2015-02-22 18:35:32 +0000281 BasicBlock *BB = N->getBlock();
Chris Lattner547192d62003-12-19 07:22:45 +0000282 // If this subregion is not in the top level loop at all, exit.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000283 if (!CurLoop->contains(BB))
284 return false;
Chris Lattner547192d62003-12-19 07:22:45 +0000285
Chris Lattner263f8042010-08-29 18:22:25 +0000286 // We are processing blocks in reverse dfo, so process children first.
Sanjay Patel99133222016-01-13 23:01:57 +0000287 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000288 const std::vector<DomTreeNode *> &Children = N->getChildren();
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000289 for (DomTreeNode *Child : Children)
290 Changed |= sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
291
Chris Lattner547192d62003-12-19 07:22:45 +0000292 // Only need to process the contents of this block if it is not part of a
293 // subloop (which would already have been processed).
Dehao Chend55bc4c2016-05-05 00:54:54 +0000294 if (inSubLoop(BB, CurLoop, LI))
295 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000296
Dehao Chend55bc4c2016-05-05 00:54:54 +0000297 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
Chris Lattner91846012003-12-19 08:18:16 +0000298 Instruction &I = *--II;
Tobias Grossera3928f52011-07-06 19:20:02 +0000299
Chris Lattner263f8042010-08-29 18:22:25 +0000300 // If the instruction is dead, we would try to sink it because it isn't used
301 // in the loop, instead, just delete it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000302 if (isInstructionTriviallyDead(&I, TLI)) {
Chris Lattnerf58382e2010-08-29 18:42:23 +0000303 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
Chris Lattner263f8042010-08-29 18:22:25 +0000304 ++II;
305 CurAST->deleteValue(&I);
306 I.eraseFromParent();
307 Changed = true;
308 continue;
309 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000310
Chris Lattner547192d62003-12-19 07:22:45 +0000311 // Check to see if we can sink this instruction to the exit blocks
312 // of the loop. We can do this if the all users of the instruction are
313 // outside of the loop. In this case, it doesn't even matter if the
314 // operands of the instruction are loop invariant.
315 //
David Majnemer42a07302016-01-04 03:37:39 +0000316 if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000317 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) {
Chris Lattner91846012003-12-19 08:18:16 +0000318 ++II;
David Majnemer42a07302016-01-04 03:37:39 +0000319 Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo);
Chris Lattner91846012003-12-19 08:18:16 +0000320 }
Chris Lattner547192d62003-12-19 07:22:45 +0000321 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000322 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000323}
324
Hal Finkel3d4269a2015-02-22 18:35:32 +0000325/// Walk the specified region of the CFG (defined by all blocks dominated by
326/// the specified block, and that are in the current loop) in depth first
327/// order w.r.t the DominatorTree. This allows us to visit definitions before
328/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000329///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000330bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
331 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
332 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000333 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000334 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
335 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
336 "Unexpected input to hoistRegion");
Sanjay Patel99133222016-01-13 23:01:57 +0000337
Owen Andersonc24701e2007-04-24 06:40:39 +0000338 BasicBlock *BB = N->getBlock();
Sanjay Patel99133222016-01-13 23:01:57 +0000339
Chris Lattner05e86302002-09-29 22:26:07 +0000340 // If this subregion is not in the top level loop at all, exit.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000341 if (!CurLoop->contains(BB))
342 return false;
Sanjay Patel99133222016-01-13 23:01:57 +0000343
Chris Lattneraaaea512003-12-10 06:41:05 +0000344 // Only need to process the contents of this block if it is not part of a
345 // subloop (which would already have been processed).
Sanjay Patel99133222016-01-13 23:01:57 +0000346 bool Changed = false;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000347 if (!inSubLoop(BB, CurLoop, LI))
Dehao Chend55bc4c2016-05-05 00:54:54 +0000348 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
Chris Lattneraaaea512003-12-10 06:41:05 +0000349 Instruction &I = *II++;
Chris Lattner030f0202010-08-31 23:00:16 +0000350 // Try constant folding this instruction. If all the operands are
351 // constants, it is technically hoistable, but it would be better to just
352 // fold it.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000353 if (Constant *C = ConstantFoldInstruction(
354 &I, I.getModule()->getDataLayout(), TLI)) {
Chris Lattner030f0202010-08-31 23:00:16 +0000355 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
356 CurAST->copyValue(&I, C);
357 CurAST->deleteValue(&I);
358 I.replaceAllUsesWith(C);
359 I.eraseFromParent();
360 continue;
361 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000362
Chris Lattner547192d62003-12-19 07:22:45 +0000363 // Try hoisting the instruction out to the preheader. We can only do this
364 // if all of the operands of the instruction are loop invariant and if it
365 // is safe to hoist the instruction.
366 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000367 if (CurLoop->hasLoopInvariantOperands(&I) &&
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000368 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) &&
Dehao Chend55bc4c2016-05-05 00:54:54 +0000369 isSafeToExecuteUnconditionally(
370 I, DT, TLI, CurLoop, SafetyInfo,
371 CurLoop->getLoopPreheader()->getTerminator()))
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000372 Changed |= hoist(I, DT, CurLoop, SafetyInfo);
Chris Lattner030f0202010-08-31 23:00:16 +0000373 }
Chris Lattner64437692002-09-29 21:46:09 +0000374
Dehao Chend55bc4c2016-05-05 00:54:54 +0000375 const std::vector<DomTreeNode *> &Children = N->getChildren();
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000376 for (DomTreeNode *Child : Children)
377 Changed |= hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000378 return Changed;
379}
380
381/// Computes loop safety information, checks loop body & header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000382/// for the possibility of may throw exception.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000383///
Dehao Chend55bc4c2016-05-05 00:54:54 +0000384void llvm::computeLICMSafetyInfo(LICMSafetyInfo *SafetyInfo, Loop *CurLoop) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000385 assert(CurLoop != nullptr && "CurLoop cant be null");
386 BasicBlock *Header = CurLoop->getHeader();
387 // Setting default safety values.
388 SafetyInfo->MayThrow = false;
389 SafetyInfo->HeaderMayThrow = false;
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000390 // Iterate over header and compute safety info.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000391 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
392 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
393 SafetyInfo->HeaderMayThrow |= I->mayThrow();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000394
Hal Finkel3d4269a2015-02-22 18:35:32 +0000395 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000396 // Iterate over loop instructions and compute safety info.
397 for (Loop::block_iterator BB = CurLoop->block_begin(),
398 BBE = CurLoop->block_end();
399 (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000400 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
401 (I != E) && !SafetyInfo->MayThrow; ++I)
402 SafetyInfo->MayThrow |= I->mayThrow();
David Majnemer42a07302016-01-04 03:37:39 +0000403
404 // Compute funclet colors if we might sink/hoist in a function with a funclet
405 // personality routine.
406 Function *Fn = CurLoop->getHeader()->getParent();
407 if (Fn->hasPersonalityFn())
408 if (Constant *PersonalityFn = Fn->getPersonalityFn())
409 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
410 SafetyInfo->BlockColors = colorEHFunclets(*Fn);
Chris Lattner64437692002-09-29 21:46:09 +0000411}
412
Chris Lattneraaaea512003-12-10 06:41:05 +0000413/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
414/// instruction.
415///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000416bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000417 TargetLibraryInfo *TLI, Loop *CurLoop,
418 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Chris Lattner65c11932003-12-09 19:32:44 +0000419 // Loads have extra constraints we have to verify before we can hoist them.
420 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000421 if (!LI->isUnordered())
Dehao Chend55bc4c2016-05-05 00:54:54 +0000422 return false; // Don't hoist volatile/atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000423
Chris Lattner8a8fb902008-07-23 05:06:28 +0000424 // Loads from constant memory are always safe to move, even if they end up
425 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000426 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000427 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000428 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000429 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000430
Chris Lattner65c11932003-12-09 19:32:44 +0000431 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000432 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000433 if (LI->getType()->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000434 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000435
436 AAMDNodes AAInfo;
437 LI->getAAMetadata(AAInfo);
438
Hal Finkel3d4269a2015-02-22 18:35:32 +0000439 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
Chris Lattner20cda262004-03-15 04:11:30 +0000440 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000441 // Don't sink or hoist dbg info; it's legal, but not useful.
442 if (isa<DbgInfoIntrinsic>(I))
443 return false;
444
David Majnemer42a07302016-01-04 03:37:39 +0000445 // Don't sink calls which can throw.
446 if (CI->mayThrow())
447 return false;
448
Eli Friedman942e1c12011-05-27 18:37:52 +0000449 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000450 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
451 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000452 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000453 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Philip Reames5f994232015-09-21 22:27:59 +0000454 // A readonly argmemonly function only reads from memory pointed to by
455 // it's arguments with arbitrary offsets. If we can prove there are no
456 // writes to this memory in the loop, we can hoist or sink.
457 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
458 for (Value *Op : CI->arg_operands())
459 if (Op->getType()->isPointerTy() &&
460 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
461 AAMDNodes(), CurAST))
462 return false;
463 return true;
464 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000465 // If this call only reads from memory and there are no writes to memory
466 // in the loop, we can hoist or sink the call as appropriate.
467 bool FoundMod = false;
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000468 for (AliasSet &AS : *CurAST) {
Duncan Sands68b6f502007-12-01 07:51:45 +0000469 if (!AS.isForwardingAliasSet() && AS.isMod()) {
470 FoundMod = true;
471 break;
Chris Lattner20cda262004-03-15 04:11:30 +0000472 }
Chris Lattner20cda262004-03-15 04:11:30 +0000473 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000474 if (!FoundMod)
475 return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000476 }
477
Nadav Rotem03dcd852012-09-04 10:25:04 +0000478 // FIXME: This should use mod/ref information to see if we can hoist or
479 // sink the call.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000480
Chris Lattner20cda262004-03-15 04:11:30 +0000481 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000482 }
483
Nadav Rotem03dcd852012-09-04 10:25:04 +0000484 // Only these instructions are hoistable/sinkable.
Benjamin Kramer130fcde2013-01-09 18:12:03 +0000485 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
486 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
487 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
488 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
489 !isa<InsertValueInst>(I))
490 return false;
Nadav Rotem03dcd852012-09-04 10:25:04 +0000491
Philip Reamesb47b9c22015-05-22 02:14:05 +0000492 // TODO: Plumb the context instruction through to make hoisting and sinking
493 // more powerful. Hoisting of loads already works due to the special casing
Dehao Chend55bc4c2016-05-05 00:54:54 +0000494 // above.
Philip Reamesb47b9c22015-05-22 02:14:05 +0000495 return isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo,
496 nullptr);
Chris Lattneraaaea512003-12-10 06:41:05 +0000497}
498
Hal Finkel3d4269a2015-02-22 18:35:32 +0000499/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000500/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000501/// This is true when all incoming values are that instruction.
502/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000503///
Pete Cooper47e80cd2015-05-12 20:05:20 +0000504static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000505 for (const Value *IncValue : PN.incoming_values())
506 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000507 return false;
508
509 return true;
510}
511
Hal Finkel3d4269a2015-02-22 18:35:32 +0000512/// Return true if the only users of this instruction are outside of
513/// the loop. If this is true, we can sink the instruction to the exit
514/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000515///
David Majnemer42a07302016-01-04 03:37:39 +0000516static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
517 const LICMSafetyInfo *SafetyInfo) {
518 const auto &BlockColors = SafetyInfo->BlockColors;
Pete Cooper0cabcf22015-05-13 01:12:18 +0000519 for (const User *U : I.users()) {
520 const Instruction *UI = cast<Instruction>(U);
521 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Majnemer42a07302016-01-04 03:37:39 +0000522 const BasicBlock *BB = PN->getParent();
523 // We cannot sink uses in catchswitches.
524 if (isa<CatchSwitchInst>(BB->getTerminator()))
525 return false;
526
527 // We need to sink a callsite to a unique funclet. Avoid sinking if the
528 // phi use is too muddled.
529 if (isa<CallInst>(I))
530 if (!BlockColors.empty() &&
531 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
532 return false;
533
Chandler Carruth8765cf72014-01-25 04:07:24 +0000534 // A PHI node where all of the incoming values are this instruction are
535 // special -- they can just be RAUW'ed with the instruction and thus
536 // don't require a use in the predecessor. This is a particular important
537 // special case because it is the pattern found in LCSSA form.
538 if (isTriviallyReplacablePHI(*PN, I)) {
539 if (CurLoop->contains(PN))
540 return false;
541 else
542 continue;
543 }
544
545 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
546 // values. Check for such a use being inside the loop.
Chris Lattner34399dd2003-12-11 22:23:32 +0000547 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
548 if (PN->getIncomingValue(i) == &I)
549 if (CurLoop->contains(PN->getIncomingBlock(i)))
550 return false;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000551
552 continue;
Chris Lattner34399dd2003-12-11 22:23:32 +0000553 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000554
Chandler Carruthcdf47882014-03-09 03:16:01 +0000555 if (CurLoop->contains(UI))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000556 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000557 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000558 return true;
559}
560
David Majnemer42a07302016-01-04 03:37:39 +0000561static Instruction *
562CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
563 const LoopInfo *LI,
564 const LICMSafetyInfo *SafetyInfo) {
565 Instruction *New;
566 if (auto *CI = dyn_cast<CallInst>(&I)) {
567 const auto &BlockColors = SafetyInfo->BlockColors;
568
569 // Sinking call-sites need to be handled differently from other
570 // instructions. The cloned call-site needs a funclet bundle operand
571 // appropriate for it's location in the CFG.
572 SmallVector<OperandBundleDef, 1> OpBundles;
573 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
574 BundleIdx != BundleEnd; ++BundleIdx) {
575 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
576 if (Bundle.getTagID() == LLVMContext::OB_funclet)
577 continue;
578
579 OpBundles.emplace_back(Bundle);
580 }
581
582 if (!BlockColors.empty()) {
583 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
584 assert(CV.size() == 1 && "non-unique color for exit block!");
585 BasicBlock *BBColor = CV.front();
586 Instruction *EHPad = BBColor->getFirstNonPHI();
587 if (EHPad->isEHPad())
588 OpBundles.emplace_back("funclet", EHPad);
589 }
590
591 New = CallInst::Create(CI, OpBundles);
592 } else {
593 New = I.clone();
594 }
595
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000596 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000597 if (!I.getName().empty())
598 New->setName(I.getName() + ".le");
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000599
600 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
601 // particularly cheap because we can rip off the PHI node that we're
602 // replacing for the number and blocks of the predecessors.
603 // OPT: If this shows up in a profile, we can instead finish sinking all
604 // invariant instructions, and then walk their operands to re-establish
605 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
606 // sinking bottom-up.
607 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
608 ++OI)
609 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
610 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
611 if (!OLoop->contains(&PN)) {
612 PHINode *OpPN =
613 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000614 OInst->getName() + ".lcssa", &ExitBlock.front());
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000615 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
616 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
617 *OI = OpPN;
618 }
619 return New;
620}
621
Hal Finkel3d4269a2015-02-22 18:35:32 +0000622/// When an instruction is found to only be used outside of the loop, this
623/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000624/// This method is guaranteed to remove the original instruction from its
625/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000626///
Pete Cooper0cabcf22015-05-13 01:12:18 +0000627static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +0000628 const Loop *CurLoop, AliasSetTracker *CurAST,
629 const LICMSafetyInfo *SafetyInfo) {
Nick Lewycky299c6df2010-07-30 20:27:01 +0000630 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000631 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000632 if (isa<LoadInst>(I))
633 ++NumMovedLoads;
634 else if (isa<CallInst>(I))
635 ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000636 ++NumSunk;
637 Changed = true;
638
Chandler Carruthfc258542014-02-11 12:52:27 +0000639#ifndef NDEBUG
640 SmallVector<BasicBlock *, 32> ExitBlocks;
641 CurLoop->getUniqueExitBlocks(ExitBlocks);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000642 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
Hal Finkel3d4269a2015-02-22 18:35:32 +0000643 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +0000644#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +0000645
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000646 // Clones of this instruction. Don't create more than one per exit block!
647 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
648
Chandler Carruthfc258542014-02-11 12:52:27 +0000649 // If this instruction is only used outside of the loop, then all users are
650 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
651 // the instruction.
652 while (!I.use_empty()) {
David Majnemer6bc83e02015-07-12 03:53:05 +0000653 Value::user_iterator UI = I.user_begin();
654 auto *User = cast<Instruction>(*UI);
David Majnemer49428102014-09-02 16:22:00 +0000655 if (!DT->isReachableFromEntry(User->getParent())) {
656 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
657 continue;
658 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000659 // The user must be a PHI node.
David Majnemer49428102014-09-02 16:22:00 +0000660 PHINode *PN = cast<PHINode>(User);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000661
David Majnemer6bc83e02015-07-12 03:53:05 +0000662 // Surprisingly, instructions can be used outside of loops without any
663 // exits. This can only happen in PHI nodes if the incoming block is
664 // unreachable.
665 Use &U = UI.getUse();
666 BasicBlock *BB = PN->getIncomingBlock(U);
667 if (!DT->isReachableFromEntry(BB)) {
668 U = UndefValue::get(I.getType());
669 continue;
670 }
671
Chandler Carruthfc258542014-02-11 12:52:27 +0000672 BasicBlock *ExitBlock = PN->getParent();
673 assert(ExitBlockSet.count(ExitBlock) &&
674 "The LCSSA PHI is not in an exit block!");
675
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000676 Instruction *New;
677 auto It = SunkCopies.find(ExitBlock);
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000678 if (It != SunkCopies.end())
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000679 New = It->second;
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000680 else
681 New = SunkCopies[ExitBlock] =
David Majnemer42a07302016-01-04 03:37:39 +0000682 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo);
Chandler Carruthfc258542014-02-11 12:52:27 +0000683
684 PN->replaceAllUsesWith(New);
685 PN->eraseFromParent();
Chris Lattnercd96b4d2010-08-29 04:28:20 +0000686 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000687
Chris Lattner1a1ed692010-08-29 18:00:00 +0000688 CurAST->deleteValue(&I);
Chandler Carruthfc258542014-02-11 12:52:27 +0000689 I.eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000690 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000691}
Chris Lattner64437692002-09-29 21:46:09 +0000692
Hal Finkel3d4269a2015-02-22 18:35:32 +0000693/// When an instruction is found to only use loop invariant operands that
694/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000695///
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000696static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
697 const LICMSafetyInfo *SafetyInfo) {
698 auto *Preheader = CurLoop->getLoopPreheader();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000699 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
700 << "\n");
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000701
702 // Metadata can be dependent on conditions we are hoisting above.
703 // Conservatively strip all metadata on the instruction unless we were
704 // guaranteed to execute I if we entered the loop, in which case the metadata
705 // is valid in the loop preheader.
706 if (I.hasMetadataOtherThanDebugLoc() &&
707 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
708 // time in isGuaranteedToExecute if we don't actually have anything to
709 // drop. It is a compile time optimization, not required for correctness.
710 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
711 I.dropUnknownNonDebugMetadata();
712
Chris Lattner6ac06592010-08-29 18:18:40 +0000713 // Move the new node to the Preheader, before its terminator.
714 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000715
Dehao Chend55bc4c2016-05-05 00:54:54 +0000716 if (isa<LoadInst>(I))
717 ++NumMovedLoads;
718 else if (isa<CallInst>(I))
719 ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000720 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000721 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000722}
723
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000724/// Only sink or hoist an instruction if it is not a trapping instruction,
725/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000726/// or if it is a trapping instruction and is guaranteed to execute.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000727static bool isSafeToExecuteUnconditionally(const Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000728 const DominatorTree *DT,
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000729 const TargetLibraryInfo *TLI,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000730 const Loop *CurLoop,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000731 const LICMSafetyInfo *SafetyInfo,
732 const Instruction *CtxI) {
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000733 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000734 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000735
Hal Finkel3d4269a2015-02-22 18:35:32 +0000736 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
Eli Friedman0cdc1482011-07-20 21:37:47 +0000737}
738
Pete Cooper0cabcf22015-05-13 01:12:18 +0000739static bool isGuaranteedToExecute(const Instruction &Inst,
Dehao Chend55bc4c2016-05-05 00:54:54 +0000740 const DominatorTree *DT, const Loop *CurLoop,
741 const LICMSafetyInfo *SafetyInfo) {
Nadav Rotem03dcd852012-09-04 10:25:04 +0000742
Philip Reamesb35f46c2014-12-29 23:00:57 +0000743 // We have to check to make sure that the instruction dominates all
Chris Lattnerc0517682003-12-09 17:18:00 +0000744 // of the exit blocks. If it doesn't, then there is a path out of the loop
745 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000746
Chris Lattnerc0517682003-12-09 17:18:00 +0000747 // If the instruction is in the header block for the loop (which is very
748 // common), it is always guaranteed to dominate the exit blocks. Since this
749 // is a common case, and can save some work, check it now.
Chris Lattneraaaea512003-12-10 06:41:05 +0000750 if (Inst.getParent() == CurLoop->getHeader())
Philip Reamesb35f46c2014-12-29 23:00:57 +0000751 // If there's a throw in the header block, we can't guarantee we'll reach
752 // Inst.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000753 return !SafetyInfo->HeaderMayThrow;
Philip Reamesb35f46c2014-12-29 23:00:57 +0000754
755 // Somewhere in this loop there is an instruction which may throw and make us
756 // exit the loop.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000757 if (SafetyInfo->MayThrow)
Philip Reamesb35f46c2014-12-29 23:00:57 +0000758 return false;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000759
Chris Lattnerc0517682003-12-09 17:18:00 +0000760 // Get the exit blocks for the current loop.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000761 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattner35eaa552004-04-18 22:15:13 +0000762 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerc0517682003-12-09 17:18:00 +0000763
Chris Lattner27497ec2011-01-02 18:45:39 +0000764 // Verify that the block dominates each of the exit blocks of the loop.
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000765 for (BasicBlock *ExitBlock : ExitBlocks)
766 if (!DT->dominates(Inst.getParent(), ExitBlock))
Chris Lattneraaaea512003-12-10 06:41:05 +0000767 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000768
Nick Lewycky78ee67e2012-05-01 04:03:01 +0000769 // As a degenerate case, if the loop is statically infinite then we haven't
770 // proven anything since there are no exit blocks.
771 if (ExitBlocks.empty())
772 return false;
773
Tanya Lattner57c03df2003-08-05 18:45:46 +0000774 return true;
775}
776
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000777namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +0000778class LoopPromoter : public LoadAndStorePromoter {
779 Value *SomePtr; // Designated pointer to store to.
780 SmallPtrSetImpl<Value *> &PointerMustAliases;
781 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
782 SmallVectorImpl<Instruction *> &LoopInsertPts;
783 PredIteratorCache &PredCache;
784 AliasSetTracker &AST;
785 LoopInfo &LI;
786 DebugLoc DL;
787 int Alignment;
788 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +0000789
Dehao Chend55bc4c2016-05-05 00:54:54 +0000790 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
791 if (Instruction *I = dyn_cast<Instruction>(V))
792 if (Loop *L = LI.getLoopFor(I->getParent()))
793 if (!L->contains(BB)) {
794 // We need to create an LCSSA PHI node for the incoming value and
795 // store that.
796 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
797 I->getName() + ".lcssa", &BB->front());
798 for (BasicBlock *Pred : PredCache.get(BB))
799 PN->addIncoming(I, Pred);
800 return PN;
801 }
802 return V;
803 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000804
Dehao Chend55bc4c2016-05-05 00:54:54 +0000805public:
806 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
807 SmallPtrSetImpl<Value *> &PMA,
808 SmallVectorImpl<BasicBlock *> &LEB,
809 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
810 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
811 const AAMDNodes &AATags)
812 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
813 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
814 LI(li), DL(dl), Alignment(alignment), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +0000815
Dehao Chend55bc4c2016-05-05 00:54:54 +0000816 bool isInstInList(Instruction *I,
817 const SmallVectorImpl<Instruction *> &) const override {
818 Value *Ptr;
819 if (LoadInst *LI = dyn_cast<LoadInst>(I))
820 Ptr = LI->getOperand(0);
821 else
822 Ptr = cast<StoreInst>(I)->getPointerOperand();
823 return PointerMustAliases.count(Ptr);
824 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000825
Dehao Chend55bc4c2016-05-05 00:54:54 +0000826 void doExtraRewritesBeforeFinalDeletion() const override {
827 // Insert stores after in the loop exit blocks. Each exit block gets a
828 // store of the live-out values that feed them. Since we've already told
829 // the SSA updater about the defs in the loop and the preheader
830 // definition, it is all set and we can start using it.
831 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
832 BasicBlock *ExitBlock = LoopExitBlocks[i];
833 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
834 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
835 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
836 Instruction *InsertPos = LoopInsertPts[i];
837 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
838 NewSI->setAlignment(Alignment);
839 NewSI->setDebugLoc(DL);
840 if (AATags)
841 NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000842 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000843 }
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000844
Dehao Chend55bc4c2016-05-05 00:54:54 +0000845 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
846 // Update alias analysis.
847 AST.copyValue(LI, V);
848 }
849 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
850};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000851} // end anon namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000852
Hal Finkel3d4269a2015-02-22 18:35:32 +0000853/// Try to promote memory values to scalars by sinking stores out of the
854/// loop and moving loads to before the loop. We do this by looping over
855/// the stores in the loop, looking for stores to Must pointers which are
856/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +0000857///
Dehao Chend55bc4c2016-05-05 00:54:54 +0000858bool llvm::promoteLoopAccessesToScalars(
859 AliasSet &AS, SmallVectorImpl<BasicBlock *> &ExitBlocks,
860 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
861 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
862 Loop *CurLoop, AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000863 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000864 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
865 CurAST != nullptr && SafetyInfo != nullptr &&
Hal Finkel3d4269a2015-02-22 18:35:32 +0000866 "Unexpected Input to promoteLoopAccessesToScalars");
Sanjay Patel99133222016-01-13 23:01:57 +0000867
Chris Lattner1dc98b42010-08-29 06:43:52 +0000868 // We can promote this alias set if it has a store, if it is a "Must" alias
869 // set, if the pointer is loop invariant, and if we are not eliminating any
870 // volatile loads or stores.
871 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
872 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
Sanjay Patel99133222016-01-13 23:01:57 +0000873 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +0000874
Chris Lattner1dc98b42010-08-29 06:43:52 +0000875 assert(!AS.empty() &&
876 "Must alias set should have at least one pointer element in it!");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000877
Chris Lattner1dc98b42010-08-29 06:43:52 +0000878 Value *SomePtr = AS.begin()->getValue();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000879 BasicBlock *Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +0000880
Chris Lattner1dc98b42010-08-29 06:43:52 +0000881 // It isn't safe to promote a load/store from the loop if the load/store is
882 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +0000883 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000884 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +0000885 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000886 // into:
887 //
888 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
889 //
890 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +0000891 //
Philip Reamesb54c8e62016-03-09 22:59:30 +0000892 // The safety property divides into two parts:
893 // 1) The memory may not be dereferenceable on entry to the loop. In this
894 // case, we can't insert the required load in the preheader.
895 // 2) The memory model does not allow us to insert a store along any dynamic
896 // path which did not originally have one.
897 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000898 // It is safe to promote P if all uses are direct load/stores and if at
899 // least one is guaranteed to be executed.
900 bool GuaranteedToExecute = false;
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000901
Philip Reamesb54c8e62016-03-09 22:59:30 +0000902 // It is also safe to promote P if we can prove that speculating a load into
903 // the preheader is safe (i.e. proving dereferenceability on all
904 // paths through the loop), and that the memory can be proven thread local
905 // (so that the memory model requirement doesn't apply.) We first establish
906 // the former, and then run a capture analysis below to establish the later.
907 // We can use any access within the alias set to prove dereferenceability
908 // since they're all must alias.
909 bool CanSpeculateLoad = false;
910
Dehao Chend55bc4c2016-05-05 00:54:54 +0000911 SmallVector<Instruction *, 64> LoopUses;
912 SmallPtrSet<Value *, 4> PointerMustAliases;
Chris Lattner45d67d62003-02-24 03:52:32 +0000913
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000914 // We start with an alignment of one and try to find instructions that allow
915 // us to prove better alignment.
916 unsigned Alignment = 1;
Hal Finkelcc39b672014-07-24 12:16:19 +0000917 AAMDNodes AATags;
Bruno Cardoso Lopes46d5bf22014-11-28 19:47:46 +0000918 bool HasDedicatedExits = CurLoop->hasDedicatedExits();
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000919
Philip Reamesb54c8e62016-03-09 22:59:30 +0000920 // Don't sink stores from loops without dedicated block exits. Exits
921 // containing indirect branches are not transformed by loop simplify,
922 // make sure we catch that. An additional load may be generated in the
923 // preheader for SSA updater, so also avoid sinking when no preheader
924 // is available.
925 if (!HasDedicatedExits || !Preheader)
926 return false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000927
Philip Reamesb54c8e62016-03-09 22:59:30 +0000928 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
929
Chris Lattner1dc98b42010-08-29 06:43:52 +0000930 // Check that all of the pointers in the alias set have the same type. We
931 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +0000932 // different sizes. While we are at it, collect alignment and AA info.
Sanjay Patel99133222016-01-13 23:01:57 +0000933 bool Changed = false;
Chris Lattner1dc98b42010-08-29 06:43:52 +0000934 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
935 Value *ASIV = ASI->getValue();
936 PointerMustAliases.insert(ASIV);
Tobias Grossera3928f52011-07-06 19:20:02 +0000937
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000938 // Check that all of the pointers in the alias set have the same type. We
939 // cannot (yet) promote a memory location that is loaded and stored in
940 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +0000941 if (SomePtr->getType() != ASIV->getType())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000942 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000943
Chandler Carruthcdf47882014-03-09 03:16:01 +0000944 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +0000945 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000946 Instruction *UI = dyn_cast<Instruction>(U);
947 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000948 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +0000949
Chris Lattner1dc98b42010-08-29 06:43:52 +0000950 // If there is an non-load/store instruction in the loop, we can't promote
951 // it.
Sanjay Patel9f49b682016-01-08 22:05:03 +0000952 if (const LoadInst *Load = dyn_cast<LoadInst>(UI)) {
953 assert(!Load->isVolatile() && "AST broken");
954 if (!Load->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000955 return Changed;
Philip Reamesb54c8e62016-03-09 22:59:30 +0000956
957 if (!GuaranteedToExecute && !CanSpeculateLoad)
Dehao Chend55bc4c2016-05-05 00:54:54 +0000958 CanSpeculateLoad = isSafeToExecuteUnconditionally(
959 *Load, DT, TLI, CurLoop, SafetyInfo, Preheader->getTerminator());
Sanjay Patel9f49b682016-01-08 22:05:03 +0000960 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +0000961 // Stores *of* the pointer are not interesting, only stores *to* the
962 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000963 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +0000964 continue;
Sanjay Patel9f49b682016-01-08 22:05:03 +0000965 assert(!Store->isVolatile() && "AST broken");
966 if (!Store->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000967 return Changed;
Eli Friedman0cdc1482011-07-20 21:37:47 +0000968
969 // Note that we only check GuaranteedToExecute inside the store case
970 // so that we do not introduce stores where they did not exist before
971 // (which would break the LLVM concurrency model).
972
973 // If the alignment of this instruction allows us to specify a more
974 // restrictive (and performant) alignment and if we are sure this
975 // instruction will be executed, update the alignment.
976 // Larger is better, with the exception of 0 being the best alignment.
Sanjay Patel9f49b682016-01-08 22:05:03 +0000977 unsigned InstAlignment = Store->getAlignment();
Chris Lattnerf5cca682012-12-31 08:37:17 +0000978 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000979 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Eli Friedman0cdc1482011-07-20 21:37:47 +0000980 GuaranteedToExecute = true;
981 Alignment = InstAlignment;
982 }
983
984 if (!GuaranteedToExecute)
Dehao Chend55bc4c2016-05-05 00:54:54 +0000985 GuaranteedToExecute =
986 isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo);
Philip Reamesb54c8e62016-03-09 22:59:30 +0000987
988 if (!GuaranteedToExecute && !CanSpeculateLoad) {
Dehao Chend55bc4c2016-05-05 00:54:54 +0000989 CanSpeculateLoad = isDereferenceableAndAlignedPointer(
990 Store->getPointerOperand(), Store->getAlignment(), MDL,
991 Preheader->getTerminator(), DT, TLI);
Philip Reamesb54c8e62016-03-09 22:59:30 +0000992 }
Chris Lattnerbe901902010-09-06 05:11:24 +0000993 } else
Hal Finkel3d4269a2015-02-22 18:35:32 +0000994 return Changed; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000995
Hal Finkelcc39b672014-07-24 12:16:19 +0000996 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +0000997 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +0000998 // On the first load/store, just take its AA tags.
999 UI->getAAMetadata(AATags);
1000 } else if (AATags) {
1001 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +00001002 }
Chandler Carruthcdf47882014-03-09 03:16:01 +00001003
1004 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001005 }
1006 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001007
Philip Reamesb54c8e62016-03-09 22:59:30 +00001008 // Check legality per comment above. Otherwise, we can't promote.
1009 bool PromotionIsLegal = GuaranteedToExecute;
1010 if (!PromotionIsLegal && CanSpeculateLoad) {
1011 // If this is a thread local location, then we can insert stores along
1012 // paths which originally didn't have them without violating the memory
Dehao Chend55bc4c2016-05-05 00:54:54 +00001013 // model.
Philip Reamesb54c8e62016-03-09 22:59:30 +00001014 Value *Object = GetUnderlyingObject(SomePtr, MDL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001015 PromotionIsLegal =
1016 isAllocLikeFn(Object, TLI) && !PointerMayBeCaptured(Object, true, true);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001017 }
1018 if (!PromotionIsLegal)
Hal Finkel3d4269a2015-02-22 18:35:32 +00001019 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +00001020
David Majnemer219055f2016-01-04 17:42:19 +00001021 // Figure out the loop exits and their insertion points, if this is the
1022 // first promotion.
1023 if (ExitBlocks.empty()) {
1024 CurLoop->getUniqueExitBlocks(ExitBlocks);
1025 InsertPts.clear();
1026 InsertPts.reserve(ExitBlocks.size());
David Majnemerb33f3a22016-01-04 23:16:22 +00001027 for (BasicBlock *ExitBlock : ExitBlocks)
David Majnemer219055f2016-01-04 17:42:19 +00001028 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
David Majnemer219055f2016-01-04 17:42:19 +00001029 }
1030
David Majnemerb33f3a22016-01-04 23:16:22 +00001031 // Can't insert into a catchswitch.
1032 for (BasicBlock *ExitBlock : ExitBlocks)
1033 if (isa<CatchSwitchInst>(ExitBlock->getTerminator()))
1034 return Changed;
1035
Chris Lattner1dc98b42010-08-29 06:43:52 +00001036 // Otherwise, this is safe to promote, lets do it!
Dehao Chend55bc4c2016-05-05 00:54:54 +00001037 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1038 << '\n');
Chris Lattner1dc98b42010-08-29 06:43:52 +00001039 Changed = true;
1040 ++NumPromoted;
1041
Eli Friedmanddf7f552011-05-27 20:31:51 +00001042 // Grab a debug location for the inserted loads/stores; given that the
1043 // inserted loads/stores have little relation to the original loads/stores,
1044 // this code just arbitrarily picks a location from one, since any debug
1045 // location is better than none.
1046 DebugLoc DL = LoopUses[0]->getDebugLoc();
1047
Chris Lattner1dc98b42010-08-29 06:43:52 +00001048 // We use the SSAUpdater interface to insert phi nodes as required.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001049 SmallVector<PHINode *, 16> NewPHIs;
Chris Lattner1dc98b42010-08-29 06:43:52 +00001050 SSAUpdater SSA(&NewPHIs);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001051 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Hal Finkelcc39b672014-07-24 12:16:19 +00001052 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +00001053
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001054 // Set up the preheader to have a definition of the value. It is the live-out
1055 // value from the preheader that uses in the loop will use.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001056 LoadInst *PreheaderLoad = new LoadInst(
1057 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001058 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +00001059 PreheaderLoad->setDebugLoc(DL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001060 if (AATags)
1061 PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001062 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1063
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001064 // Rewrite all the loads in the loop and remember all the definitions from
1065 // stores in the loop.
1066 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +00001067
1068 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1069 if (PreheaderLoad->use_empty())
1070 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +00001071
1072 return Changed;
Chris Lattnera51fa882002-08-22 21:39:55 +00001073}
Devang Patelb98a0972007-07-31 08:01:41 +00001074
Roman Gareev036c0882016-02-15 14:48:50 +00001075/// Returns an owning pointer to an alias set which incorporates aliasing info
Chandler Carruthad8cb382016-02-27 04:34:07 +00001076/// from L and all subloops of L.
1077AliasSetTracker *LICM::collectAliasInfoForLoop(Loop *L) {
Roman Gareev036c0882016-02-15 14:48:50 +00001078 AliasSetTracker *CurAST = nullptr;
Chandler Carruthad8cb382016-02-27 04:34:07 +00001079 SmallVector<Loop *, 4> RecomputeLoops;
Roman Gareev036c0882016-02-15 14:48:50 +00001080 for (Loop *InnerL : L->getSubLoops()) {
Chandler Carruthad8cb382016-02-27 04:34:07 +00001081 auto MapI = LoopToAliasSetMap.find(InnerL);
1082 // If the AST for this inner loop is missing it may have been merged into
1083 // some other loop's AST and then that loop unrolled, and so we need to
1084 // recompute it.
1085 if (MapI == LoopToAliasSetMap.end()) {
1086 RecomputeLoops.push_back(InnerL);
1087 continue;
1088 }
1089 AliasSetTracker *InnerAST = MapI->second;
Roman Gareev036c0882016-02-15 14:48:50 +00001090
1091 if (CurAST != nullptr) {
1092 // What if InnerLoop was modified by other passes ?
1093 CurAST->add(*InnerAST);
1094
1095 // Once we've incorporated the inner loop's AST into ours, we don't need
1096 // the subloop's anymore.
1097 delete InnerAST;
1098 } else {
1099 CurAST = InnerAST;
1100 }
Chandler Carruthad8cb382016-02-27 04:34:07 +00001101 LoopToAliasSetMap.erase(MapI);
Roman Gareev036c0882016-02-15 14:48:50 +00001102 }
1103 if (CurAST == nullptr)
1104 CurAST = new AliasSetTracker(*AA);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001105
1106 auto mergeLoop = [&](Loop *L) {
1107 // Loop over the body of this loop, looking for calls, invokes, and stores.
1108 // Because subloops have already been incorporated into AST, we skip blocks
1109 // in subloops.
1110 for (BasicBlock *BB : L->blocks())
1111 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
1112 CurAST->add(*BB); // Incorporate the specified basic block
1113 };
1114
1115 // Add everything from the sub loops that are no longer directly available.
1116 for (Loop *InnerL : RecomputeLoops)
1117 mergeLoop(InnerL);
1118
1119 // And merge in this loop.
1120 mergeLoop(L);
1121
Roman Gareev036c0882016-02-15 14:48:50 +00001122 return CurAST;
1123}
1124
Ashutosh Nema47802622015-08-13 11:18:35 +00001125/// Simple analysis hook. Clone alias set info.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001126///
Devang Patelb98a0972007-07-31 08:01:41 +00001127void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +00001128 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001129 if (!AST)
1130 return;
1131
1132 AST->copyValue(From, To);
1133}
1134
Hal Finkel3d4269a2015-02-22 18:35:32 +00001135/// Simple Analysis hook. Delete value V from alias set
1136///
Devang Patelb98a0972007-07-31 08:01:41 +00001137void LICM::deleteAnalysisValue(Value *V, Loop *L) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +00001138 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001139 if (!AST)
1140 return;
1141
1142 AST->deleteValue(V);
1143}
David Peixotto0d4d5e62014-09-24 16:48:31 +00001144
1145/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001146///
David Peixotto0d4d5e62014-09-24 16:48:31 +00001147void LICM::deleteAnalysisLoop(Loop *L) {
1148 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
1149 if (!AST)
1150 return;
1151
1152 delete AST;
1153 LoopToAliasSetMap.erase(L);
1154}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001155
Hal Finkel3d4269a2015-02-22 18:35:32 +00001156/// Return true if the body of this loop may store into the memory
1157/// location pointed to by V.
1158///
1159static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001160 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +00001161 AliasSetTracker *CurAST) {
1162 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1163 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1164}
1165
1166/// Little predicate that returns true if the specified basic block is in
1167/// a subloop of the current one, not the current one itself.
1168///
1169static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1170 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1171 return LI->getLoopFor(BB) != CurLoop;
1172}