blob: 14af38b9491d3b6a1aa93b7db20483ec2d59b4e6 [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"
Chris Lattner030f0202010-08-31 23:00:16 +000037#include "llvm/Analysis/ConstantFolding.h"
38#include "llvm/Analysis/LoopInfo.h"
39#include "llvm/Analysis/LoopPass.h"
Chandler Carruthabfa3e52014-01-24 01:59:49 +000040#include "llvm/Analysis/ScalarEvolution.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000041#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000042#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Constants.h"
44#include "llvm/IR/DataLayout.h"
45#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000046#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Instructions.h"
48#include "llvm/IR/IntrinsicInst.h"
49#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000050#include "llvm/IR/Metadata.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000051#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/Support/CommandLine.h"
53#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000054#include "llvm/Support/raw_ostream.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000055#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000057#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000058#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000059#include <algorithm>
Chris Lattnerc0517682003-12-09 17:18:00 +000060using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000061
Chandler Carruth964daaa2014-04-22 02:55:47 +000062#define DEBUG_TYPE "licm"
63
Chris Lattner79a42ac2006-12-19 21:40:18 +000064STATISTIC(NumSunk , "Number of instructions sunk out of loop");
65STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
66STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
67STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
68STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
69
Dan Gohmand78c4002008-05-13 00:00:25 +000070static cl::opt<bool>
71DisablePromotion("disable-licm-promotion", cl::Hidden,
72 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000073
Hal Finkel3d4269a2015-02-22 18:35:32 +000074static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
75static bool isNotUsedInLoop(Instruction &I, Loop *CurLoop);
76static bool hoist(Instruction &I, BasicBlock *Preheader);
77static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
78 Loop *CurLoop, AliasSetTracker *CurAST );
79static bool isGuaranteedToExecute(Instruction &Inst, DominatorTree *DT,
80 Loop *CurLoop, LICMSafetyInfo * SafetyInfo);
81static bool isSafeToExecuteUnconditionally(Instruction &Inst,DominatorTree *DT,
82 const DataLayout *DL, Loop *CurLoop,
83 LICMSafetyInfo * SafetyInfo);
84static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
85 const AAMDNodes &AAInfo,
86 AliasSetTracker *CurAST);
87static Instruction *CloneInstructionInExitBlock(Instruction &I,
88 BasicBlock &ExitBlock,
89 PHINode &PN, LoopInfo *LI);
90static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
91 DominatorTree *DT, const DataLayout *DL,
92 Loop *CurLoop, AliasSetTracker *CurAST,
93 LICMSafetyInfo * SafetyInfo);
94
Dan Gohmand78c4002008-05-13 00:00:25 +000095namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000096 struct LICM : public LoopPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000097 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000098 LICM() : LoopPass(ID) {
99 initializeLICMPass(*PassRegistry::getPassRegistry());
100 }
Devang Patel09f162c2007-05-01 21:15:47 +0000101
Craig Topper3e4c6972014-03-05 09:10:37 +0000102 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000103
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000104 /// This transformation requires natural loop information & requires that
105 /// loop preheaders be inserted into the CFG...
106 ///
Craig Topper3e4c6972014-03-05 09:10:37 +0000107 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chris Lattner820d9712002-10-21 20:00:28 +0000108 AU.setPreservesCFG();
Chandler Carruth73523022014-01-13 13:07:17 +0000109 AU.addRequired<DominatorTreeWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000110 AU.addRequired<LoopInfoWrapperPass>();
Dan Gohmanefd7f9c2010-07-16 17:58:45 +0000111 AU.addRequiredID(LoopSimplifyID);
Chandler Carruth8765cf72014-01-25 04:07:24 +0000112 AU.addPreservedID(LoopSimplifyID);
113 AU.addRequiredID(LCSSAID);
114 AU.addPreservedID(LCSSAID);
Chris Lattnera51fa882002-08-22 21:39:55 +0000115 AU.addRequired<AliasAnalysis>();
Chris Lattnerf94f6bb2010-08-29 07:02:56 +0000116 AU.addPreserved<AliasAnalysis>();
Chandler Carruthabfa3e52014-01-24 01:59:49 +0000117 AU.addPreserved<ScalarEvolution>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000118 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chris Lattner6ec05f52002-05-10 22:44:58 +0000119 }
120
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000121 using llvm::Pass::doFinalization;
122
Craig Topper3e4c6972014-03-05 09:10:37 +0000123 bool doFinalization() override {
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000124 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets");
Devang Patel69730c92007-03-07 04:41:30 +0000125 return false;
126 }
127
Chris Lattner6ec05f52002-05-10 22:44:58 +0000128 private:
Chris Lattner45d67d62003-02-24 03:52:32 +0000129 AliasAnalysis *AA; // Current AliasAnalysis information
Chris Lattnerc0517682003-12-09 17:18:00 +0000130 LoopInfo *LI; // Current LoopInfo
Chris Lattnerabe61ef2010-08-29 06:49:44 +0000131 DominatorTree *DT; // Dominator Tree for the current Loop.
Chris Lattnerc0517682003-12-09 17:18:00 +0000132
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000133 const DataLayout *DL; // DataLayout for constant folding.
Chad Rosier43a33062011-12-02 01:26:24 +0000134 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding.
135
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000136 // State that is updated as we process loops.
Chris Lattner45d67d62003-02-24 03:52:32 +0000137 bool Changed; // Set to true when we change anything.
138 BasicBlock *Preheader; // The preheader block of the current loop...
139 Loop *CurLoop; // The current loop we are working on...
Chris Lattner0592bb72003-03-03 23:32:45 +0000140 AliasSetTracker *CurAST; // AliasSet information for the current loop...
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000141 DenseMap<Loop*, AliasSetTracker*> LoopToAliasSetMap;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000142
Devang Patelb98a0972007-07-31 08:01:41 +0000143 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
Craig Topper3e4c6972014-03-05 09:10:37 +0000144 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
145 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000146
147 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
148 /// set.
Craig Topper3e4c6972014-03-05 09:10:37 +0000149 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000150
David Peixotto0d4d5e62014-09-24 16:48:31 +0000151 /// Simple Analysis hook. Delete loop L from alias set map.
152 void deleteAnalysisLoop(Loop *L) override;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000153 };
154}
155
Dan Gohmand78c4002008-05-13 00:00:25 +0000156char LICM::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000157INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false)
Chandler Carruth73523022014-01-13 13:07:17 +0000158INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000159INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000160INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000161INITIALIZE_PASS_DEPENDENCY(LCSSA)
162INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000163INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000164INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
165INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000166
Daniel Dunbar7f39e2d2008-10-22 23:32:42 +0000167Pass *llvm::createLICMPass() { return new LICM(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000168
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000169/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000170/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000171/// times on one loop.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000172///
Devang Patel69730c92007-03-07 04:41:30 +0000173bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000174 if (skipOptnoneFunction(L))
175 return false;
176
Chris Lattner45d67d62003-02-24 03:52:32 +0000177 Changed = false;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000178
Chris Lattner45d67d62003-02-24 03:52:32 +0000179 // Get our Loop and Alias Analysis information...
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000180 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Chris Lattnera51fa882002-08-22 21:39:55 +0000181 AA = &getAnalysis<AliasAnalysis>();
Chandler Carruth73523022014-01-13 13:07:17 +0000182 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnera51fa882002-08-22 21:39:55 +0000183
Rafael Espindola93512512014-02-25 17:30:31 +0000184 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topperf40110f2014-04-25 05:29:35 +0000185 DL = DLP ? &DLP->getDataLayout() : nullptr;
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
Devang Patel69730c92007-03-07 04:41:30 +0000190 CurAST = new AliasSetTracker(*AA);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000191 // Collect Alias info from subloops.
Devang Patel69730c92007-03-07 04:41:30 +0000192 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
193 LoopItr != LoopItrE; ++LoopItr) {
194 Loop *InnerL = *LoopItr;
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000195 AliasSetTracker *InnerAST = LoopToAliasSetMap[InnerL];
196 assert(InnerAST && "Where is my AST?");
Devang Patel69730c92007-03-07 04:41:30 +0000197
198 // What if InnerLoop was modified by other passes ?
199 CurAST->add(*InnerAST);
Tobias Grossera3928f52011-07-06 19:20:02 +0000200
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000201 // Once we've incorporated the inner loop's AST into ours, we don't need the
202 // subloop's anymore.
203 delete InnerAST;
204 LoopToAliasSetMap.erase(InnerL);
Chris Lattner45d67d62003-02-24 03:52:32 +0000205 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000206
Chris Lattner6ec05f52002-05-10 22:44:58 +0000207 CurLoop = L;
208
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000209 // Get the preheader block to move instructions into...
210 Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000211
Chris Lattner45d67d62003-02-24 03:52:32 +0000212 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chris Lattner0592bb72003-03-03 23:32:45 +0000213 // Because subloops have already been incorporated into AST, we skip blocks in
Chris Lattner45d67d62003-02-24 03:52:32 +0000214 // subloops.
215 //
Dan Gohman90071072008-06-22 20:18:58 +0000216 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
217 I != E; ++I) {
218 BasicBlock *BB = *I;
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000219 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops.
Dan Gohman90071072008-06-22 20:18:58 +0000220 CurAST->add(*BB); // Incorporate the specified basic block
221 }
Chris Lattner45d67d62003-02-24 03:52:32 +0000222
Hal Finkel3d4269a2015-02-22 18:35:32 +0000223 // Compute loop safety information.
224 LICMSafetyInfo SafetyInfo;
225 computeLICMSafetyInfo(&SafetyInfo, CurLoop);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000226
Chris Lattner6ec05f52002-05-10 22:44:58 +0000227 // We want to visit all of the instructions in this loop... that are not parts
228 // of our subloops (they have already had their invariants hoisted out of
229 // their loop, into this loop, so there is no need to process the BODIES of
230 // the subloops).
231 //
Chris Lattner64437692002-09-29 21:46:09 +0000232 // Traverse the body of the loop in depth first order on the dominator tree so
233 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000234 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000235 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000236 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000237 if (L->hasDedicatedExits())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000238 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, DL, TLI,
239 CurLoop, CurAST, &SafetyInfo);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000240 if (Preheader)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000241 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, DL, TLI,
242 CurLoop, CurAST, &SafetyInfo);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000243
Chris Lattner45d67d62003-02-24 03:52:32 +0000244 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000245 // memory references to scalars that we can.
Chandler Carruthcc497b62014-01-24 02:24:47 +0000246 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) {
Dan Gohmanb9487362012-08-08 00:00:26 +0000247 SmallVector<BasicBlock *, 8> ExitBlocks;
248 SmallVector<Instruction *, 8> InsertPts;
Chandler Carruthfc258542014-02-11 12:52:27 +0000249 PredIteratorCache PIC;
Dan Gohmanb9487362012-08-08 00:00:26 +0000250
Chris Lattner1dc98b42010-08-29 06:43:52 +0000251 // Loop over all of the alias sets in the tracker object.
252 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
253 I != E; ++I)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000254 Changed |= promoteLoopAccessesToScalars(*I, ExitBlocks, InsertPts,
255 PIC, LI, DT, CurLoop,
256 CurAST, &SafetyInfo);
Chandler Carruth16651522014-02-01 13:35:14 +0000257
258 // Once we have promoted values across the loop body we have to recursively
259 // reform LCSSA as any nested loop may now have values defined within the
260 // loop used in the outer loop.
261 // FIXME: This is really heavy handed. It would be a bit better to use an
262 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
263 // it as it went.
264 if (Changed)
Bruno Cardoso Lopesbad65c32014-12-22 22:35:46 +0000265 formLCSSARecursively(*L, *DT, LI,
266 getAnalysisIfAvailable<ScalarEvolution>());
Chris Lattner1dc98b42010-08-29 06:43:52 +0000267 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000268
Chandler Carruthfc258542014-02-11 12:52:27 +0000269 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
270 // specifically moving instructions across the loop boundary and so it is
271 // especially in need of sanity checking here.
272 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
273 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
274 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000275
Chris Lattner6ec05f52002-05-10 22:44:58 +0000276 // Clear out loops state information for the next iteration
Craig Topperf40110f2014-04-25 05:29:35 +0000277 CurLoop = nullptr;
278 Preheader = nullptr;
Devang Patel69730c92007-03-07 04:41:30 +0000279
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000280 // If this loop is nested inside of another one, save the alias information
281 // for when we process the outer loop.
282 if (L->getParentLoop())
283 LoopToAliasSetMap[L] = CurAST;
284 else
285 delete CurAST;
Devang Patel69730c92007-03-07 04:41:30 +0000286 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000287}
288
Hal Finkel3d4269a2015-02-22 18:35:32 +0000289/// Walk the specified region of the CFG (defined by all blocks dominated by
290/// the specified block, and that are in the current loop) in reverse depth
291/// first order w.r.t the DominatorTree. This allows us to visit uses before
292/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000293///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000294bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
295 DominatorTree *DT, const DataLayout *DL,
296 TargetLibraryInfo *TLI, Loop *CurLoop,
297 AliasSetTracker *CurAST, LICMSafetyInfo * SafetyInfo) {
Chris Lattner547192d62003-12-19 07:22:45 +0000298
Hal Finkel3d4269a2015-02-22 18:35:32 +0000299 // Verify inputs.
300 assert(N != nullptr && AA != nullptr && LI != nullptr &&
301 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
302 SafetyInfo != nullptr && "Unexpected input to sinkRegion");
303
304 // Set changed as false.
305 bool Changed = false;
306 // Get basic block
307 BasicBlock *BB = N->getBlock();
Chris Lattner547192d62003-12-19 07:22:45 +0000308 // If this subregion is not in the top level loop at all, exit.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000309 if (!CurLoop->contains(BB)) return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000310
Chris Lattner263f8042010-08-29 18:22:25 +0000311 // We are processing blocks in reverse dfo, so process children first.
Devang Patelbdd1aae2007-06-04 00:32:22 +0000312 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattner547192d62003-12-19 07:22:45 +0000313 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000314 Changed |= sinkRegion(Children[i], AA, LI, DT, DL, TLI, CurLoop,
315 CurAST, SafetyInfo);
Chris Lattner547192d62003-12-19 07:22:45 +0000316 // Only need to process the contents of this block if it is not part of a
317 // subloop (which would already have been processed).
Hal Finkel3d4269a2015-02-22 18:35:32 +0000318 if (inSubLoop(BB,CurLoop,LI)) return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000319
Chris Lattner91846012003-12-19 08:18:16 +0000320 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
321 Instruction &I = *--II;
Tobias Grossera3928f52011-07-06 19:20:02 +0000322
Chris Lattner263f8042010-08-29 18:22:25 +0000323 // If the instruction is dead, we would try to sink it because it isn't used
324 // in the loop, instead, just delete it.
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000325 if (isInstructionTriviallyDead(&I, TLI)) {
Chris Lattnerf58382e2010-08-29 18:42:23 +0000326 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
Chris Lattner263f8042010-08-29 18:22:25 +0000327 ++II;
328 CurAST->deleteValue(&I);
329 I.eraseFromParent();
330 Changed = true;
331 continue;
332 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000333
Chris Lattner547192d62003-12-19 07:22:45 +0000334 // Check to see if we can sink this instruction to the exit blocks
335 // of the loop. We can do this if the all users of the instruction are
336 // outside of the loop. In this case, it doesn't even matter if the
337 // operands of the instruction are loop invariant.
338 //
Hal Finkel3d4269a2015-02-22 18:35:32 +0000339 if (isNotUsedInLoop(I, CurLoop) &&
340 canSinkOrHoistInst(I, AA, DT, DL, CurLoop, CurAST, SafetyInfo)) {
Chris Lattner91846012003-12-19 08:18:16 +0000341 ++II;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000342 Changed |= sink(I, LI, DT, CurLoop, CurAST);
Chris Lattner91846012003-12-19 08:18:16 +0000343 }
Chris Lattner547192d62003-12-19 07:22:45 +0000344 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000345 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000346}
347
Hal Finkel3d4269a2015-02-22 18:35:32 +0000348/// Walk the specified region of the CFG (defined by all blocks dominated by
349/// the specified block, and that are in the current loop) in depth first
350/// order w.r.t the DominatorTree. This allows us to visit definitions before
351/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000352///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000353bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
354 DominatorTree *DT, const DataLayout *DL,
355 TargetLibraryInfo *TLI, Loop *CurLoop,
356 AliasSetTracker *CurAST, LICMSafetyInfo *SafetyInfo) {
357 // Verify inputs.
358 assert(N != nullptr && AA != nullptr && LI != nullptr &&
359 DT != nullptr && CurLoop != nullptr && CurAST != nullptr &&
360 SafetyInfo != nullptr && "Unexpected input to hoistRegion");
361 // Set changed as false.
362 bool Changed = false;
363 // Get basic block
Owen Andersonc24701e2007-04-24 06:40:39 +0000364 BasicBlock *BB = N->getBlock();
Chris Lattner05e86302002-09-29 22:26:07 +0000365 // If this subregion is not in the top level loop at all, exit.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000366 if (!CurLoop->contains(BB)) return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000367 // Only need to process the contents of this block if it is not part of a
368 // subloop (which would already have been processed).
Hal Finkel3d4269a2015-02-22 18:35:32 +0000369 if (!inSubLoop(BB, CurLoop, LI))
Chris Lattneraaaea512003-12-10 06:41:05 +0000370 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
371 Instruction &I = *II++;
Chris Lattner030f0202010-08-31 23:00:16 +0000372 // Try constant folding this instruction. If all the operands are
373 // constants, it is technically hoistable, but it would be better to just
374 // fold it.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000375 if (Constant *C = ConstantFoldInstruction(&I, DL, TLI)) {
Chris Lattner030f0202010-08-31 23:00:16 +0000376 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
377 CurAST->copyValue(&I, C);
378 CurAST->deleteValue(&I);
379 I.replaceAllUsesWith(C);
380 I.eraseFromParent();
381 continue;
382 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000383
Chris Lattner547192d62003-12-19 07:22:45 +0000384 // Try hoisting the instruction out to the preheader. We can only do this
385 // if all of the operands of the instruction are loop invariant and if it
386 // is safe to hoist the instruction.
387 //
Hal Finkel3d4269a2015-02-22 18:35:32 +0000388 if (CurLoop->hasLoopInvariantOperands(&I) &&
389 canSinkOrHoistInst(I, AA, DT, DL, CurLoop, CurAST, SafetyInfo) &&
390 isSafeToExecuteUnconditionally(I, DT, DL, CurLoop, SafetyInfo))
391 Changed |= hoist(I, CurLoop->getLoopPreheader());
Chris Lattner030f0202010-08-31 23:00:16 +0000392 }
Chris Lattner64437692002-09-29 21:46:09 +0000393
Devang Patelbdd1aae2007-06-04 00:32:22 +0000394 const std::vector<DomTreeNode*> &Children = N->getChildren();
Chris Lattner64437692002-09-29 21:46:09 +0000395 for (unsigned i = 0, e = Children.size(); i != e; ++i)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000396 Changed |= hoistRegion(Children[i], AA, LI, DT, DL, TLI, CurLoop,
397 CurAST, SafetyInfo);
398 return Changed;
399}
400
401/// Computes loop safety information, checks loop body & header
402/// for the possiblity of may throw exception.
403///
404void llvm::computeLICMSafetyInfo(LICMSafetyInfo * SafetyInfo, Loop * CurLoop) {
405 assert(CurLoop != nullptr && "CurLoop cant be null");
406 BasicBlock *Header = CurLoop->getHeader();
407 // Setting default safety values.
408 SafetyInfo->MayThrow = false;
409 SafetyInfo->HeaderMayThrow = false;
410 // Iterate over header and compute dafety info.
411 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
412 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
413 SafetyInfo->HeaderMayThrow |= I->mayThrow();
414
415 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
416 // Iterate over loop instructions and compute safety info.
417 for (Loop::block_iterator BB = CurLoop->block_begin(),
418 BBE = CurLoop->block_end(); (BB != BBE) && !SafetyInfo->MayThrow ; ++BB)
419 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
420 (I != E) && !SafetyInfo->MayThrow; ++I)
421 SafetyInfo->MayThrow |= I->mayThrow();
Chris Lattner64437692002-09-29 21:46:09 +0000422}
423
Chris Lattneraaaea512003-12-10 06:41:05 +0000424/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
425/// instruction.
426///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000427bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA,
428 DominatorTree *DT, const DataLayout *DL,
429 Loop *CurLoop, AliasSetTracker *CurAST,
430 LICMSafetyInfo * SafetyInfo) {
Chris Lattner65c11932003-12-09 19:32:44 +0000431 // Loads have extra constraints we have to verify before we can hoist them.
432 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000433 if (!LI->isUnordered())
434 return false; // Don't hoist volatile/atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000435
Chris Lattner8a8fb902008-07-23 05:06:28 +0000436 // Loads from constant memory are always safe to move, even if they end up
437 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000438 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000439 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000440 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000441 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000442
Chris Lattner65c11932003-12-09 19:32:44 +0000443 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000444 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000445 if (LI->getType()->isSized())
Dan Gohman43d19d62009-07-25 00:48:42 +0000446 Size = AA->getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000447
448 AAMDNodes AAInfo;
449 LI->getAAMetadata(AAInfo);
450
Hal Finkel3d4269a2015-02-22 18:35:32 +0000451 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
Chris Lattner20cda262004-03-15 04:11:30 +0000452 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000453 // Don't sink or hoist dbg info; it's legal, but not useful.
454 if (isa<DbgInfoIntrinsic>(I))
455 return false;
456
457 // Handle simple cases by querying alias analysis.
Duncan Sands68b6f502007-12-01 07:51:45 +0000458 AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
459 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
460 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000461 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Duncan Sands68b6f502007-12-01 07:51:45 +0000462 // If this call only reads from memory and there are no writes to memory
463 // in the loop, we can hoist or sink the call as appropriate.
464 bool FoundMod = false;
465 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
466 I != E; ++I) {
467 AliasSet &AS = *I;
468 if (!AS.isForwardingAliasSet() && AS.isMod()) {
469 FoundMod = true;
470 break;
Chris Lattner20cda262004-03-15 04:11:30 +0000471 }
Chris Lattner20cda262004-03-15 04:11:30 +0000472 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000473 if (!FoundMod) return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000474 }
475
Nadav Rotem03dcd852012-09-04 10:25:04 +0000476 // FIXME: This should use mod/ref information to see if we can hoist or
477 // sink the call.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000478
Chris Lattner20cda262004-03-15 04:11:30 +0000479 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000480 }
481
Nadav Rotem03dcd852012-09-04 10:25:04 +0000482 // Only these instructions are hoistable/sinkable.
Benjamin Kramer130fcde2013-01-09 18:12:03 +0000483 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
484 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
485 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
486 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
487 !isa<InsertValueInst>(I))
488 return false;
Nadav Rotem03dcd852012-09-04 10:25:04 +0000489
Hal Finkel3d4269a2015-02-22 18:35:32 +0000490 return isSafeToExecuteUnconditionally(I, DT, DL, CurLoop, SafetyInfo);
Chris Lattneraaaea512003-12-10 06:41:05 +0000491}
492
Hal Finkel3d4269a2015-02-22 18:35:32 +0000493/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000494/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000495/// This is true when all incoming values are that instruction.
496/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000497///
Chandler Carruth8765cf72014-01-25 04:07:24 +0000498static bool isTriviallyReplacablePHI(PHINode &PN, Instruction &I) {
499 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
500 if (PN.getIncomingValue(i) != &I)
501 return false;
502
503 return true;
504}
505
Hal Finkel3d4269a2015-02-22 18:35:32 +0000506/// Return true if the only users of this instruction are outside of
507/// the loop. If this is true, we can sink the instruction to the exit
508/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000509///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000510static bool isNotUsedInLoop(Instruction &I, Loop *CurLoop) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000511 for (User *U : I.users()) {
512 Instruction *UI = cast<Instruction>(U);
513 if (PHINode *PN = dyn_cast<PHINode>(UI)) {
Chandler Carruth8765cf72014-01-25 04:07:24 +0000514 // A PHI node where all of the incoming values are this instruction are
515 // special -- they can just be RAUW'ed with the instruction and thus
516 // don't require a use in the predecessor. This is a particular important
517 // special case because it is the pattern found in LCSSA form.
518 if (isTriviallyReplacablePHI(*PN, I)) {
519 if (CurLoop->contains(PN))
520 return false;
521 else
522 continue;
523 }
524
525 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
526 // values. Check for such a use being inside the loop.
Chris Lattner34399dd2003-12-11 22:23:32 +0000527 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
528 if (PN->getIncomingValue(i) == &I)
529 if (CurLoop->contains(PN->getIncomingBlock(i)))
530 return false;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000531
532 continue;
Chris Lattner34399dd2003-12-11 22:23:32 +0000533 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000534
Chandler Carruthcdf47882014-03-09 03:16:01 +0000535 if (CurLoop->contains(UI))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000536 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000537 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000538 return true;
539}
540
Hal Finkel3d4269a2015-02-22 18:35:32 +0000541static Instruction *CloneInstructionInExitBlock(Instruction &I,
542 BasicBlock &ExitBlock,
543 PHINode &PN, LoopInfo *LI) {
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000544 Instruction *New = I.clone();
545 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
546 if (!I.getName().empty()) New->setName(I.getName() + ".le");
547
548 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
549 // particularly cheap because we can rip off the PHI node that we're
550 // replacing for the number and blocks of the predecessors.
551 // OPT: If this shows up in a profile, we can instead finish sinking all
552 // invariant instructions, and then walk their operands to re-establish
553 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
554 // sinking bottom-up.
555 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
556 ++OI)
557 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
558 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
559 if (!OLoop->contains(&PN)) {
560 PHINode *OpPN =
561 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
562 OInst->getName() + ".lcssa", ExitBlock.begin());
563 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
564 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
565 *OI = OpPN;
566 }
567 return New;
568}
569
Hal Finkel3d4269a2015-02-22 18:35:32 +0000570/// When an instruction is found to only be used outside of the loop, this
571/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000572/// This method is guaranteed to remove the original instruction from its
573/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000574///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000575static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
576 Loop *CurLoop, AliasSetTracker *CurAST ) {
Nick Lewycky299c6df2010-07-30 20:27:01 +0000577 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000578 bool Changed = false;
Chris Lattner55c21132003-12-10 20:43:29 +0000579 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000580 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000581 ++NumSunk;
582 Changed = true;
583
Chandler Carruthfc258542014-02-11 12:52:27 +0000584#ifndef NDEBUG
585 SmallVector<BasicBlock *, 32> ExitBlocks;
586 CurLoop->getUniqueExitBlocks(ExitBlocks);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000587 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
588 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +0000589#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +0000590
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000591 // Clones of this instruction. Don't create more than one per exit block!
592 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
593
Chandler Carruthfc258542014-02-11 12:52:27 +0000594 // If this instruction is only used outside of the loop, then all users are
595 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
596 // the instruction.
597 while (!I.use_empty()) {
David Majnemer49428102014-09-02 16:22:00 +0000598 Instruction *User = I.user_back();
599 if (!DT->isReachableFromEntry(User->getParent())) {
600 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
601 continue;
602 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000603 // The user must be a PHI node.
David Majnemer49428102014-09-02 16:22:00 +0000604 PHINode *PN = cast<PHINode>(User);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000605
Chandler Carruthfc258542014-02-11 12:52:27 +0000606 BasicBlock *ExitBlock = PN->getParent();
607 assert(ExitBlockSet.count(ExitBlock) &&
608 "The LCSSA PHI is not in an exit block!");
609
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000610 Instruction *New;
611 auto It = SunkCopies.find(ExitBlock);
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000612 if (It != SunkCopies.end())
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000613 New = It->second;
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000614 else
615 New = SunkCopies[ExitBlock] =
Hal Finkel3d4269a2015-02-22 18:35:32 +0000616 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI);
Chandler Carruthfc258542014-02-11 12:52:27 +0000617
618 PN->replaceAllUsesWith(New);
619 PN->eraseFromParent();
Chris Lattnercd96b4d2010-08-29 04:28:20 +0000620 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000621
Chris Lattner1a1ed692010-08-29 18:00:00 +0000622 CurAST->deleteValue(&I);
Chandler Carruthfc258542014-02-11 12:52:27 +0000623 I.eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000624 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000625}
Chris Lattner64437692002-09-29 21:46:09 +0000626
Hal Finkel3d4269a2015-02-22 18:35:32 +0000627/// When an instruction is found to only use loop invariant operands that
628/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000629///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000630static bool hoist(Instruction &I, BasicBlock *Preheader) {
David Greene0fd86222010-01-05 01:27:30 +0000631 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": "
Evan Chengf8158612009-10-12 22:25:23 +0000632 << I << "\n");
Chris Lattner6ac06592010-08-29 18:18:40 +0000633 // Move the new node to the Preheader, before its terminator.
634 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000635
Chris Lattneraaaea512003-12-10 06:41:05 +0000636 if (isa<LoadInst>(I)) ++NumMovedLoads;
Chris Lattner20cda262004-03-15 04:11:30 +0000637 else if (isa<CallInst>(I)) ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000638 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000639 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000640}
641
Hal Finkel3d4269a2015-02-22 18:35:32 +0000642/// Only sink or hoist an instruction if it is not a trapping instruction
643/// or if it is a trapping instruction and is guaranteed to execute.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000644///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000645static bool isSafeToExecuteUnconditionally(Instruction &Inst, DominatorTree *DT,
646 const DataLayout *DL, Loop *CurLoop,
647 LICMSafetyInfo * SafetyInfo) {
Chris Lattnerc0517682003-12-09 17:18:00 +0000648 // If it is not a trapping instruction, it is always safe to hoist.
Hal Finkel2e42c342014-07-10 05:27:53 +0000649 if (isSafeToSpeculativelyExecute(&Inst, DL))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000650 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000651
Hal Finkel3d4269a2015-02-22 18:35:32 +0000652 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
Eli Friedman0cdc1482011-07-20 21:37:47 +0000653}
654
Hal Finkel3d4269a2015-02-22 18:35:32 +0000655static bool isGuaranteedToExecute(Instruction &Inst, DominatorTree *DT,
656 Loop *CurLoop, LICMSafetyInfo * SafetyInfo) {
Nadav Rotem03dcd852012-09-04 10:25:04 +0000657
Philip Reamesb35f46c2014-12-29 23:00:57 +0000658 // We have to check to make sure that the instruction dominates all
Chris Lattnerc0517682003-12-09 17:18:00 +0000659 // of the exit blocks. If it doesn't, then there is a path out of the loop
660 // which does not execute this instruction, so we can't hoist it.
Tanya Lattner57c03df2003-08-05 18:45:46 +0000661
Chris Lattnerc0517682003-12-09 17:18:00 +0000662 // If the instruction is in the header block for the loop (which is very
663 // common), it is always guaranteed to dominate the exit blocks. Since this
664 // is a common case, and can save some work, check it now.
Chris Lattneraaaea512003-12-10 06:41:05 +0000665 if (Inst.getParent() == CurLoop->getHeader())
Philip Reamesb35f46c2014-12-29 23:00:57 +0000666 // If there's a throw in the header block, we can't guarantee we'll reach
667 // Inst.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000668 return !SafetyInfo->HeaderMayThrow;
Philip Reamesb35f46c2014-12-29 23:00:57 +0000669
670 // Somewhere in this loop there is an instruction which may throw and make us
671 // exit the loop.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000672 if (SafetyInfo->MayThrow)
Philip Reamesb35f46c2014-12-29 23:00:57 +0000673 return false;
Tanya Lattner57c03df2003-08-05 18:45:46 +0000674
Chris Lattnerc0517682003-12-09 17:18:00 +0000675 // Get the exit blocks for the current loop.
Devang Patelb5933bb2007-08-21 00:31:24 +0000676 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattner35eaa552004-04-18 22:15:13 +0000677 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnerc0517682003-12-09 17:18:00 +0000678
Chris Lattner27497ec2011-01-02 18:45:39 +0000679 // Verify that the block dominates each of the exit blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000680 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
Chris Lattner27497ec2011-01-02 18:45:39 +0000681 if (!DT->dominates(Inst.getParent(), ExitBlocks[i]))
Chris Lattneraaaea512003-12-10 06:41:05 +0000682 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000683
Nick Lewycky78ee67e2012-05-01 04:03:01 +0000684 // As a degenerate case, if the loop is statically infinite then we haven't
685 // proven anything since there are no exit blocks.
686 if (ExitBlocks.empty())
687 return false;
688
Tanya Lattner57c03df2003-08-05 18:45:46 +0000689 return true;
690}
691
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000692namespace {
693 class LoopPromoter : public LoadAndStorePromoter {
694 Value *SomePtr; // Designated pointer to store to.
Craig Topper71b7b682014-08-21 05:55:13 +0000695 SmallPtrSetImpl<Value*> &PointerMustAliases;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000696 SmallVectorImpl<BasicBlock*> &LoopExitBlocks;
Dan Gohmanb9487362012-08-08 00:00:26 +0000697 SmallVectorImpl<Instruction*> &LoopInsertPts;
Chandler Carruthfc258542014-02-11 12:52:27 +0000698 PredIteratorCache &PredCache;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000699 AliasSetTracker &AST;
Chandler Carruthfc258542014-02-11 12:52:27 +0000700 LoopInfo &LI;
Eli Friedmanddf7f552011-05-27 20:31:51 +0000701 DebugLoc DL;
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000702 int Alignment;
Hal Finkelcc39b672014-07-24 12:16:19 +0000703 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +0000704
705 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
706 if (Instruction *I = dyn_cast<Instruction>(V))
707 if (Loop *L = LI.getLoopFor(I->getParent()))
708 if (!L->contains(BB)) {
709 // We need to create an LCSSA PHI node for the incoming value and
710 // store that.
711 PHINode *PN = PHINode::Create(
712 I->getType(), PredCache.GetNumPreds(BB),
713 I->getName() + ".lcssa", BB->begin());
714 for (BasicBlock **PI = PredCache.GetPreds(BB); *PI; ++PI)
715 PN->addIncoming(I, *PI);
716 return PN;
717 }
718 return V;
719 }
720
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000721 public:
Chandler Carruthfc258542014-02-11 12:52:27 +0000722 LoopPromoter(Value *SP, const SmallVectorImpl<Instruction *> &Insts,
Craig Topper71b7b682014-08-21 05:55:13 +0000723 SSAUpdater &S, SmallPtrSetImpl<Value *> &PMA,
Chandler Carruthfc258542014-02-11 12:52:27 +0000724 SmallVectorImpl<BasicBlock *> &LEB,
725 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
726 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
Hal Finkelcc39b672014-07-24 12:16:19 +0000727 const AAMDNodes &AATags)
Chandler Carruthfc258542014-02-11 12:52:27 +0000728 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
729 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Hal Finkelcc39b672014-07-24 12:16:19 +0000730 LI(li), DL(dl), Alignment(alignment), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +0000731
Craig Topper3e4c6972014-03-05 09:10:37 +0000732 bool isInstInList(Instruction *I,
733 const SmallVectorImpl<Instruction*> &) const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000734 Value *Ptr;
735 if (LoadInst *LI = dyn_cast<LoadInst>(I))
736 Ptr = LI->getOperand(0);
737 else
738 Ptr = cast<StoreInst>(I)->getPointerOperand();
739 return PointerMustAliases.count(Ptr);
740 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000741
Craig Topper3e4c6972014-03-05 09:10:37 +0000742 void doExtraRewritesBeforeFinalDeletion() const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000743 // Insert stores after in the loop exit blocks. Each exit block gets a
744 // store of the live-out values that feed them. Since we've already told
745 // the SSA updater about the defs in the loop and the preheader
746 // definition, it is all set and we can start using it.
747 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
748 BasicBlock *ExitBlock = LoopExitBlocks[i];
749 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
Chandler Carruthfc258542014-02-11 12:52:27 +0000750 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
751 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
Dan Gohmanb9487362012-08-08 00:00:26 +0000752 Instruction *InsertPos = LoopInsertPts[i];
Chandler Carruthfc258542014-02-11 12:52:27 +0000753 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000754 NewSI->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +0000755 NewSI->setDebugLoc(DL);
Hal Finkelcc39b672014-07-24 12:16:19 +0000756 if (AATags) NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000757 }
758 }
759
Craig Topper3e4c6972014-03-05 09:10:37 +0000760 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000761 // Update alias analysis.
762 AST.copyValue(LI, V);
763 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000764 void instructionDeleted(Instruction *I) const override {
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000765 AST.deleteValue(I);
766 }
767 };
768} // end anon namespace
769
Hal Finkel3d4269a2015-02-22 18:35:32 +0000770/// Try to promote memory values to scalars by sinking stores out of the
771/// loop and moving loads to before the loop. We do this by looping over
772/// the stores in the loop, looking for stores to Must pointers which are
773/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +0000774///
Hal Finkel3d4269a2015-02-22 18:35:32 +0000775bool llvm::promoteLoopAccessesToScalars(AliasSet &AS,
776 SmallVectorImpl<BasicBlock*>&ExitBlocks,
777 SmallVectorImpl<Instruction*>&InsertPts,
778 PredIteratorCache &PIC, LoopInfo *LI,
779 DominatorTree *DT, Loop *CurLoop,
780 AliasSetTracker *CurAST,
781 LICMSafetyInfo * SafetyInfo) {
782 // Verify inputs.
783 assert(LI != nullptr && DT != nullptr &&
784 CurLoop != nullptr && CurAST != nullptr &&
785 SafetyInfo != nullptr &&
786 "Unexpected Input to promoteLoopAccessesToScalars");
787 // Initially set Changed status to false.
788 bool Changed = false;
Chris Lattner1dc98b42010-08-29 06:43:52 +0000789 // We can promote this alias set if it has a store, if it is a "Must" alias
790 // set, if the pointer is loop invariant, and if we are not eliminating any
791 // volatile loads or stores.
792 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
793 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue()))
Hal Finkel3d4269a2015-02-22 18:35:32 +0000794 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000795
Chris Lattner1dc98b42010-08-29 06:43:52 +0000796 assert(!AS.empty() &&
797 "Must alias set should have at least one pointer element in it!");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000798
Chris Lattner1dc98b42010-08-29 06:43:52 +0000799 Value *SomePtr = AS.begin()->getValue();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000800 BasicBlock * Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +0000801
Chris Lattner1dc98b42010-08-29 06:43:52 +0000802 // It isn't safe to promote a load/store from the loop if the load/store is
803 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +0000804 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000805 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +0000806 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000807 // into:
808 //
809 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
810 //
811 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +0000812 //
Chris Lattner1dc98b42010-08-29 06:43:52 +0000813 // It is safe to promote P if all uses are direct load/stores and if at
814 // least one is guaranteed to be executed.
815 bool GuaranteedToExecute = false;
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000816
Chris Lattner1dc98b42010-08-29 06:43:52 +0000817 SmallVector<Instruction*, 64> LoopUses;
818 SmallPtrSet<Value*, 4> PointerMustAliases;
Chris Lattner45d67d62003-02-24 03:52:32 +0000819
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000820 // We start with an alignment of one and try to find instructions that allow
821 // us to prove better alignment.
822 unsigned Alignment = 1;
Hal Finkelcc39b672014-07-24 12:16:19 +0000823 AAMDNodes AATags;
Bruno Cardoso Lopes46d5bf22014-11-28 19:47:46 +0000824 bool HasDedicatedExits = CurLoop->hasDedicatedExits();
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000825
Chris Lattner1dc98b42010-08-29 06:43:52 +0000826 // Check that all of the pointers in the alias set have the same type. We
827 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +0000828 // different sizes. While we are at it, collect alignment and AA info.
Chris Lattner1dc98b42010-08-29 06:43:52 +0000829 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) {
830 Value *ASIV = ASI->getValue();
831 PointerMustAliases.insert(ASIV);
Tobias Grossera3928f52011-07-06 19:20:02 +0000832
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000833 // Check that all of the pointers in the alias set have the same type. We
834 // cannot (yet) promote a memory location that is loaded and stored in
835 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +0000836 if (SomePtr->getType() != ASIV->getType())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000837 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000838
Chandler Carruthcdf47882014-03-09 03:16:01 +0000839 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +0000840 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000841 Instruction *UI = dyn_cast<Instruction>(U);
842 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +0000843 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +0000844
Chris Lattner1dc98b42010-08-29 06:43:52 +0000845 // If there is an non-load/store instruction in the loop, we can't promote
846 // it.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000847 if (LoadInst *load = dyn_cast<LoadInst>(UI)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000848 assert(!load->isVolatile() && "AST broken");
849 if (!load->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000850 return Changed;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000851 } else if (StoreInst *store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +0000852 // Stores *of* the pointer are not interesting, only stores *to* the
853 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000854 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +0000855 continue;
Eli Friedman91386c72011-08-15 20:52:09 +0000856 assert(!store->isVolatile() && "AST broken");
857 if (!store->isSimple())
Hal Finkel3d4269a2015-02-22 18:35:32 +0000858 return Changed;
Bruno Cardoso Lopes46d5bf22014-11-28 19:47:46 +0000859 // Don't sink stores from loops without dedicated block exits. Exits
860 // containing indirect branches are not transformed by loop simplify,
Bruno Cardoso Lopesd035fbb2014-12-02 14:22:34 +0000861 // make sure we catch that. An additional load may be generated in the
862 // preheader for SSA updater, so also avoid sinking when no preheader
863 // is available.
864 if (!HasDedicatedExits || !Preheader)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000865 return Changed;
Eli Friedman0cdc1482011-07-20 21:37:47 +0000866
867 // Note that we only check GuaranteedToExecute inside the store case
868 // so that we do not introduce stores where they did not exist before
869 // (which would break the LLVM concurrency model).
870
871 // If the alignment of this instruction allows us to specify a more
872 // restrictive (and performant) alignment and if we are sure this
873 // instruction will be executed, update the alignment.
874 // Larger is better, with the exception of 0 being the best alignment.
Eli Friedman91386c72011-08-15 20:52:09 +0000875 unsigned InstAlignment = store->getAlignment();
Chris Lattnerf5cca682012-12-31 08:37:17 +0000876 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000877 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Eli Friedman0cdc1482011-07-20 21:37:47 +0000878 GuaranteedToExecute = true;
879 Alignment = InstAlignment;
880 }
881
882 if (!GuaranteedToExecute)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000883 GuaranteedToExecute = isGuaranteedToExecute(*UI, DT,
884 CurLoop, SafetyInfo);
Eli Friedman0cdc1482011-07-20 21:37:47 +0000885
Chris Lattnerbe901902010-09-06 05:11:24 +0000886 } else
Hal Finkel3d4269a2015-02-22 18:35:32 +0000887 return Changed; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000888
Hal Finkelcc39b672014-07-24 12:16:19 +0000889 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +0000890 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +0000891 // On the first load/store, just take its AA tags.
892 UI->getAAMetadata(AATags);
893 } else if (AATags) {
894 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +0000895 }
Chandler Carruthcdf47882014-03-09 03:16:01 +0000896
897 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +0000898 }
899 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000900
Chris Lattner1dc98b42010-08-29 06:43:52 +0000901 // If there isn't a guaranteed-to-execute instruction, we can't promote.
902 if (!GuaranteedToExecute)
Hal Finkel3d4269a2015-02-22 18:35:32 +0000903 return Changed;
Tobias Grossera3928f52011-07-06 19:20:02 +0000904
Chris Lattner1dc98b42010-08-29 06:43:52 +0000905 // Otherwise, this is safe to promote, lets do it!
Tobias Grossera3928f52011-07-06 19:20:02 +0000906 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " <<*SomePtr<<'\n');
Chris Lattner1dc98b42010-08-29 06:43:52 +0000907 Changed = true;
908 ++NumPromoted;
909
Eli Friedmanddf7f552011-05-27 20:31:51 +0000910 // Grab a debug location for the inserted loads/stores; given that the
911 // inserted loads/stores have little relation to the original loads/stores,
912 // this code just arbitrarily picks a location from one, since any debug
913 // location is better than none.
914 DebugLoc DL = LoopUses[0]->getDebugLoc();
915
Dan Gohmanb9487362012-08-08 00:00:26 +0000916 // Figure out the loop exits and their insertion points, if this is the
917 // first promotion.
918 if (ExitBlocks.empty()) {
919 CurLoop->getUniqueExitBlocks(ExitBlocks);
920 InsertPts.resize(ExitBlocks.size());
921 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
922 InsertPts[i] = ExitBlocks[i]->getFirstInsertionPt();
923 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000924
Chris Lattner1dc98b42010-08-29 06:43:52 +0000925 // We use the SSAUpdater interface to insert phi nodes as required.
926 SmallVector<PHINode*, 16> NewPHIs;
927 SSAUpdater SSA(&NewPHIs);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000928 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Hal Finkelcc39b672014-07-24 12:16:19 +0000929 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +0000930
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000931 // Set up the preheader to have a definition of the value. It is the live-out
932 // value from the preheader that uses in the loop will use.
933 LoadInst *PreheaderLoad =
934 new LoadInst(SomePtr, SomePtr->getName()+".promoted",
935 Preheader->getTerminator());
Tobias Grosser4a5d9a92011-07-06 19:19:55 +0000936 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +0000937 PreheaderLoad->setDebugLoc(DL);
Hal Finkelcc39b672014-07-24 12:16:19 +0000938 if (AATags) PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +0000939 SSA.AddAvailableValue(Preheader, PreheaderLoad);
940
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000941 // Rewrite all the loads in the loop and remember all the definitions from
942 // stores in the loop.
943 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +0000944
945 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
946 if (PreheaderLoad->use_empty())
947 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000948
949 return Changed;
Chris Lattnera51fa882002-08-22 21:39:55 +0000950}
Devang Patelb98a0972007-07-31 08:01:41 +0000951
Hal Finkel3d4269a2015-02-22 18:35:32 +0000952/// Simple Analysis hook. Clone alias set info.
953///
Devang Patelb98a0972007-07-31 08:01:41 +0000954void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000955 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +0000956 if (!AST)
957 return;
958
959 AST->copyValue(From, To);
960}
961
Hal Finkel3d4269a2015-02-22 18:35:32 +0000962/// Simple Analysis hook. Delete value V from alias set
963///
Devang Patelb98a0972007-07-31 08:01:41 +0000964void LICM::deleteAnalysisValue(Value *V, Loop *L) {
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000965 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +0000966 if (!AST)
967 return;
968
969 AST->deleteValue(V);
970}
David Peixotto0d4d5e62014-09-24 16:48:31 +0000971
972/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000973///
David Peixotto0d4d5e62014-09-24 16:48:31 +0000974void LICM::deleteAnalysisLoop(Loop *L) {
975 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L);
976 if (!AST)
977 return;
978
979 delete AST;
980 LoopToAliasSetMap.erase(L);
981}
Hal Finkel3d4269a2015-02-22 18:35:32 +0000982
983
984/// Return true if the body of this loop may store into the memory
985/// location pointed to by V.
986///
987static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
988 const AAMDNodes &AAInfo,
989 AliasSetTracker *CurAST) {
990 // Check to see if any of the basic blocks in CurLoop invalidate *V.
991 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
992}
993
994/// Little predicate that returns true if the specified basic block is in
995/// a subloop of the current one, not the current one itself.
996///
997static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
998 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
999 return LI->getLoopFor(BB) != CurLoop;
1000}
1001