blob: 0cc70d4244753d1ebb98ac5767dc102d13e9738e [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
Dehao Chen9cba1f42016-07-12 22:37:48 +000033#include "llvm/Transforms/Scalar/LICM.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000034#include "llvm/ADT/Statistic.h"
Chris Lattnera51fa882002-08-22 21:39:55 +000035#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner0592bb72003-03-03 23:32:45 +000036#include "llvm/Analysis/AliasSetTracker.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000037#include "llvm/Analysis/BasicAliasAnalysis.h"
Philip Reamesb54c8e62016-03-09 22:59:30 +000038#include "llvm/Analysis/CaptureTracking.h"
Chris Lattner030f0202010-08-31 23:00:16 +000039#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000040#include "llvm/Analysis/GlobalsModRef.h"
Philip Reamese0a54542016-03-09 23:07:53 +000041#include "llvm/Analysis/Loads.h"
Chris Lattner030f0202010-08-31 23:00:16 +000042#include "llvm/Analysis/LoopInfo.h"
43#include "llvm/Analysis/LoopPass.h"
Philip Reamesb54c8e62016-03-09 22:59:30 +000044#include "llvm/Analysis/MemoryBuiltins.h"
Adam Nemet0965da22017-10-09 23:19:02 +000045#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Chandler Carruthabfa3e52014-01-24 01:59:49 +000046#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000047#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000048#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000049#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000050#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Constants.h"
52#include "llvm/IR/DataLayout.h"
53#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000054#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/Instructions.h"
56#include "llvm/IR/IntrinsicInst.h"
57#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000058#include "llvm/IR/Metadata.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000059#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000060#include "llvm/Support/CommandLine.h"
61#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000062#include "llvm/Support/raw_ostream.h"
Dehao Chend55bc4c2016-05-05 00:54:54 +000063#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000064#include "llvm/Transforms/Scalar/LoopPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000065#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000066#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000067#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000068#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000069#include <utility>
Chris Lattnerc0517682003-12-09 17:18:00 +000070using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000071
Chandler Carruth964daaa2014-04-22 02:55:47 +000072#define DEBUG_TYPE "licm"
73
Dehao Chend55bc4c2016-05-05 00:54:54 +000074STATISTIC(NumSunk, "Number of instructions sunk out of loop");
75STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
Chris Lattner79a42ac2006-12-19 21:40:18 +000076STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
77STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
Dehao Chend55bc4c2016-05-05 00:54:54 +000078STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
Chris Lattner79a42ac2006-12-19 21:40:18 +000079
Xin Tongccee0e02017-02-21 20:53:48 +000080/// Memory promotion is enabled by default.
Dan Gohmand78c4002008-05-13 00:00:25 +000081static cl::opt<bool>
Xin Tongccee0e02017-02-21 20:53:48 +000082 DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
Dehao Chend55bc4c2016-05-05 00:54:54 +000083 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000084
Anna Thomas7f4b26e2017-02-02 13:22:03 +000085static cl::opt<uint32_t> MaxNumUsesTraversed(
86 "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
87 cl::desc("Max num uses visited for identifying load "
88 "invariance in loop using invariant start (default = 8)"));
89
Hal Finkel3d4269a2015-02-22 18:35:32 +000090static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
David Majnemer42a07302016-01-04 03:37:39 +000091static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +000092 const LoopSafetyInfo *SafetyInfo);
Sanjoy Das7a2e2be2016-01-28 15:51:58 +000093static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +000094 const LoopSafetyInfo *SafetyInfo,
95 OptimizationRemarkEmitter *ORE);
Pete Cooper0cabcf22015-05-13 01:12:18 +000096static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +000097 const Loop *CurLoop, AliasSetTracker *CurAST,
Adam Nemet358433c2017-01-11 04:39:35 +000098 const LoopSafetyInfo *SafetyInfo,
99 OptimizationRemarkEmitter *ORE);
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000100static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000101 const DominatorTree *DT,
102 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000103 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000104 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000105 const Instruction *CtxI = nullptr);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000106static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +0000107 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +0000108 AliasSetTracker *CurAST);
David Majnemer42a07302016-01-04 03:37:39 +0000109static Instruction *
110CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
111 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000112 const LoopSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000113
Dan Gohmand78c4002008-05-13 00:00:25 +0000114namespace {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000115struct LoopInvariantCodeMotion {
116 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
Adam Nemet358433c2017-01-11 04:39:35 +0000117 TargetLibraryInfo *TLI, ScalarEvolution *SE,
118 OptimizationRemarkEmitter *ORE, bool DeleteAST);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000119
120 DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() {
121 return LoopToAliasSetMap;
Dehao Chen7ef58202016-07-11 22:45:24 +0000122 }
123
Dehao Chen9cba1f42016-07-12 22:37:48 +0000124private:
125 DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
126
127 AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
128 AliasAnalysis *AA);
129};
130
131struct LegacyLICMPass : public LoopPass {
132 static char ID; // Pass identification, replacement for typeid
133 LegacyLICMPass() : LoopPass(ID) {
134 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
135 }
136
137 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Davide Italiano34f94382016-12-23 13:12:50 +0000138 if (skipLoop(L)) {
139 // If we have run LICM on a previous loop but now we are skipping
140 // (because we've hit the opt-bisect limit), we need to clear the
141 // loop alias information.
Davide Italianob9ff23a2016-12-23 15:02:35 +0000142 for (auto &LTAS : LICM.getLoopToAliasSetMap())
143 delete LTAS.second;
Davide Italiano34f94382016-12-23 13:12:50 +0000144 LICM.getLoopToAliasSetMap().clear();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000145 return false;
Davide Italiano34f94382016-12-23 13:12:50 +0000146 }
Dehao Chen9cba1f42016-07-12 22:37:48 +0000147
148 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
Adam Nemet358433c2017-01-11 04:39:35 +0000149 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
150 // pass. Function analyses need to be preserved across loop transformations
151 // but ORE cannot be preserved (see comment before the pass definition).
152 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
Dehao Chen9cba1f42016-07-12 22:37:48 +0000153 return LICM.runOnLoop(L,
154 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
155 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
156 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
157 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Adam Nemet358433c2017-01-11 04:39:35 +0000158 SE ? &SE->getSE() : nullptr, &ORE, false);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000159 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000160
Dehao Chend55bc4c2016-05-05 00:54:54 +0000161 /// This transformation requires natural loop information & requires that
162 /// loop preheaders be inserted into the CFG...
163 ///
164 void getAnalysisUsage(AnalysisUsage &AU) const override {
165 AU.setPreservesCFG();
166 AU.addRequired<TargetLibraryInfoWrapperPass>();
167 getLoopAnalysisUsage(AU);
168 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000169
Dehao Chend55bc4c2016-05-05 00:54:54 +0000170 using llvm::Pass::doFinalization;
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000171
Dehao Chend55bc4c2016-05-05 00:54:54 +0000172 bool doFinalization() override {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000173 assert(LICM.getLoopToAliasSetMap().empty() &&
174 "Didn't free loop alias sets");
Dehao Chend55bc4c2016-05-05 00:54:54 +0000175 return false;
176 }
Devang Patel69730c92007-03-07 04:41:30 +0000177
Dehao Chend55bc4c2016-05-05 00:54:54 +0000178private:
Dehao Chen9cba1f42016-07-12 22:37:48 +0000179 LoopInvariantCodeMotion LICM;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000180
Dehao Chend55bc4c2016-05-05 00:54:54 +0000181 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
182 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
183 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000184
Dehao Chend55bc4c2016-05-05 00:54:54 +0000185 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
186 /// set.
187 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000188
Dehao Chend55bc4c2016-05-05 00:54:54 +0000189 /// Simple Analysis hook. Delete loop L from alias set map.
190 void deleteAnalysisLoop(Loop *L) override;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000191};
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000192} // namespace
Chris Lattner6ec05f52002-05-10 22:44:58 +0000193
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000194PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
195 LoopStandardAnalysisResults &AR, LPMUpdater &) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000196 const auto &FAM =
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000197 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000198 Function *F = L.getHeader()->getParent();
199
Adam Nemet358433c2017-01-11 04:39:35 +0000200 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000201 // FIXME: This should probably be optional rather than required.
202 if (!ORE)
203 report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
204 "cached at a higher level");
Dehao Chen9cba1f42016-07-12 22:37:48 +0000205
206 LoopInvariantCodeMotion LICM;
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000207 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.SE, ORE, true))
Dehao Chen9cba1f42016-07-12 22:37:48 +0000208 return PreservedAnalyses::all();
209
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000210 auto PA = getLoopPassPreservedAnalyses();
211 PA.preserveSet<CFGAnalyses>();
212 return PA;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000213}
214
215char LegacyLICMPass::ID = 0;
216INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
217 false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000218INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000219INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000220INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
221 false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000222
Dehao Chen9cba1f42016-07-12 22:37:48 +0000223Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000224
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000225/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000226/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000227/// times on one loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000228/// We should delete AST for inner loops in the new pass manager to avoid
229/// memory leak.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000230///
Dehao Chen9cba1f42016-07-12 22:37:48 +0000231bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AliasAnalysis *AA,
232 LoopInfo *LI, DominatorTree *DT,
233 TargetLibraryInfo *TLI,
Adam Nemet358433c2017-01-11 04:39:35 +0000234 ScalarEvolution *SE,
235 OptimizationRemarkEmitter *ORE,
236 bool DeleteAST) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000237 bool Changed = false;
Chad Rosier43a33062011-12-02 01:26:24 +0000238
Chandler Carruthfc258542014-02-11 12:52:27 +0000239 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
240
Dehao Chen9cba1f42016-07-12 22:37:48 +0000241 AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000242
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000243 // Get the preheader block to move instructions into...
Dehao Chen9cba1f42016-07-12 22:37:48 +0000244 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000245
Hal Finkel3d4269a2015-02-22 18:35:32 +0000246 // Compute loop safety information.
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000247 LoopSafetyInfo SafetyInfo;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000248 computeLoopSafetyInfo(&SafetyInfo, L);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000249
Chris Lattner6ec05f52002-05-10 22:44:58 +0000250 // We want to visit all of the instructions in this loop... that are not parts
251 // of our subloops (they have already had their invariants hoisted out of
252 // their loop, into this loop, so there is no need to process the BODIES of
253 // the subloops).
254 //
Chris Lattner64437692002-09-29 21:46:09 +0000255 // Traverse the body of the loop in depth first order on the dominator tree so
256 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000257 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000258 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000259 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000260 if (L->hasDedicatedExits())
Dehao Chen9cba1f42016-07-12 22:37:48 +0000261 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
Adam Nemet358433c2017-01-11 04:39:35 +0000262 CurAST, &SafetyInfo, ORE);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000263 if (Preheader)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000264 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
Adam Nemet358433c2017-01-11 04:39:35 +0000265 CurAST, &SafetyInfo, ORE);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000266
Chris Lattner45d67d62003-02-24 03:52:32 +0000267 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000268 // memory references to scalars that we can.
Michael Kuperstein55660922016-12-29 22:51:22 +0000269 // Don't sink stores from loops without dedicated block exits. Exits
270 // containing indirect branches are not transformed by loop simplify,
271 // make sure we catch that. An additional load may be generated in the
272 // preheader for SSA updater, so also avoid sinking when no preheader
273 // is available.
274 if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000275 // Figure out the loop exits and their insertion points
Dan Gohmanb9487362012-08-08 00:00:26 +0000276 SmallVector<BasicBlock *, 8> ExitBlocks;
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000277 L->getUniqueExitBlocks(ExitBlocks);
Dan Gohmanb9487362012-08-08 00:00:26 +0000278
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000279 // We can't insert into a catchswitch.
280 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
281 return isa<CatchSwitchInst>(Exit->getTerminator());
282 });
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000283
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000284 if (!HasCatchSwitch) {
285 SmallVector<Instruction *, 8> InsertPts;
286 InsertPts.reserve(ExitBlocks.size());
287 for (BasicBlock *ExitBlock : ExitBlocks)
288 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
Chandler Carruth16651522014-02-01 13:35:14 +0000289
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000290 PredIteratorCache PIC;
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000291
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000292 bool Promoted = false;
293
294 // Loop over all of the alias sets in the tracker object.
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000295 for (AliasSet &AS : *CurAST) {
296 // We can promote this alias set if it has a store, if it is a "Must"
297 // alias set, if the pointer is loop invariant, and if we are not
298 // eliminating any volatile loads or stores.
299 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
300 AS.isVolatile() || !L->isLoopInvariant(AS.begin()->getValue()))
301 continue;
302
303 assert(
304 !AS.empty() &&
305 "Must alias set should have at least one pointer element in it!");
306
307 SmallSetVector<Value *, 8> PointerMustAliases;
308 for (const auto &ASI : AS)
309 PointerMustAliases.insert(ASI.getValue());
310
311 Promoted |= promoteLoopAccessesToScalars(PointerMustAliases, ExitBlocks,
312 InsertPts, PIC, LI, DT, TLI, L,
313 CurAST, &SafetyInfo, ORE);
314 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000315
316 // Once we have promoted values across the loop body we have to
317 // recursively reform LCSSA as any nested loop may now have values defined
318 // within the loop used in the outer loop.
319 // FIXME: This is really heavy handed. It would be a bit better to use an
320 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
321 // it as it went.
322 if (Promoted)
323 formLCSSARecursively(*L, *DT, LI, SE);
324
325 Changed |= Promoted;
326 }
Chris Lattner1dc98b42010-08-29 06:43:52 +0000327 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000328
Chandler Carruthfc258542014-02-11 12:52:27 +0000329 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
330 // specifically moving instructions across the loop boundary and so it is
331 // especially in need of sanity checking here.
332 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
333 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
334 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000335
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000336 // If this loop is nested inside of another one, save the alias information
337 // for when we process the outer loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000338 if (L->getParentLoop() && !DeleteAST)
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000339 LoopToAliasSetMap[L] = CurAST;
340 else
341 delete CurAST;
Sanjoy Das4ae39202016-05-03 17:50:11 +0000342
Dehao Chen9cba1f42016-07-12 22:37:48 +0000343 if (Changed && SE)
344 SE->forgetLoopDispositions(L);
Devang Patel69730c92007-03-07 04:41:30 +0000345 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000346}
347
Hal Finkel3d4269a2015-02-22 18:35:32 +0000348/// Walk the specified region of the CFG (defined by all blocks dominated by
Dehao Chend55bc4c2016-05-05 00:54:54 +0000349/// the specified block, and that are in the current loop) in reverse depth
Hal Finkel3d4269a2015-02-22 18:35:32 +0000350/// first order w.r.t the DominatorTree. This allows us to visit uses before
351/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000352///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000353bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
354 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000355 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
356 OptimizationRemarkEmitter *ORE) {
Chris Lattner547192d62003-12-19 07:22:45 +0000357
Hal Finkel3d4269a2015-02-22 18:35:32 +0000358 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000359 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
360 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
361 "Unexpected input to sinkRegion");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000362
David Majnemere6bb8952017-07-20 03:27:02 +0000363 // We want to visit children before parents. We will enque all the parents
364 // before their children in the worklist and process the worklist in reverse
365 // order.
366 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
Chris Lattner547192d62003-12-19 07:22:45 +0000367
Sanjay Patel99133222016-01-13 23:01:57 +0000368 bool Changed = false;
David Majnemere6bb8952017-07-20 03:27:02 +0000369 for (DomTreeNode *DTN : reverse(Worklist)) {
370 BasicBlock *BB = DTN->getBlock();
371 // Only need to process the contents of this block if it is not part of a
372 // subloop (which would already have been processed).
373 if (inSubLoop(BB, CurLoop, LI))
Chris Lattner263f8042010-08-29 18:22:25 +0000374 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000375
David Majnemere6bb8952017-07-20 03:27:02 +0000376 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
377 Instruction &I = *--II;
378
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000379 // If the instruction is dead, we would try to sink it because it isn't
380 // used in the loop, instead, just delete it.
David Majnemere6bb8952017-07-20 03:27:02 +0000381 if (isInstructionTriviallyDead(&I, TLI)) {
382 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
383 ++II;
384 CurAST->deleteValue(&I);
385 I.eraseFromParent();
386 Changed = true;
387 continue;
388 }
389
390 // Check to see if we can sink this instruction to the exit blocks
391 // of the loop. We can do this if the all users of the instruction are
392 // outside of the loop. In this case, it doesn't even matter if the
393 // operands of the instruction are loop invariant.
394 //
395 if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
396 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE)) {
397 ++II;
398 Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo, ORE);
399 }
Chris Lattner91846012003-12-19 08:18:16 +0000400 }
Chris Lattner547192d62003-12-19 07:22:45 +0000401 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000402 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000403}
404
Hal Finkel3d4269a2015-02-22 18:35:32 +0000405/// Walk the specified region of the CFG (defined by all blocks dominated by
406/// the specified block, and that are in the current loop) in depth first
407/// order w.r.t the DominatorTree. This allows us to visit definitions before
408/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000409///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000410bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
411 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000412 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
413 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000414 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000415 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
416 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
417 "Unexpected input to hoistRegion");
Sanjay Patel99133222016-01-13 23:01:57 +0000418
David Majnemere6bb8952017-07-20 03:27:02 +0000419 // We want to visit parents before children. We will enque all the parents
420 // before their children in the worklist and process the worklist in order.
421 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
Sanjay Patel99133222016-01-13 23:01:57 +0000422
Sanjay Patel99133222016-01-13 23:01:57 +0000423 bool Changed = false;
David Majnemere6bb8952017-07-20 03:27:02 +0000424 for (DomTreeNode *DTN : Worklist) {
425 BasicBlock *BB = DTN->getBlock();
426 // Only need to process the contents of this block if it is not part of a
427 // subloop (which would already have been processed).
428 if (!inSubLoop(BB, CurLoop, LI))
429 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
430 Instruction &I = *II++;
431 // Try constant folding this instruction. If all the operands are
432 // constants, it is technically hoistable, but it would be better to
433 // just fold it.
434 if (Constant *C = ConstantFoldInstruction(
435 &I, I.getModule()->getDataLayout(), TLI)) {
436 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
437 CurAST->copyValue(&I, C);
438 I.replaceAllUsesWith(C);
439 if (isInstructionTriviallyDead(&I, TLI)) {
440 CurAST->deleteValue(&I);
441 I.eraseFromParent();
442 }
443 Changed = true;
444 continue;
David Majnemer522a9112016-07-22 04:54:44 +0000445 }
David Majnemere6bb8952017-07-20 03:27:02 +0000446
447 // Attempt to remove floating point division out of the loop by
448 // converting it to a reciprocal multiplication.
449 if (I.getOpcode() == Instruction::FDiv &&
450 CurLoop->isLoopInvariant(I.getOperand(1)) &&
451 I.hasAllowReciprocal()) {
452 auto Divisor = I.getOperand(1);
453 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
454 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
455 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
456 ReciprocalDivisor->insertBefore(&I);
457
458 auto Product =
459 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
460 Product->setFastMathFlags(I.getFastMathFlags());
461 Product->insertAfter(&I);
462 I.replaceAllUsesWith(Product);
463 I.eraseFromParent();
464
465 hoist(*ReciprocalDivisor, DT, CurLoop, SafetyInfo, ORE);
466 Changed = true;
467 continue;
468 }
469
470 // Try hoisting the instruction out to the preheader. We can only do
471 // this if all of the operands of the instruction are loop invariant and
472 // if it is safe to hoist the instruction.
473 //
474 if (CurLoop->hasLoopInvariantOperands(&I) &&
475 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE) &&
476 isSafeToExecuteUnconditionally(
477 I, DT, CurLoop, SafetyInfo, ORE,
478 CurLoop->getLoopPreheader()->getTerminator()))
479 Changed |= hoist(I, DT, CurLoop, SafetyInfo, ORE);
Chris Lattner030f0202010-08-31 23:00:16 +0000480 }
David Majnemere6bb8952017-07-20 03:27:02 +0000481 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000482
Hal Finkel3d4269a2015-02-22 18:35:32 +0000483 return Changed;
484}
485
486/// Computes loop safety information, checks loop body & header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000487/// for the possibility of may throw exception.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000488///
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000489void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000490 assert(CurLoop != nullptr && "CurLoop cant be null");
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +0000491 BasicBlock *Header = CurLoop->getHeader();
492 // Setting default safety values.
493 SafetyInfo->MayThrow = false;
494 SafetyInfo->HeaderMayThrow = false;
495 // Iterate over header and compute safety info.
496 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
497 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
498 SafetyInfo->HeaderMayThrow |=
499 !isGuaranteedToTransferExecutionToSuccessor(&*I);
500
501 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
502 // Iterate over loop instructions and compute safety info.
503 // Skip header as it has been computed and stored in HeaderMayThrow.
504 // The first block in loopinfo.Blocks is guaranteed to be the header.
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000505 assert(Header == *CurLoop->getBlocks().begin() &&
506 "First block must be header");
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +0000507 for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
Dehao Chend55bc4c2016-05-05 00:54:54 +0000508 BBE = CurLoop->block_end();
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +0000509 (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
510 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
511 (I != E) && !SafetyInfo->MayThrow; ++I)
512 SafetyInfo->MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I);
David Majnemer42a07302016-01-04 03:37:39 +0000513
514 // Compute funclet colors if we might sink/hoist in a function with a funclet
515 // personality routine.
516 Function *Fn = CurLoop->getHeader()->getParent();
517 if (Fn->hasPersonalityFn())
518 if (Constant *PersonalityFn = Fn->getPersonalityFn())
519 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
520 SafetyInfo->BlockColors = colorEHFunclets(*Fn);
Chris Lattner64437692002-09-29 21:46:09 +0000521}
522
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000523// Return true if LI is invariant within scope of the loop. LI is invariant if
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000524// CurLoop is dominated by an invariant.start representing the same memory
525// location and size as the memory location LI loads from, and also the
526// invariant.start has no uses.
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000527static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
528 Loop *CurLoop) {
529 Value *Addr = LI->getOperand(0);
530 const DataLayout &DL = LI->getModule()->getDataLayout();
531 const uint32_t LocSizeInBits = DL.getTypeSizeInBits(
532 cast<PointerType>(Addr->getType())->getElementType());
533
534 // if the type is i8 addrspace(x)*, we know this is the type of
535 // llvm.invariant.start operand
536 auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
537 LI->getPointerAddressSpace());
538 unsigned BitcastsVisited = 0;
539 // Look through bitcasts until we reach the i8* type (this is invariant.start
540 // operand type).
541 while (Addr->getType() != PtrInt8Ty) {
542 auto *BC = dyn_cast<BitCastInst>(Addr);
543 // Avoid traversing high number of bitcast uses.
544 if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
545 return false;
546 Addr = BC->getOperand(0);
547 }
548
549 unsigned UsesVisited = 0;
550 // Traverse all uses of the load operand value, to see if invariant.start is
551 // one of the uses, and whether it dominates the load instruction.
552 for (auto *U : Addr->users()) {
553 // Avoid traversing for Load operand with high number of users.
554 if (++UsesVisited > MaxNumUsesTraversed)
555 return false;
556 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
557 // If there are escaping uses of invariant.start instruction, the load maybe
558 // non-invariant.
559 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
Davide Italiano79eb3b02017-05-16 22:38:40 +0000560 !II->use_empty())
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000561 continue;
562 unsigned InvariantSizeInBits =
563 cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
564 // Confirm the invariant.start location size contains the load operand size
565 // in bits. Also, the invariant.start should dominate the load, and we
566 // should not hoist the load out of a loop that contains this dominating
567 // invariant.start.
568 if (LocSizeInBits <= InvariantSizeInBits &&
569 DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
570 return true;
571 }
572
573 return false;
574}
575
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000576bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
577 Loop *CurLoop, AliasSetTracker *CurAST,
Adam Nemet81941b32017-01-11 04:39:45 +0000578 LoopSafetyInfo *SafetyInfo,
579 OptimizationRemarkEmitter *ORE) {
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000580 // SafetyInfo is nullptr if we are checking for sinking from preheader to
581 // loop body.
582 const bool SinkingToLoopBody = !SafetyInfo;
Chris Lattner65c11932003-12-09 19:32:44 +0000583 // Loads have extra constraints we have to verify before we can hoist them.
584 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000585 if (!LI->isUnordered())
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000586 return false; // Don't sink/hoist volatile or ordered atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000587
Chris Lattner8a8fb902008-07-23 05:06:28 +0000588 // Loads from constant memory are always safe to move, even if they end up
589 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000590 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000591 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000592 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000593 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000594
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000595 if (LI->isAtomic() && SinkingToLoopBody)
596 return false; // Don't sink unordered atomic loads to loop body.
597
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000598 // This checks for an invariant.start dominating the load.
599 if (isLoadInvariantInLoop(LI, DT, CurLoop))
600 return true;
601
Chris Lattner65c11932003-12-09 19:32:44 +0000602 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000603 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000604 if (LI->getType()->isSized())
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000605 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000606
607 AAMDNodes AAInfo;
608 LI->getAAMetadata(AAInfo);
609
Adam Nemet81941b32017-01-11 04:39:45 +0000610 bool Invalidated =
611 pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
612 // Check loop-invariant address because this may also be a sinkable load
613 // whose address is not necessarily loop-invariant.
614 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
615 ORE->emit(OptimizationRemarkMissed(
616 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
617 << "failed to move load with loop-invariant address "
618 "because the loop may invalidate its value");
619
620 return !Invalidated;
Chris Lattner20cda262004-03-15 04:11:30 +0000621 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000622 // Don't sink or hoist dbg info; it's legal, but not useful.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000623 if (isa<DbgInfoIntrinsic>(I))
Eli Friedman942e1c12011-05-27 18:37:52 +0000624 return false;
625
David Majnemer42a07302016-01-04 03:37:39 +0000626 // Don't sink calls which can throw.
627 if (CI->mayThrow())
628 return false;
629
Eli Friedman942e1c12011-05-27 18:37:52 +0000630 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000631 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
632 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000633 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000634 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Philip Reames5f994232015-09-21 22:27:59 +0000635 // A readonly argmemonly function only reads from memory pointed to by
636 // it's arguments with arbitrary offsets. If we can prove there are no
637 // writes to this memory in the loop, we can hoist or sink.
638 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
639 for (Value *Op : CI->arg_operands())
640 if (Op->getType()->isPointerTy() &&
641 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
642 AAMDNodes(), CurAST))
643 return false;
644 return true;
645 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000646 // If this call only reads from memory and there are no writes to memory
647 // in the loop, we can hoist or sink the call as appropriate.
648 bool FoundMod = false;
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000649 for (AliasSet &AS : *CurAST) {
Duncan Sands68b6f502007-12-01 07:51:45 +0000650 if (!AS.isForwardingAliasSet() && AS.isMod()) {
651 FoundMod = true;
652 break;
Chris Lattner20cda262004-03-15 04:11:30 +0000653 }
Chris Lattner20cda262004-03-15 04:11:30 +0000654 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000655 if (!FoundMod)
656 return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000657 }
658
Nadav Rotem03dcd852012-09-04 10:25:04 +0000659 // FIXME: This should use mod/ref information to see if we can hoist or
660 // sink the call.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000661
Chris Lattner20cda262004-03-15 04:11:30 +0000662 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000663 }
664
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000665 // Only these instructions are hoistable/sinkable.
666 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
667 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
668 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
669 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
670 !isa<InsertValueInst>(I))
671 return false;
672
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000673 // If we are checking for sinking from preheader to loop body it will be
674 // always safe as there is no speculative execution.
675 if (SinkingToLoopBody)
Dehao Chen92abc7e2016-10-03 18:52:08 +0000676 return true;
677
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000678 // TODO: Plumb the context instruction through to make hoisting and sinking
679 // more powerful. Hoisting of loads already works due to the special casing
680 // above.
681 return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr);
Chris Lattneraaaea512003-12-10 06:41:05 +0000682}
683
Hal Finkel3d4269a2015-02-22 18:35:32 +0000684/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000685/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000686/// This is true when all incoming values are that instruction.
687/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000688///
Pete Cooper47e80cd2015-05-12 20:05:20 +0000689static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000690 for (const Value *IncValue : PN.incoming_values())
691 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000692 return false;
693
694 return true;
695}
696
Hal Finkel3d4269a2015-02-22 18:35:32 +0000697/// Return true if the only users of this instruction are outside of
698/// the loop. If this is true, we can sink the instruction to the exit
699/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000700///
David Majnemer42a07302016-01-04 03:37:39 +0000701static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000702 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000703 const auto &BlockColors = SafetyInfo->BlockColors;
Pete Cooper0cabcf22015-05-13 01:12:18 +0000704 for (const User *U : I.users()) {
705 const Instruction *UI = cast<Instruction>(U);
706 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Majnemer42a07302016-01-04 03:37:39 +0000707 const BasicBlock *BB = PN->getParent();
708 // We cannot sink uses in catchswitches.
709 if (isa<CatchSwitchInst>(BB->getTerminator()))
710 return false;
711
712 // We need to sink a callsite to a unique funclet. Avoid sinking if the
713 // phi use is too muddled.
714 if (isa<CallInst>(I))
715 if (!BlockColors.empty() &&
716 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
717 return false;
718
Chandler Carruth8765cf72014-01-25 04:07:24 +0000719 // A PHI node where all of the incoming values are this instruction are
720 // special -- they can just be RAUW'ed with the instruction and thus
721 // don't require a use in the predecessor. This is a particular important
722 // special case because it is the pattern found in LCSSA form.
723 if (isTriviallyReplacablePHI(*PN, I)) {
724 if (CurLoop->contains(PN))
725 return false;
726 else
727 continue;
728 }
729
730 // Otherwise, PHI node uses occur in predecessor blocks if the incoming
731 // values. Check for such a use being inside the loop.
Chris Lattner34399dd2003-12-11 22:23:32 +0000732 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
733 if (PN->getIncomingValue(i) == &I)
734 if (CurLoop->contains(PN->getIncomingBlock(i)))
735 return false;
Chandler Carruth8765cf72014-01-25 04:07:24 +0000736
737 continue;
Chris Lattner34399dd2003-12-11 22:23:32 +0000738 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000739
Chandler Carruthcdf47882014-03-09 03:16:01 +0000740 if (CurLoop->contains(UI))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000741 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000742 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000743 return true;
744}
745
David Majnemer42a07302016-01-04 03:37:39 +0000746static Instruction *
747CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
748 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000749 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000750 Instruction *New;
751 if (auto *CI = dyn_cast<CallInst>(&I)) {
752 const auto &BlockColors = SafetyInfo->BlockColors;
753
754 // Sinking call-sites need to be handled differently from other
755 // instructions. The cloned call-site needs a funclet bundle operand
756 // appropriate for it's location in the CFG.
757 SmallVector<OperandBundleDef, 1> OpBundles;
758 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
759 BundleIdx != BundleEnd; ++BundleIdx) {
760 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
761 if (Bundle.getTagID() == LLVMContext::OB_funclet)
762 continue;
763
764 OpBundles.emplace_back(Bundle);
765 }
766
767 if (!BlockColors.empty()) {
768 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
769 assert(CV.size() == 1 && "non-unique color for exit block!");
770 BasicBlock *BBColor = CV.front();
771 Instruction *EHPad = BBColor->getFirstNonPHI();
772 if (EHPad->isEHPad())
773 OpBundles.emplace_back("funclet", EHPad);
774 }
775
776 New = CallInst::Create(CI, OpBundles);
777 } else {
778 New = I.clone();
779 }
780
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000781 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000782 if (!I.getName().empty())
783 New->setName(I.getName() + ".le");
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000784
785 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
786 // particularly cheap because we can rip off the PHI node that we're
787 // replacing for the number and blocks of the predecessors.
788 // OPT: If this shows up in a profile, we can instead finish sinking all
789 // invariant instructions, and then walk their operands to re-establish
790 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
791 // sinking bottom-up.
792 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
793 ++OI)
794 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
795 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
796 if (!OLoop->contains(&PN)) {
797 PHINode *OpPN =
798 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000799 OInst->getName() + ".lcssa", &ExitBlock.front());
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000800 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
801 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
802 *OI = OpPN;
803 }
804 return New;
805}
806
Hal Finkel3d4269a2015-02-22 18:35:32 +0000807/// When an instruction is found to only be used outside of the loop, this
808/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000809/// This method is guaranteed to remove the original instruction from its
810/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000811///
Pete Cooper0cabcf22015-05-13 01:12:18 +0000812static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT,
David Majnemer42a07302016-01-04 03:37:39 +0000813 const Loop *CurLoop, AliasSetTracker *CurAST,
Adam Nemet358433c2017-01-11 04:39:35 +0000814 const LoopSafetyInfo *SafetyInfo,
815 OptimizationRemarkEmitter *ORE) {
Nick Lewycky299c6df2010-07-30 20:27:01 +0000816 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Adam Nemet358433c2017-01-11 04:39:35 +0000817 ORE->emit(OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
818 << "sinking " << ore::NV("Inst", &I));
Hal Finkel3d4269a2015-02-22 18:35:32 +0000819 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000820 if (isa<LoadInst>(I))
821 ++NumMovedLoads;
822 else if (isa<CallInst>(I))
823 ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000824 ++NumSunk;
825 Changed = true;
826
Chandler Carruthfc258542014-02-11 12:52:27 +0000827#ifndef NDEBUG
828 SmallVector<BasicBlock *, 32> ExitBlocks;
829 CurLoop->getUniqueExitBlocks(ExitBlocks);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000830 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
Hal Finkel3d4269a2015-02-22 18:35:32 +0000831 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +0000832#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +0000833
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000834 // Clones of this instruction. Don't create more than one per exit block!
835 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
836
Chandler Carruthfc258542014-02-11 12:52:27 +0000837 // If this instruction is only used outside of the loop, then all users are
838 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
839 // the instruction.
840 while (!I.use_empty()) {
David Majnemer6bc83e02015-07-12 03:53:05 +0000841 Value::user_iterator UI = I.user_begin();
842 auto *User = cast<Instruction>(*UI);
David Majnemer49428102014-09-02 16:22:00 +0000843 if (!DT->isReachableFromEntry(User->getParent())) {
844 User->replaceUsesOfWith(&I, UndefValue::get(I.getType()));
845 continue;
846 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000847 // The user must be a PHI node.
David Majnemer49428102014-09-02 16:22:00 +0000848 PHINode *PN = cast<PHINode>(User);
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000849
David Majnemer6bc83e02015-07-12 03:53:05 +0000850 // Surprisingly, instructions can be used outside of loops without any
851 // exits. This can only happen in PHI nodes if the incoming block is
852 // unreachable.
853 Use &U = UI.getUse();
854 BasicBlock *BB = PN->getIncomingBlock(U);
855 if (!DT->isReachableFromEntry(BB)) {
856 U = UndefValue::get(I.getType());
857 continue;
858 }
859
Chandler Carruthfc258542014-02-11 12:52:27 +0000860 BasicBlock *ExitBlock = PN->getParent();
861 assert(ExitBlockSet.count(ExitBlock) &&
862 "The LCSSA PHI is not in an exit block!");
863
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000864 Instruction *New;
865 auto It = SunkCopies.find(ExitBlock);
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000866 if (It != SunkCopies.end())
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000867 New = It->second;
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000868 else
869 New = SunkCopies[ExitBlock] =
David Majnemer42a07302016-01-04 03:37:39 +0000870 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo);
Chandler Carruthfc258542014-02-11 12:52:27 +0000871
872 PN->replaceAllUsesWith(New);
873 PN->eraseFromParent();
Chris Lattnercd96b4d2010-08-29 04:28:20 +0000874 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000875
Chris Lattner1a1ed692010-08-29 18:00:00 +0000876 CurAST->deleteValue(&I);
Chandler Carruthfc258542014-02-11 12:52:27 +0000877 I.eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +0000878 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000879}
Chris Lattner64437692002-09-29 21:46:09 +0000880
Hal Finkel3d4269a2015-02-22 18:35:32 +0000881/// When an instruction is found to only use loop invariant operands that
882/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000883///
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000884static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000885 const LoopSafetyInfo *SafetyInfo,
886 OptimizationRemarkEmitter *ORE) {
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000887 auto *Preheader = CurLoop->getLoopPreheader();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000888 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
889 << "\n");
Adam Nemet358433c2017-01-11 04:39:35 +0000890 ORE->emit(OptimizationRemark(DEBUG_TYPE, "Hoisted", &I)
Brian Cain6dedf652017-02-14 16:41:10 +0000891 << "hoisting " << ore::NV("Inst", &I));
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000892
893 // Metadata can be dependent on conditions we are hoisting above.
894 // Conservatively strip all metadata on the instruction unless we were
895 // guaranteed to execute I if we entered the loop, in which case the metadata
896 // is valid in the loop preheader.
897 if (I.hasMetadataOtherThanDebugLoc() &&
898 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
899 // time in isGuaranteedToExecute if we don't actually have anything to
900 // drop. It is a compile time optimization, not required for correctness.
901 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
902 I.dropUnknownNonDebugMetadata();
903
Chris Lattner6ac06592010-08-29 18:18:40 +0000904 // Move the new node to the Preheader, before its terminator.
905 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000906
Wolfgang Piebc17a2792017-01-06 18:38:57 +0000907 // Do not retain debug locations when we are moving instructions to different
908 // basic blocks, because we want to avoid jumpy line tables. Calls, however,
909 // need to retain their debug locs because they may be inlined.
910 // FIXME: How do we retain source locations without causing poor debugging
911 // behavior?
912 if (!isa<CallInst>(I))
913 I.setDebugLoc(DebugLoc());
914
Dehao Chend55bc4c2016-05-05 00:54:54 +0000915 if (isa<LoadInst>(I))
916 ++NumMovedLoads;
917 else if (isa<CallInst>(I))
918 ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +0000919 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +0000920 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000921}
922
Sanjoy Dasf8a0db52015-05-18 18:07:00 +0000923/// Only sink or hoist an instruction if it is not a trapping instruction,
924/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000925/// or if it is a trapping instruction and is guaranteed to execute.
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000926static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000927 const DominatorTree *DT,
928 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000929 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000930 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000931 const Instruction *CtxI) {
Sean Silva45835e72016-07-02 23:47:27 +0000932 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +0000933 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000934
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000935 bool GuaranteedToExecute =
936 isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
937
938 if (!GuaranteedToExecute) {
939 auto *LI = dyn_cast<LoadInst>(&Inst);
940 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
941 ORE->emit(OptimizationRemarkMissed(
942 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
943 << "failed to hoist load with loop-invariant address "
944 "because load is conditionally executed");
945 }
946
947 return GuaranteedToExecute;
Eli Friedman0cdc1482011-07-20 21:37:47 +0000948}
949
Chris Lattnerb68ec5c2011-01-15 00:12:35 +0000950namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +0000951class LoopPromoter : public LoadAndStorePromoter {
952 Value *SomePtr; // Designated pointer to store to.
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000953 const SmallSetVector<Value *, 8> &PointerMustAliases;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000954 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
955 SmallVectorImpl<Instruction *> &LoopInsertPts;
956 PredIteratorCache &PredCache;
957 AliasSetTracker &AST;
958 LoopInfo &LI;
959 DebugLoc DL;
960 int Alignment;
Philip Reamesb2bca7e2017-02-14 01:38:31 +0000961 bool UnorderedAtomic;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000962 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +0000963
Dehao Chend55bc4c2016-05-05 00:54:54 +0000964 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
965 if (Instruction *I = dyn_cast<Instruction>(V))
966 if (Loop *L = LI.getLoopFor(I->getParent()))
967 if (!L->contains(BB)) {
968 // We need to create an LCSSA PHI node for the incoming value and
969 // store that.
970 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
971 I->getName() + ".lcssa", &BB->front());
972 for (BasicBlock *Pred : PredCache.get(BB))
973 PN->addIncoming(I, Pred);
974 return PN;
975 }
976 return V;
977 }
Chandler Carruthfc258542014-02-11 12:52:27 +0000978
Dehao Chend55bc4c2016-05-05 00:54:54 +0000979public:
980 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000981 const SmallSetVector<Value *, 8> &PMA,
Dehao Chend55bc4c2016-05-05 00:54:54 +0000982 SmallVectorImpl<BasicBlock *> &LEB,
983 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
984 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
Philip Reamesb2bca7e2017-02-14 01:38:31 +0000985 bool UnorderedAtomic, const AAMDNodes &AATags)
Dehao Chend55bc4c2016-05-05 00:54:54 +0000986 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
987 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Philip Reamesb2bca7e2017-02-14 01:38:31 +0000988 LI(li), DL(std::move(dl)), Alignment(alignment),
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000989 UnorderedAtomic(UnorderedAtomic), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +0000990
Dehao Chend55bc4c2016-05-05 00:54:54 +0000991 bool isInstInList(Instruction *I,
992 const SmallVectorImpl<Instruction *> &) const override {
993 Value *Ptr;
994 if (LoadInst *LI = dyn_cast<LoadInst>(I))
995 Ptr = LI->getOperand(0);
996 else
997 Ptr = cast<StoreInst>(I)->getPointerOperand();
998 return PointerMustAliases.count(Ptr);
999 }
Tobias Grossera3928f52011-07-06 19:20:02 +00001000
Dehao Chend55bc4c2016-05-05 00:54:54 +00001001 void doExtraRewritesBeforeFinalDeletion() const override {
1002 // Insert stores after in the loop exit blocks. Each exit block gets a
1003 // store of the live-out values that feed them. Since we've already told
1004 // the SSA updater about the defs in the loop and the preheader
1005 // definition, it is all set and we can start using it.
1006 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1007 BasicBlock *ExitBlock = LoopExitBlocks[i];
1008 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1009 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1010 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1011 Instruction *InsertPos = LoopInsertPts[i];
1012 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001013 if (UnorderedAtomic)
1014 NewSI->setOrdering(AtomicOrdering::Unordered);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001015 NewSI->setAlignment(Alignment);
1016 NewSI->setDebugLoc(DL);
1017 if (AATags)
1018 NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001019 }
Dehao Chend55bc4c2016-05-05 00:54:54 +00001020 }
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001021
Dehao Chend55bc4c2016-05-05 00:54:54 +00001022 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1023 // Update alias analysis.
1024 AST.copyValue(LI, V);
1025 }
1026 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
1027};
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001028} // namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001029
Hal Finkel3d4269a2015-02-22 18:35:32 +00001030/// Try to promote memory values to scalars by sinking stores out of the
1031/// loop and moving loads to before the loop. We do this by looping over
1032/// the stores in the loop, looking for stores to Must pointers which are
1033/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +00001034///
Dehao Chend55bc4c2016-05-05 00:54:54 +00001035bool llvm::promoteLoopAccessesToScalars(
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001036 const SmallSetVector<Value *, 8> &PointerMustAliases,
1037 SmallVectorImpl<BasicBlock *> &ExitBlocks,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001038 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
1039 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
Adam Nemet358433c2017-01-11 04:39:35 +00001040 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
1041 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +00001042 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001043 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1044 CurAST != nullptr && SafetyInfo != nullptr &&
Hal Finkel3d4269a2015-02-22 18:35:32 +00001045 "Unexpected Input to promoteLoopAccessesToScalars");
Sanjay Patel99133222016-01-13 23:01:57 +00001046
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001047 Value *SomePtr = *PointerMustAliases.begin();
Dehao Chend55bc4c2016-05-05 00:54:54 +00001048 BasicBlock *Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +00001049
Chris Lattner1dc98b42010-08-29 06:43:52 +00001050 // It isn't safe to promote a load/store from the loop if the load/store is
1051 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +00001052 //
Chris Lattner1dc98b42010-08-29 06:43:52 +00001053 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +00001054 //
Chris Lattner1dc98b42010-08-29 06:43:52 +00001055 // into:
1056 //
1057 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
1058 //
1059 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +00001060 //
Philip Reamesb54c8e62016-03-09 22:59:30 +00001061 // The safety property divides into two parts:
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001062 // p1) The memory may not be dereferenceable on entry to the loop. In this
Philip Reamesb54c8e62016-03-09 22:59:30 +00001063 // case, we can't insert the required load in the preheader.
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001064 // p2) The memory model does not allow us to insert a store along any dynamic
Philip Reamesb54c8e62016-03-09 22:59:30 +00001065 // path which did not originally have one.
1066 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001067 // If at least one store is guaranteed to execute, both properties are
1068 // satisfied, and promotion is legal.
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001069 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001070 // This, however, is not a necessary condition. Even if no store/load is
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001071 // guaranteed to execute, we can still establish these properties.
1072 // We can establish (p1) by proving that hoisting the load into the preheader
1073 // is safe (i.e. proving dereferenceability on all paths through the loop). We
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001074 // can use any access within the alias set to prove dereferenceability,
Philip Reamesb54c8e62016-03-09 22:59:30 +00001075 // since they're all must alias.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001076 //
1077 // There are two ways establish (p2):
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001078 // a) Prove the location is thread-local. In this case the memory model
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001079 // requirement does not apply, and stores are safe to insert.
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001080 // b) Prove a store dominates every exit block. In this case, if an exit
1081 // blocks is reached, the original dynamic path would have taken us through
1082 // the store, so inserting a store into the exit block is safe. Note that this
1083 // is different from the store being guaranteed to execute. For instance,
1084 // if an exception is thrown on the first iteration of the loop, the original
1085 // store is never executed, but the exit blocks are not executed either.
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001086
1087 bool DereferenceableInPH = false;
1088 bool SafeToInsertStore = false;
Philip Reamesb54c8e62016-03-09 22:59:30 +00001089
Dehao Chend55bc4c2016-05-05 00:54:54 +00001090 SmallVector<Instruction *, 64> LoopUses;
Chris Lattner45d67d62003-02-24 03:52:32 +00001091
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001092 // We start with an alignment of one and try to find instructions that allow
1093 // us to prove better alignment.
1094 unsigned Alignment = 1;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001095 // Keep track of which types of access we see
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001096 bool SawUnorderedAtomic = false;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001097 bool SawNotAtomic = false;
Hal Finkelcc39b672014-07-24 12:16:19 +00001098 AAMDNodes AATags;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001099
Philip Reamesb54c8e62016-03-09 22:59:30 +00001100 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1101
Xin Tong5ee40ba2017-01-19 19:31:40 +00001102 // Do we know this object does not escape ?
1103 bool IsKnownNonEscapingObject = false;
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +00001104 if (SafetyInfo->MayThrow) {
Eli Friedmanee895052016-06-05 22:13:52 +00001105 // If a loop can throw, we have to insert a store along each unwind edge.
1106 // That said, we can't actually make the unwind edge explicit. Therefore,
1107 // we have to prove that the store is dead along the unwind edge.
1108 //
Xin Tong5ee40ba2017-01-19 19:31:40 +00001109 // If the underlying object is not an alloca, nor a pointer that does not
1110 // escape, then we can not effectively prove that the store is dead along
1111 // the unwind edge. i.e. the caller of this function could have ways to
1112 // access the pointed object.
1113 Value *Object = GetUnderlyingObject(SomePtr, MDL);
1114 // If this is a base pointer we do not understand, simply bail.
1115 // We only handle alloca and return value from alloc-like fn right now.
1116 if (!isa<AllocaInst>(Object)) {
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001117 if (!isAllocLikeFn(Object, TLI))
1118 return false;
1119 // If this is an alloc like fn. There are more constraints we need to
1120 // verify. More specifically, we must make sure that the pointer can not
1121 // escape.
Xin Tong5ee40ba2017-01-19 19:31:40 +00001122 //
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001123 // NOTE: PointerMayBeCaptured is not enough as the pointer may have
1124 // escaped even though its not captured by the enclosing function.
1125 // Standard allocation functions like malloc, calloc, and operator new
1126 // return values which can be assumed not to have previously escaped.
Xin Tong5ee40ba2017-01-19 19:31:40 +00001127 if (PointerMayBeCaptured(Object, true, true))
1128 return false;
1129 IsKnownNonEscapingObject = true;
1130 }
Eli Friedmanee895052016-06-05 22:13:52 +00001131 }
1132
Chris Lattner1dc98b42010-08-29 06:43:52 +00001133 // Check that all of the pointers in the alias set have the same type. We
1134 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +00001135 // different sizes. While we are at it, collect alignment and AA info.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001136 for (Value *ASIV : PointerMustAliases) {
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001137 // Check that all of the pointers in the alias set have the same type. We
1138 // cannot (yet) promote a memory location that is loaded and stored in
1139 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +00001140 if (SomePtr->getType() != ASIV->getType())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001141 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001142
Chandler Carruthcdf47882014-03-09 03:16:01 +00001143 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +00001144 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001145 Instruction *UI = dyn_cast<Instruction>(U);
1146 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001147 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +00001148
Chris Lattner1dc98b42010-08-29 06:43:52 +00001149 // If there is an non-load/store instruction in the loop, we can't promote
1150 // it.
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001151 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
Sanjay Patel9f49b682016-01-08 22:05:03 +00001152 assert(!Load->isVolatile() && "AST broken");
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001153 if (!Load->isUnordered())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001154 return false;
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001155
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001156 SawUnorderedAtomic |= Load->isAtomic();
1157 SawNotAtomic |= !Load->isAtomic();
Philip Reamesb54c8e62016-03-09 22:59:30 +00001158
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001159 if (!DereferenceableInPH)
1160 DereferenceableInPH = isSafeToExecuteUnconditionally(
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001161 *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator());
Sanjay Patel9f49b682016-01-08 22:05:03 +00001162 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +00001163 // Stores *of* the pointer are not interesting, only stores *to* the
1164 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001165 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +00001166 continue;
Sanjay Patel9f49b682016-01-08 22:05:03 +00001167 assert(!Store->isVolatile() && "AST broken");
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001168 if (!Store->isUnordered())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001169 return false;
Eli Friedman0cdc1482011-07-20 21:37:47 +00001170
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001171 SawUnorderedAtomic |= Store->isAtomic();
1172 SawNotAtomic |= !Store->isAtomic();
1173
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001174 // If the store is guaranteed to execute, both properties are satisfied.
1175 // We may want to check if a store is guaranteed to execute even if we
1176 // already know that promotion is safe, since it may have higher
1177 // alignment than any other guaranteed stores, in which case we can
1178 // raise the alignment on the promoted store.
Sanjay Patel9f49b682016-01-08 22:05:03 +00001179 unsigned InstAlignment = Store->getAlignment();
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001180 if (!InstAlignment)
1181 InstAlignment =
1182 MDL.getABITypeAlignment(Store->getValueOperand()->getType());
1183
1184 if (!DereferenceableInPH || !SafeToInsertStore ||
1185 (InstAlignment > Alignment)) {
Hal Finkel3d4269a2015-02-22 18:35:32 +00001186 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001187 DereferenceableInPH = true;
1188 SafeToInsertStore = true;
1189 Alignment = std::max(Alignment, InstAlignment);
Eli Friedman0cdc1482011-07-20 21:37:47 +00001190 }
Anna Thomas67151352016-06-24 12:38:45 +00001191 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001192
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001193 // If a store dominates all exit blocks, it is safe to sink.
1194 // As explained above, if an exit block was executed, a dominating
1195 // store must have been been executed at least once, so we are not
1196 // introducing stores on paths that did not have them.
1197 // Note that this only looks at explicit exit blocks. If we ever
1198 // start sinking stores into unwind edges (see above), this will break.
1199 if (!SafeToInsertStore)
1200 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1201 return DT->dominates(Store->getParent(), Exit);
1202 });
1203
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001204 // If the store is not guaranteed to execute, we may still get
1205 // deref info through it.
1206 if (!DereferenceableInPH) {
1207 DereferenceableInPH = isDereferenceableAndAlignedPointer(
Dehao Chend55bc4c2016-05-05 00:54:54 +00001208 Store->getPointerOperand(), Store->getAlignment(), MDL,
Sean Silva45835e72016-07-02 23:47:27 +00001209 Preheader->getTerminator(), DT);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001210 }
Chris Lattnerbe901902010-09-06 05:11:24 +00001211 } else
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001212 return false; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001213
Hal Finkelcc39b672014-07-24 12:16:19 +00001214 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +00001215 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001216 // On the first load/store, just take its AA tags.
1217 UI->getAAMetadata(AATags);
1218 } else if (AATags) {
1219 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +00001220 }
Chandler Carruthcdf47882014-03-09 03:16:01 +00001221
1222 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001223 }
1224 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001225
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001226 // If we found both an unordered atomic instruction and a non-atomic memory
1227 // access, bail. We can't blindly promote non-atomic to atomic since we
1228 // might not be able to lower the result. We can't downgrade since that
1229 // would violate memory model. Also, align 0 is an error for atomics.
1230 if (SawUnorderedAtomic && SawNotAtomic)
1231 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001232
1233 // If we couldn't prove we can hoist the load, bail.
1234 if (!DereferenceableInPH)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001235 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001236
1237 // We know we can hoist the load, but don't have a guaranteed store.
1238 // Check whether the location is thread-local. If it is, then we can insert
1239 // stores along paths which originally didn't have them without violating the
1240 // memory model.
1241 if (!SafeToInsertStore) {
Xin Tong5ee40ba2017-01-19 19:31:40 +00001242 // If this is a known non-escaping object, it is safe to insert the stores.
1243 if (IsKnownNonEscapingObject)
1244 SafeToInsertStore = true;
1245 else {
1246 Value *Object = GetUnderlyingObject(SomePtr, MDL);
1247 SafeToInsertStore =
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001248 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
1249 !PointerMayBeCaptured(Object, true, true);
Xin Tong5ee40ba2017-01-19 19:31:40 +00001250 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001251 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +00001252
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001253 // If we've still failed to prove we can sink the store, give up.
1254 if (!SafeToInsertStore)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001255 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001256
Chris Lattner1dc98b42010-08-29 06:43:52 +00001257 // Otherwise, this is safe to promote, lets do it!
Dehao Chend55bc4c2016-05-05 00:54:54 +00001258 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1259 << '\n');
Adam Nemet358433c2017-01-11 04:39:35 +00001260 ORE->emit(
1261 OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar", LoopUses[0])
1262 << "Moving accesses to memory location out of the loop");
Chris Lattner1dc98b42010-08-29 06:43:52 +00001263 ++NumPromoted;
1264
Eli Friedmanddf7f552011-05-27 20:31:51 +00001265 // Grab a debug location for the inserted loads/stores; given that the
1266 // inserted loads/stores have little relation to the original loads/stores,
1267 // this code just arbitrarily picks a location from one, since any debug
1268 // location is better than none.
1269 DebugLoc DL = LoopUses[0]->getDebugLoc();
1270
Chris Lattner1dc98b42010-08-29 06:43:52 +00001271 // We use the SSAUpdater interface to insert phi nodes as required.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001272 SmallVector<PHINode *, 16> NewPHIs;
Chris Lattner1dc98b42010-08-29 06:43:52 +00001273 SSAUpdater SSA(&NewPHIs);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001274 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001275 InsertPts, PIC, *CurAST, *LI, DL, Alignment,
1276 SawUnorderedAtomic, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +00001277
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001278 // Set up the preheader to have a definition of the value. It is the live-out
1279 // value from the preheader that uses in the loop will use.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001280 LoadInst *PreheaderLoad = new LoadInst(
1281 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001282 if (SawUnorderedAtomic)
1283 PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001284 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +00001285 PreheaderLoad->setDebugLoc(DL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001286 if (AATags)
1287 PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001288 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1289
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001290 // Rewrite all the loads in the loop and remember all the definitions from
1291 // stores in the loop.
1292 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +00001293
1294 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1295 if (PreheaderLoad->use_empty())
1296 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +00001297
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001298 return true;
Chris Lattnera51fa882002-08-22 21:39:55 +00001299}
Devang Patelb98a0972007-07-31 08:01:41 +00001300
Roman Gareev036c0882016-02-15 14:48:50 +00001301/// Returns an owning pointer to an alias set which incorporates aliasing info
Chandler Carruthad8cb382016-02-27 04:34:07 +00001302/// from L and all subloops of L.
Xinliang David Licbb5e022016-08-11 22:34:00 +00001303/// FIXME: In new pass manager, there is no helper function to handle loop
1304/// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
Dehao Chen9cba1f42016-07-12 22:37:48 +00001305/// from scratch for every loop. Hook up with the helper functions when
1306/// available in the new pass manager to avoid redundant computation.
1307AliasSetTracker *
1308LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1309 AliasAnalysis *AA) {
Roman Gareev036c0882016-02-15 14:48:50 +00001310 AliasSetTracker *CurAST = nullptr;
Chandler Carruthad8cb382016-02-27 04:34:07 +00001311 SmallVector<Loop *, 4> RecomputeLoops;
Roman Gareev036c0882016-02-15 14:48:50 +00001312 for (Loop *InnerL : L->getSubLoops()) {
Chandler Carruthad8cb382016-02-27 04:34:07 +00001313 auto MapI = LoopToAliasSetMap.find(InnerL);
1314 // If the AST for this inner loop is missing it may have been merged into
1315 // some other loop's AST and then that loop unrolled, and so we need to
1316 // recompute it.
1317 if (MapI == LoopToAliasSetMap.end()) {
1318 RecomputeLoops.push_back(InnerL);
1319 continue;
1320 }
1321 AliasSetTracker *InnerAST = MapI->second;
Roman Gareev036c0882016-02-15 14:48:50 +00001322
1323 if (CurAST != nullptr) {
1324 // What if InnerLoop was modified by other passes ?
1325 CurAST->add(*InnerAST);
1326
1327 // Once we've incorporated the inner loop's AST into ours, we don't need
1328 // the subloop's anymore.
1329 delete InnerAST;
1330 } else {
1331 CurAST = InnerAST;
1332 }
Chandler Carruthad8cb382016-02-27 04:34:07 +00001333 LoopToAliasSetMap.erase(MapI);
Roman Gareev036c0882016-02-15 14:48:50 +00001334 }
1335 if (CurAST == nullptr)
1336 CurAST = new AliasSetTracker(*AA);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001337
1338 auto mergeLoop = [&](Loop *L) {
1339 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chandler Carruthad8cb382016-02-27 04:34:07 +00001340 for (BasicBlock *BB : L->blocks())
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001341 CurAST->add(*BB); // Incorporate the specified basic block
Chandler Carruthad8cb382016-02-27 04:34:07 +00001342 };
1343
1344 // Add everything from the sub loops that are no longer directly available.
1345 for (Loop *InnerL : RecomputeLoops)
1346 mergeLoop(InnerL);
1347
1348 // And merge in this loop.
1349 mergeLoop(L);
1350
Roman Gareev036c0882016-02-15 14:48:50 +00001351 return CurAST;
1352}
1353
Ashutosh Nema47802622015-08-13 11:18:35 +00001354/// Simple analysis hook. Clone alias set info.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001355///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001356void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1357 Loop *L) {
1358 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001359 if (!AST)
1360 return;
1361
1362 AST->copyValue(From, To);
1363}
1364
Hal Finkel3d4269a2015-02-22 18:35:32 +00001365/// Simple Analysis hook. Delete value V from alias set
1366///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001367void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1368 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001369 if (!AST)
1370 return;
1371
1372 AST->deleteValue(V);
1373}
David Peixotto0d4d5e62014-09-24 16:48:31 +00001374
1375/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001376///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001377void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1378 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001379 if (!AST)
1380 return;
1381
1382 delete AST;
Dehao Chen9cba1f42016-07-12 22:37:48 +00001383 LICM.getLoopToAliasSetMap().erase(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001384}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001385
Hal Finkel3d4269a2015-02-22 18:35:32 +00001386/// Return true if the body of this loop may store into the memory
1387/// location pointed to by V.
1388///
1389static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001390 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +00001391 AliasSetTracker *CurAST) {
1392 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1393 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1394}
1395
1396/// Little predicate that returns true if the specified basic block is in
1397/// a subloop of the current one, not the current one itself.
1398///
1399static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1400 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1401 return LI->getLoopFor(BB) != CurLoop;
1402}