blob: f610aae2403badcc58f658f7a033e75eae2d660a [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"
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +000045#include "llvm/Analysis/MemorySSA.h"
Adam Nemet0965da22017-10-09 23:19:02 +000046#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Chandler Carruthabfa3e52014-01-24 01:59:49 +000047#include "llvm/Analysis/ScalarEvolution.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000048#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000049#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman75d7d5e2011-12-14 23:49:11 +000050#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000051#include "llvm/IR/CFG.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Constants.h"
53#include "llvm/IR/DataLayout.h"
54#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000055#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/Instructions.h"
57#include "llvm/IR/IntrinsicInst.h"
58#include "llvm/IR/LLVMContext.h"
Chris Lattner473988c2013-01-05 16:44:07 +000059#include "llvm/IR/Metadata.h"
Chandler Carruthaa0ab632014-03-04 12:09:19 +000060#include "llvm/IR/PredIteratorCache.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000061#include "llvm/Support/CommandLine.h"
62#include "llvm/Support/Debug.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000063#include "llvm/Support/raw_ostream.h"
Dehao Chend55bc4c2016-05-05 00:54:54 +000064#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000065#include "llvm/Transforms/Scalar/LoopPassManager.h"
Jun Bum Limf5fb3d72017-11-03 16:24:53 +000066#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000067#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth8765cf72014-01-25 04:07:24 +000068#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000069#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner6ec05f52002-05-10 22:44:58 +000070#include <algorithm>
Benjamin Kramer82de7d32016-05-27 14:27:24 +000071#include <utility>
Chris Lattnerc0517682003-12-09 17:18:00 +000072using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000073
Chandler Carruth964daaa2014-04-22 02:55:47 +000074#define DEBUG_TYPE "licm"
75
Dehao Chend55bc4c2016-05-05 00:54:54 +000076STATISTIC(NumSunk, "Number of instructions sunk out of loop");
77STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
Chris Lattner79a42ac2006-12-19 21:40:18 +000078STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
79STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
Dehao Chend55bc4c2016-05-05 00:54:54 +000080STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
Chris Lattner79a42ac2006-12-19 21:40:18 +000081
Xin Tongccee0e02017-02-21 20:53:48 +000082/// Memory promotion is enabled by default.
Dan Gohmand78c4002008-05-13 00:00:25 +000083static cl::opt<bool>
Xin Tongccee0e02017-02-21 20:53:48 +000084 DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
Dehao Chend55bc4c2016-05-05 00:54:54 +000085 cl::desc("Disable memory promotion in LICM pass"));
Chris Lattner45d67d62003-02-24 03:52:32 +000086
Anna Thomas7f4b26e2017-02-02 13:22:03 +000087static cl::opt<uint32_t> MaxNumUsesTraversed(
88 "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
89 cl::desc("Max num uses visited for identifying load "
90 "invariance in loop using invariant start (default = 8)"));
91
Hal Finkel3d4269a2015-02-22 18:35:32 +000092static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
David Majnemer42a07302016-01-04 03:37:39 +000093static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +000094 const LoopSafetyInfo *SafetyInfo);
Sanjoy Das7a2e2be2016-01-28 15:51:58 +000095static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +000096 const LoopSafetyInfo *SafetyInfo,
97 OptimizationRemarkEmitter *ORE);
Jun Bum Limf5fb3d72017-11-03 16:24:53 +000098static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
99 const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,
Adam Nemet358433c2017-01-11 04:39:35 +0000100 OptimizationRemarkEmitter *ORE);
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000101static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +0000102 const DominatorTree *DT,
103 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000104 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +0000105 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +0000106 const Instruction *CtxI = nullptr);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000107static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +0000108 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +0000109 AliasSetTracker *CurAST);
David Majnemer42a07302016-01-04 03:37:39 +0000110static Instruction *
111CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
112 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000113 const LoopSafetyInfo *SafetyInfo);
Hal Finkel3d4269a2015-02-22 18:35:32 +0000114
Dan Gohmand78c4002008-05-13 00:00:25 +0000115namespace {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000116struct LoopInvariantCodeMotion {
117 bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000118 TargetLibraryInfo *TLI, ScalarEvolution *SE, MemorySSA *MSSA,
Adam Nemet358433c2017-01-11 04:39:35 +0000119 OptimizationRemarkEmitter *ORE, bool DeleteAST);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000120
121 DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() {
122 return LoopToAliasSetMap;
Dehao Chen7ef58202016-07-11 22:45:24 +0000123 }
124
Dehao Chen9cba1f42016-07-12 22:37:48 +0000125private:
126 DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
127
128 AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
129 AliasAnalysis *AA);
130};
131
132struct LegacyLICMPass : public LoopPass {
133 static char ID; // Pass identification, replacement for typeid
134 LegacyLICMPass() : LoopPass(ID) {
135 initializeLegacyLICMPassPass(*PassRegistry::getPassRegistry());
136 }
137
138 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Davide Italiano34f94382016-12-23 13:12:50 +0000139 if (skipLoop(L)) {
140 // If we have run LICM on a previous loop but now we are skipping
141 // (because we've hit the opt-bisect limit), we need to clear the
142 // loop alias information.
Davide Italianob9ff23a2016-12-23 15:02:35 +0000143 for (auto &LTAS : LICM.getLoopToAliasSetMap())
144 delete LTAS.second;
Davide Italiano34f94382016-12-23 13:12:50 +0000145 LICM.getLoopToAliasSetMap().clear();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000146 return false;
Davide Italiano34f94382016-12-23 13:12:50 +0000147 }
Dehao Chen9cba1f42016-07-12 22:37:48 +0000148
149 auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000150 MemorySSA *MSSA = EnableMSSALoopDependency
151 ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA())
152 : nullptr;
Adam Nemet358433c2017-01-11 04:39:35 +0000153 // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
154 // pass. Function analyses need to be preserved across loop transformations
155 // but ORE cannot be preserved (see comment before the pass definition).
156 OptimizationRemarkEmitter ORE(L->getHeader()->getParent());
Dehao Chen9cba1f42016-07-12 22:37:48 +0000157 return LICM.runOnLoop(L,
158 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
159 &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
160 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
161 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000162 SE ? &SE->getSE() : nullptr, MSSA, &ORE, false);
Dehao Chen9cba1f42016-07-12 22:37:48 +0000163 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000164
Dehao Chend55bc4c2016-05-05 00:54:54 +0000165 /// This transformation requires natural loop information & requires that
166 /// loop preheaders be inserted into the CFG...
167 ///
168 void getAnalysisUsage(AnalysisUsage &AU) const override {
169 AU.setPreservesCFG();
170 AU.addRequired<TargetLibraryInfoWrapperPass>();
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000171 if (EnableMSSALoopDependency)
172 AU.addRequired<MemorySSAWrapperPass>();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000173 getLoopAnalysisUsage(AU);
174 }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000175
Dehao Chend55bc4c2016-05-05 00:54:54 +0000176 using llvm::Pass::doFinalization;
Matt Beaumont-Gayabfc4462012-12-04 05:41:27 +0000177
Dehao Chend55bc4c2016-05-05 00:54:54 +0000178 bool doFinalization() override {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000179 assert(LICM.getLoopToAliasSetMap().empty() &&
180 "Didn't free loop alias sets");
Dehao Chend55bc4c2016-05-05 00:54:54 +0000181 return false;
182 }
Devang Patel69730c92007-03-07 04:41:30 +0000183
Dehao Chend55bc4c2016-05-05 00:54:54 +0000184private:
Dehao Chen9cba1f42016-07-12 22:37:48 +0000185 LoopInvariantCodeMotion LICM;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000186
Dehao Chend55bc4c2016-05-05 00:54:54 +0000187 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
188 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
189 Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000190
Dehao Chend55bc4c2016-05-05 00:54:54 +0000191 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
192 /// set.
193 void deleteAnalysisValue(Value *V, Loop *L) override;
Devang Patelb98a0972007-07-31 08:01:41 +0000194
Dehao Chend55bc4c2016-05-05 00:54:54 +0000195 /// Simple Analysis hook. Delete loop L from alias set map.
196 void deleteAnalysisLoop(Loop *L) override;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000197};
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000198} // namespace
Chris Lattner6ec05f52002-05-10 22:44:58 +0000199
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000200PreservedAnalyses LICMPass::run(Loop &L, LoopAnalysisManager &AM,
201 LoopStandardAnalysisResults &AR, LPMUpdater &) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000202 const auto &FAM =
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000203 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
Dehao Chen9cba1f42016-07-12 22:37:48 +0000204 Function *F = L.getHeader()->getParent();
205
Adam Nemet358433c2017-01-11 04:39:35 +0000206 auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000207 // FIXME: This should probably be optional rather than required.
208 if (!ORE)
209 report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
210 "cached at a higher level");
Dehao Chen9cba1f42016-07-12 22:37:48 +0000211
212 LoopInvariantCodeMotion LICM;
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000213 if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.SE, AR.MSSA, ORE,
214 true))
Dehao Chen9cba1f42016-07-12 22:37:48 +0000215 return PreservedAnalyses::all();
216
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000217 auto PA = getLoopPassPreservedAnalyses();
218 PA.preserveSet<CFGAnalyses>();
219 return PA;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000220}
221
222char LegacyLICMPass::ID = 0;
223INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
224 false, false)
Chandler Carruth31088a92016-02-19 10:45:18 +0000225INITIALIZE_PASS_DEPENDENCY(LoopPass)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000226INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000227INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000228INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
229 false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000230
Dehao Chen9cba1f42016-07-12 22:37:48 +0000231Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
Chris Lattner6ec05f52002-05-10 22:44:58 +0000232
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000233/// Hoist expressions out of the specified loop. Note, alias info for inner
Tobias Grossera3928f52011-07-06 19:20:02 +0000234/// loop is not preserved so it is not a good idea to run LICM multiple
Devang Pateld8b1ceb2007-07-31 16:52:25 +0000235/// times on one loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000236/// We should delete AST for inner loops in the new pass manager to avoid
237/// memory leak.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000238///
Dehao Chen9cba1f42016-07-12 22:37:48 +0000239bool LoopInvariantCodeMotion::runOnLoop(Loop *L, AliasAnalysis *AA,
240 LoopInfo *LI, DominatorTree *DT,
241 TargetLibraryInfo *TLI,
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +0000242 ScalarEvolution *SE, MemorySSA *MSSA,
Adam Nemet358433c2017-01-11 04:39:35 +0000243 OptimizationRemarkEmitter *ORE,
244 bool DeleteAST) {
Dehao Chen9cba1f42016-07-12 22:37:48 +0000245 bool Changed = false;
Chad Rosier43a33062011-12-02 01:26:24 +0000246
Chandler Carruthfc258542014-02-11 12:52:27 +0000247 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
248
Dehao Chen9cba1f42016-07-12 22:37:48 +0000249 AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000250
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000251 // Get the preheader block to move instructions into...
Dehao Chen9cba1f42016-07-12 22:37:48 +0000252 BasicBlock *Preheader = L->getLoopPreheader();
Chris Lattnerd57f3f52002-09-26 19:40:25 +0000253
Hal Finkel3d4269a2015-02-22 18:35:32 +0000254 // Compute loop safety information.
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000255 LoopSafetyInfo SafetyInfo;
Dehao Chen9cba1f42016-07-12 22:37:48 +0000256 computeLoopSafetyInfo(&SafetyInfo, L);
Nadav Rotem03dcd852012-09-04 10:25:04 +0000257
Chris Lattner6ec05f52002-05-10 22:44:58 +0000258 // We want to visit all of the instructions in this loop... that are not parts
259 // of our subloops (they have already had their invariants hoisted out of
260 // their loop, into this loop, so there is no need to process the BODIES of
261 // the subloops).
262 //
Chris Lattner64437692002-09-29 21:46:09 +0000263 // Traverse the body of the loop in depth first order on the dominator tree so
264 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckya0d49da2007-08-18 15:08:56 +0000265 // us to sink instructions in one pass, without iteration. After sinking
Chris Lattner547192d62003-12-19 07:22:45 +0000266 // instructions, we perform another pass to hoist them out of the loop.
Chris Lattner64437692002-09-29 21:46:09 +0000267 //
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000268 if (L->hasDedicatedExits())
Dehao Chen9cba1f42016-07-12 22:37:48 +0000269 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
Adam Nemet358433c2017-01-11 04:39:35 +0000270 CurAST, &SafetyInfo, ORE);
Dan Gohmana83ac2d2009-11-05 21:11:53 +0000271 if (Preheader)
Dehao Chen9cba1f42016-07-12 22:37:48 +0000272 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
Adam Nemet358433c2017-01-11 04:39:35 +0000273 CurAST, &SafetyInfo, ORE);
Chris Lattner6ec05f52002-05-10 22:44:58 +0000274
Chris Lattner45d67d62003-02-24 03:52:32 +0000275 // Now that all loop invariants have been removed from the loop, promote any
Chris Lattner1dc98b42010-08-29 06:43:52 +0000276 // memory references to scalars that we can.
Michael Kuperstein55660922016-12-29 22:51:22 +0000277 // Don't sink stores from loops without dedicated block exits. Exits
278 // containing indirect branches are not transformed by loop simplify,
279 // make sure we catch that. An additional load may be generated in the
280 // preheader for SSA updater, so also avoid sinking when no preheader
281 // is available.
282 if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000283 // Figure out the loop exits and their insertion points
Dan Gohmanb9487362012-08-08 00:00:26 +0000284 SmallVector<BasicBlock *, 8> ExitBlocks;
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000285 L->getUniqueExitBlocks(ExitBlocks);
Dan Gohmanb9487362012-08-08 00:00:26 +0000286
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000287 // We can't insert into a catchswitch.
288 bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
289 return isa<CatchSwitchInst>(Exit->getTerminator());
290 });
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000291
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000292 if (!HasCatchSwitch) {
293 SmallVector<Instruction *, 8> InsertPts;
294 InsertPts.reserve(ExitBlocks.size());
295 for (BasicBlock *ExitBlock : ExitBlocks)
296 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
Chandler Carruth16651522014-02-01 13:35:14 +0000297
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000298 PredIteratorCache PIC;
Michael Kupersteinb6da9cf2016-12-29 22:37:13 +0000299
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000300 bool Promoted = false;
301
302 // Loop over all of the alias sets in the tracker object.
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000303 for (AliasSet &AS : *CurAST) {
304 // We can promote this alias set if it has a store, if it is a "Must"
305 // alias set, if the pointer is loop invariant, and if we are not
306 // eliminating any volatile loads or stores.
307 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
308 AS.isVolatile() || !L->isLoopInvariant(AS.begin()->getValue()))
309 continue;
310
311 assert(
312 !AS.empty() &&
313 "Must alias set should have at least one pointer element in it!");
314
315 SmallSetVector<Value *, 8> PointerMustAliases;
316 for (const auto &ASI : AS)
317 PointerMustAliases.insert(ASI.getValue());
318
319 Promoted |= promoteLoopAccessesToScalars(PointerMustAliases, ExitBlocks,
320 InsertPts, PIC, LI, DT, TLI, L,
321 CurAST, &SafetyInfo, ORE);
322 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +0000323
324 // Once we have promoted values across the loop body we have to
325 // recursively reform LCSSA as any nested loop may now have values defined
326 // within the loop used in the outer loop.
327 // FIXME: This is really heavy handed. It would be a bit better to use an
328 // SSAUpdater strategy during promotion that was LCSSA aware and reformed
329 // it as it went.
330 if (Promoted)
331 formLCSSARecursively(*L, *DT, LI, SE);
332
333 Changed |= Promoted;
334 }
Chris Lattner1dc98b42010-08-29 06:43:52 +0000335 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000336
Chandler Carruthfc258542014-02-11 12:52:27 +0000337 // Check that neither this loop nor its parent have had LCSSA broken. LICM is
338 // specifically moving instructions across the loop boundary and so it is
339 // especially in need of sanity checking here.
340 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
341 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
342 "Parent loop not left in LCSSA form after LICM!");
Chandler Carruth8765cf72014-01-25 04:07:24 +0000343
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000344 // If this loop is nested inside of another one, save the alias information
345 // for when we process the outer loop.
Dehao Chen9cba1f42016-07-12 22:37:48 +0000346 if (L->getParentLoop() && !DeleteAST)
Chris Lattnercc9cbc62010-08-29 17:46:00 +0000347 LoopToAliasSetMap[L] = CurAST;
348 else
349 delete CurAST;
Sanjoy Das4ae39202016-05-03 17:50:11 +0000350
Dehao Chen9cba1f42016-07-12 22:37:48 +0000351 if (Changed && SE)
352 SE->forgetLoopDispositions(L);
Devang Patel69730c92007-03-07 04:41:30 +0000353 return Changed;
Chris Lattner6ec05f52002-05-10 22:44:58 +0000354}
355
Hal Finkel3d4269a2015-02-22 18:35:32 +0000356/// Walk the specified region of the CFG (defined by all blocks dominated by
Dehao Chend55bc4c2016-05-05 00:54:54 +0000357/// the specified block, and that are in the current loop) in reverse depth
Hal Finkel3d4269a2015-02-22 18:35:32 +0000358/// first order w.r.t the DominatorTree. This allows us to visit uses before
359/// definitions, allowing us to sink a loop body in one pass without iteration.
Chris Lattner547192d62003-12-19 07:22:45 +0000360///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000361bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
362 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000363 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
364 OptimizationRemarkEmitter *ORE) {
Chris Lattner547192d62003-12-19 07:22:45 +0000365
Hal Finkel3d4269a2015-02-22 18:35:32 +0000366 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000367 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
368 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
369 "Unexpected input to sinkRegion");
Hal Finkel3d4269a2015-02-22 18:35:32 +0000370
David Majnemere6bb8952017-07-20 03:27:02 +0000371 // We want to visit children before parents. We will enque all the parents
372 // before their children in the worklist and process the worklist in reverse
373 // order.
374 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
Chris Lattner547192d62003-12-19 07:22:45 +0000375
Sanjay Patel99133222016-01-13 23:01:57 +0000376 bool Changed = false;
David Majnemere6bb8952017-07-20 03:27:02 +0000377 for (DomTreeNode *DTN : reverse(Worklist)) {
378 BasicBlock *BB = DTN->getBlock();
379 // Only need to process the contents of this block if it is not part of a
380 // subloop (which would already have been processed).
381 if (inSubLoop(BB, CurLoop, LI))
Chris Lattner263f8042010-08-29 18:22:25 +0000382 continue;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000383
David Majnemere6bb8952017-07-20 03:27:02 +0000384 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
385 Instruction &I = *--II;
386
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000387 // If the instruction is dead, we would try to sink it because it isn't
388 // used in the loop, instead, just delete it.
David Majnemere6bb8952017-07-20 03:27:02 +0000389 if (isInstructionTriviallyDead(&I, TLI)) {
390 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
391 ++II;
392 CurAST->deleteValue(&I);
393 I.eraseFromParent();
394 Changed = true;
395 continue;
396 }
397
398 // Check to see if we can sink this instruction to the exit blocks
399 // of the loop. We can do this if the all users of the instruction are
400 // outside of the loop. In this case, it doesn't even matter if the
401 // operands of the instruction are loop invariant.
402 //
403 if (isNotUsedInLoop(I, CurLoop, SafetyInfo) &&
404 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE)) {
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000405 if (sink(I, LI, DT, CurLoop, SafetyInfo, ORE)) {
406 ++II;
407 CurAST->deleteValue(&I);
408 I.eraseFromParent();
409 Changed = true;
410 }
David Majnemere6bb8952017-07-20 03:27:02 +0000411 }
Chris Lattner91846012003-12-19 08:18:16 +0000412 }
Chris Lattner547192d62003-12-19 07:22:45 +0000413 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000414 return Changed;
Chris Lattner547192d62003-12-19 07:22:45 +0000415}
416
Hal Finkel3d4269a2015-02-22 18:35:32 +0000417/// Walk the specified region of the CFG (defined by all blocks dominated by
418/// the specified block, and that are in the current loop) in depth first
419/// order w.r.t the DominatorTree. This allows us to visit definitions before
420/// uses, allowing us to hoist a loop body in one pass without iteration.
Chris Lattner64437692002-09-29 21:46:09 +0000421///
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000422bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI,
423 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000424 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
425 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000426 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +0000427 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
428 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
429 "Unexpected input to hoistRegion");
Sanjay Patel99133222016-01-13 23:01:57 +0000430
David Majnemere6bb8952017-07-20 03:27:02 +0000431 // We want to visit parents before children. We will enque all the parents
432 // before their children in the worklist and process the worklist in order.
433 SmallVector<DomTreeNode *, 16> Worklist = collectChildrenInLoop(N, CurLoop);
Sanjay Patel99133222016-01-13 23:01:57 +0000434
Sanjay Patel99133222016-01-13 23:01:57 +0000435 bool Changed = false;
David Majnemere6bb8952017-07-20 03:27:02 +0000436 for (DomTreeNode *DTN : Worklist) {
437 BasicBlock *BB = DTN->getBlock();
438 // Only need to process the contents of this block if it is not part of a
439 // subloop (which would already have been processed).
440 if (!inSubLoop(BB, CurLoop, LI))
441 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
442 Instruction &I = *II++;
443 // Try constant folding this instruction. If all the operands are
444 // constants, it is technically hoistable, but it would be better to
445 // just fold it.
446 if (Constant *C = ConstantFoldInstruction(
447 &I, I.getModule()->getDataLayout(), TLI)) {
448 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n');
449 CurAST->copyValue(&I, C);
450 I.replaceAllUsesWith(C);
451 if (isInstructionTriviallyDead(&I, TLI)) {
452 CurAST->deleteValue(&I);
453 I.eraseFromParent();
454 }
455 Changed = true;
456 continue;
David Majnemer522a9112016-07-22 04:54:44 +0000457 }
David Majnemere6bb8952017-07-20 03:27:02 +0000458
459 // Attempt to remove floating point division out of the loop by
460 // converting it to a reciprocal multiplication.
461 if (I.getOpcode() == Instruction::FDiv &&
462 CurLoop->isLoopInvariant(I.getOperand(1)) &&
463 I.hasAllowReciprocal()) {
464 auto Divisor = I.getOperand(1);
465 auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
466 auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
467 ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
468 ReciprocalDivisor->insertBefore(&I);
469
470 auto Product =
471 BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
472 Product->setFastMathFlags(I.getFastMathFlags());
473 Product->insertAfter(&I);
474 I.replaceAllUsesWith(Product);
475 I.eraseFromParent();
476
477 hoist(*ReciprocalDivisor, DT, CurLoop, SafetyInfo, ORE);
478 Changed = true;
479 continue;
480 }
481
482 // Try hoisting the instruction out to the preheader. We can only do
483 // this if all of the operands of the instruction are loop invariant and
484 // if it is safe to hoist the instruction.
485 //
486 if (CurLoop->hasLoopInvariantOperands(&I) &&
487 canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE) &&
488 isSafeToExecuteUnconditionally(
489 I, DT, CurLoop, SafetyInfo, ORE,
490 CurLoop->getLoopPreheader()->getTerminator()))
491 Changed |= hoist(I, DT, CurLoop, SafetyInfo, ORE);
Chris Lattner030f0202010-08-31 23:00:16 +0000492 }
David Majnemere6bb8952017-07-20 03:27:02 +0000493 }
Tobias Grossera3928f52011-07-06 19:20:02 +0000494
Hal Finkel3d4269a2015-02-22 18:35:32 +0000495 return Changed;
496}
497
498/// Computes loop safety information, checks loop body & header
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000499/// for the possibility of may throw exception.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000500///
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000501void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) {
Hal Finkel3d4269a2015-02-22 18:35:32 +0000502 assert(CurLoop != nullptr && "CurLoop cant be null");
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +0000503 BasicBlock *Header = CurLoop->getHeader();
504 // Setting default safety values.
505 SafetyInfo->MayThrow = false;
506 SafetyInfo->HeaderMayThrow = false;
507 // Iterate over header and compute safety info.
508 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
509 (I != E) && !SafetyInfo->HeaderMayThrow; ++I)
510 SafetyInfo->HeaderMayThrow |=
511 !isGuaranteedToTransferExecutionToSuccessor(&*I);
512
513 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow;
514 // Iterate over loop instructions and compute safety info.
515 // Skip header as it has been computed and stored in HeaderMayThrow.
516 // The first block in loopinfo.Blocks is guaranteed to be the header.
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000517 assert(Header == *CurLoop->getBlocks().begin() &&
518 "First block must be header");
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +0000519 for (Loop::block_iterator BB = std::next(CurLoop->block_begin()),
Dehao Chend55bc4c2016-05-05 00:54:54 +0000520 BBE = CurLoop->block_end();
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +0000521 (BB != BBE) && !SafetyInfo->MayThrow; ++BB)
522 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end();
523 (I != E) && !SafetyInfo->MayThrow; ++I)
524 SafetyInfo->MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I);
David Majnemer42a07302016-01-04 03:37:39 +0000525
526 // Compute funclet colors if we might sink/hoist in a function with a funclet
527 // personality routine.
528 Function *Fn = CurLoop->getHeader()->getParent();
529 if (Fn->hasPersonalityFn())
530 if (Constant *PersonalityFn = Fn->getPersonalityFn())
531 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn)))
532 SafetyInfo->BlockColors = colorEHFunclets(*Fn);
Chris Lattner64437692002-09-29 21:46:09 +0000533}
534
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000535// Return true if LI is invariant within scope of the loop. LI is invariant if
Alina Sbirlea80b806b2017-09-12 21:18:44 +0000536// CurLoop is dominated by an invariant.start representing the same memory
537// location and size as the memory location LI loads from, and also the
538// invariant.start has no uses.
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000539static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT,
540 Loop *CurLoop) {
541 Value *Addr = LI->getOperand(0);
542 const DataLayout &DL = LI->getModule()->getDataLayout();
543 const uint32_t LocSizeInBits = DL.getTypeSizeInBits(
544 cast<PointerType>(Addr->getType())->getElementType());
545
546 // if the type is i8 addrspace(x)*, we know this is the type of
547 // llvm.invariant.start operand
548 auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
549 LI->getPointerAddressSpace());
550 unsigned BitcastsVisited = 0;
551 // Look through bitcasts until we reach the i8* type (this is invariant.start
552 // operand type).
553 while (Addr->getType() != PtrInt8Ty) {
554 auto *BC = dyn_cast<BitCastInst>(Addr);
555 // Avoid traversing high number of bitcast uses.
556 if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
557 return false;
558 Addr = BC->getOperand(0);
559 }
560
561 unsigned UsesVisited = 0;
562 // Traverse all uses of the load operand value, to see if invariant.start is
563 // one of the uses, and whether it dominates the load instruction.
564 for (auto *U : Addr->users()) {
565 // Avoid traversing for Load operand with high number of users.
566 if (++UsesVisited > MaxNumUsesTraversed)
567 return false;
568 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
569 // If there are escaping uses of invariant.start instruction, the load maybe
570 // non-invariant.
571 if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
Davide Italiano79eb3b02017-05-16 22:38:40 +0000572 !II->use_empty())
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000573 continue;
574 unsigned InvariantSizeInBits =
575 cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
576 // Confirm the invariant.start location size contains the load operand size
577 // in bits. Also, the invariant.start should dominate the load, and we
578 // should not hoist the load out of a loop that contains this dominating
579 // invariant.start.
580 if (LocSizeInBits <= InvariantSizeInBits &&
581 DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
582 return true;
583 }
584
585 return false;
586}
587
Dehao Chenb94c09ba2016-10-27 16:30:08 +0000588bool llvm::canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT,
589 Loop *CurLoop, AliasSetTracker *CurAST,
Adam Nemet81941b32017-01-11 04:39:45 +0000590 LoopSafetyInfo *SafetyInfo,
591 OptimizationRemarkEmitter *ORE) {
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000592 // SafetyInfo is nullptr if we are checking for sinking from preheader to
593 // loop body.
594 const bool SinkingToLoopBody = !SafetyInfo;
Chris Lattner65c11932003-12-09 19:32:44 +0000595 // Loads have extra constraints we have to verify before we can hoist them.
596 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
Eli Friedman91386c72011-08-15 20:52:09 +0000597 if (!LI->isUnordered())
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000598 return false; // Don't sink/hoist volatile or ordered atomic loads!
Chris Lattner65c11932003-12-09 19:32:44 +0000599
Chris Lattner8a8fb902008-07-23 05:06:28 +0000600 // Loads from constant memory are always safe to move, even if they end up
601 // in the same alias set as something that ends up being modified.
Dan Gohmancbc6ebb2009-11-19 19:00:10 +0000602 if (AA->pointsToConstantMemory(LI->getOperand(0)))
Chris Lattner8a8fb902008-07-23 05:06:28 +0000603 return true;
Philip Reames5a3f5f72014-10-21 00:13:20 +0000604 if (LI->getMetadata(LLVMContext::MD_invariant_load))
Pete Cooper9ee22092011-11-08 19:30:00 +0000605 return true;
Tobias Grossera3928f52011-07-06 19:20:02 +0000606
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000607 if (LI->isAtomic() && SinkingToLoopBody)
608 return false; // Don't sink unordered atomic loads to loop body.
609
Anna Thomas7f4b26e2017-02-02 13:22:03 +0000610 // This checks for an invariant.start dominating the load.
611 if (isLoadInvariantInLoop(LI, DT, CurLoop))
612 return true;
613
Chris Lattner65c11932003-12-09 19:32:44 +0000614 // Don't hoist loads which have may-aliased stores in loop.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000615 uint64_t Size = 0;
Chris Lattnerb1374092004-11-26 21:20:09 +0000616 if (LI->getType()->isSized())
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000617 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
Hal Finkelcc39b672014-07-24 12:16:19 +0000618
619 AAMDNodes AAInfo;
620 LI->getAAMetadata(AAInfo);
621
Adam Nemet81941b32017-01-11 04:39:45 +0000622 bool Invalidated =
623 pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
624 // Check loop-invariant address because this may also be a sinkable load
625 // whose address is not necessarily loop-invariant.
626 if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
Vivek Pandya95906582017-10-11 17:12:59 +0000627 ORE->emit([&]() {
628 return OptimizationRemarkMissed(
629 DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
630 << "failed to move load with loop-invariant address "
631 "because the loop may invalidate its value";
632 });
Adam Nemet81941b32017-01-11 04:39:45 +0000633
634 return !Invalidated;
Chris Lattner20cda262004-03-15 04:11:30 +0000635 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
Eli Friedman942e1c12011-05-27 18:37:52 +0000636 // Don't sink or hoist dbg info; it's legal, but not useful.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000637 if (isa<DbgInfoIntrinsic>(I))
Eli Friedman942e1c12011-05-27 18:37:52 +0000638 return false;
639
David Majnemer42a07302016-01-04 03:37:39 +0000640 // Don't sink calls which can throw.
641 if (CI->mayThrow())
642 return false;
643
Eli Friedman942e1c12011-05-27 18:37:52 +0000644 // Handle simple cases by querying alias analysis.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000645 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
646 if (Behavior == FMRB_DoesNotAccessMemory)
Duncan Sands68b6f502007-12-01 07:51:45 +0000647 return true;
Dan Gohman0f175072010-11-09 19:58:21 +0000648 if (AliasAnalysis::onlyReadsMemory(Behavior)) {
Philip Reames5f994232015-09-21 22:27:59 +0000649 // A readonly argmemonly function only reads from memory pointed to by
650 // it's arguments with arbitrary offsets. If we can prove there are no
651 // writes to this memory in the loop, we can hoist or sink.
652 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) {
653 for (Value *Op : CI->arg_operands())
654 if (Op->getType()->isPointerTy() &&
655 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize,
656 AAMDNodes(), CurAST))
657 return false;
658 return true;
659 }
Duncan Sands68b6f502007-12-01 07:51:45 +0000660 // If this call only reads from memory and there are no writes to memory
661 // in the loop, we can hoist or sink the call as appropriate.
662 bool FoundMod = false;
Sanjay Patel9f088ab2016-01-08 22:59:42 +0000663 for (AliasSet &AS : *CurAST) {
Duncan Sands68b6f502007-12-01 07:51:45 +0000664 if (!AS.isForwardingAliasSet() && AS.isMod()) {
665 FoundMod = true;
666 break;
Chris Lattner20cda262004-03-15 04:11:30 +0000667 }
Chris Lattner20cda262004-03-15 04:11:30 +0000668 }
Dehao Chend55bc4c2016-05-05 00:54:54 +0000669 if (!FoundMod)
670 return true;
Chris Lattner20cda262004-03-15 04:11:30 +0000671 }
672
Nadav Rotem03dcd852012-09-04 10:25:04 +0000673 // FIXME: This should use mod/ref information to see if we can hoist or
674 // sink the call.
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000675
Chris Lattner20cda262004-03-15 04:11:30 +0000676 return false;
Chris Lattner65c11932003-12-09 19:32:44 +0000677 }
678
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000679 // Only these instructions are hoistable/sinkable.
680 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
681 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
682 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
683 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
684 !isa<InsertValueInst>(I))
685 return false;
686
Max Kazantsev0c8dd052017-10-11 07:26:45 +0000687 // If we are checking for sinking from preheader to loop body it will be
688 // always safe as there is no speculative execution.
689 if (SinkingToLoopBody)
Dehao Chen92abc7e2016-10-03 18:52:08 +0000690 return true;
691
Dehao Chen4b5e7f72016-09-02 01:59:27 +0000692 // TODO: Plumb the context instruction through to make hoisting and sinking
693 // more powerful. Hoisting of loads already works due to the special casing
694 // above.
695 return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr);
Chris Lattneraaaea512003-12-10 06:41:05 +0000696}
697
Hal Finkel3d4269a2015-02-22 18:35:32 +0000698/// Returns true if a PHINode is a trivially replaceable with an
Chandler Carruth8765cf72014-01-25 04:07:24 +0000699/// Instruction.
Hal Finkel3d4269a2015-02-22 18:35:32 +0000700/// This is true when all incoming values are that instruction.
701/// This pattern occurs most often with LCSSA PHI nodes.
Chandler Carruth8765cf72014-01-25 04:07:24 +0000702///
Pete Cooper47e80cd2015-05-12 20:05:20 +0000703static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000704 for (const Value *IncValue : PN.incoming_values())
705 if (IncValue != &I)
Chandler Carruth8765cf72014-01-25 04:07:24 +0000706 return false;
707
708 return true;
709}
710
Hal Finkel3d4269a2015-02-22 18:35:32 +0000711/// Return true if the only users of this instruction are outside of
712/// the loop. If this is true, we can sink the instruction to the exit
713/// blocks of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000714///
David Majnemer42a07302016-01-04 03:37:39 +0000715static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000716 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000717 const auto &BlockColors = SafetyInfo->BlockColors;
Pete Cooper0cabcf22015-05-13 01:12:18 +0000718 for (const User *U : I.users()) {
719 const Instruction *UI = cast<Instruction>(U);
720 if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
David Majnemer42a07302016-01-04 03:37:39 +0000721 const BasicBlock *BB = PN->getParent();
722 // We cannot sink uses in catchswitches.
723 if (isa<CatchSwitchInst>(BB->getTerminator()))
724 return false;
725
726 // We need to sink a callsite to a unique funclet. Avoid sinking if the
727 // phi use is too muddled.
728 if (isa<CallInst>(I))
729 if (!BlockColors.empty() &&
730 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
731 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000732 }
Chandler Carruth8765cf72014-01-25 04:07:24 +0000733
Chandler Carruthcdf47882014-03-09 03:16:01 +0000734 if (CurLoop->contains(UI))
Chandler Carruth8765cf72014-01-25 04:07:24 +0000735 return false;
Chris Lattner34399dd2003-12-11 22:23:32 +0000736 }
Chris Lattneraaaea512003-12-10 06:41:05 +0000737 return true;
738}
739
David Majnemer42a07302016-01-04 03:37:39 +0000740static Instruction *
741CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN,
742 const LoopInfo *LI,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000743 const LoopSafetyInfo *SafetyInfo) {
David Majnemer42a07302016-01-04 03:37:39 +0000744 Instruction *New;
745 if (auto *CI = dyn_cast<CallInst>(&I)) {
746 const auto &BlockColors = SafetyInfo->BlockColors;
747
748 // Sinking call-sites need to be handled differently from other
749 // instructions. The cloned call-site needs a funclet bundle operand
750 // appropriate for it's location in the CFG.
751 SmallVector<OperandBundleDef, 1> OpBundles;
752 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
753 BundleIdx != BundleEnd; ++BundleIdx) {
754 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
755 if (Bundle.getTagID() == LLVMContext::OB_funclet)
756 continue;
757
758 OpBundles.emplace_back(Bundle);
759 }
760
761 if (!BlockColors.empty()) {
762 const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
763 assert(CV.size() == 1 && "non-unique color for exit block!");
764 BasicBlock *BBColor = CV.front();
765 Instruction *EHPad = BBColor->getFirstNonPHI();
766 if (EHPad->isEHPad())
767 OpBundles.emplace_back("funclet", EHPad);
768 }
769
770 New = CallInst::Create(CI, OpBundles);
771 } else {
772 New = I.clone();
773 }
774
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000775 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000776 if (!I.getName().empty())
777 New->setName(I.getName() + ".le");
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000778
779 // Build LCSSA PHI nodes for any in-loop operands. Note that this is
780 // particularly cheap because we can rip off the PHI node that we're
781 // replacing for the number and blocks of the predecessors.
782 // OPT: If this shows up in a profile, we can instead finish sinking all
783 // invariant instructions, and then walk their operands to re-establish
784 // LCSSA. That will eliminate creating PHI nodes just to nuke them when
785 // sinking bottom-up.
786 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
787 ++OI)
788 if (Instruction *OInst = dyn_cast<Instruction>(*OI))
789 if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
790 if (!OLoop->contains(&PN)) {
791 PHINode *OpPN =
792 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000793 OInst->getName() + ".lcssa", &ExitBlock.front());
Evgeniy Stepanovd99cca22014-06-25 09:17:21 +0000794 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
795 OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
796 *OI = OpPN;
797 }
798 return New;
799}
800
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000801static Instruction *sinkThroughTriviallyReplacablePHI(
802 PHINode *TPN, Instruction *I, LoopInfo *LI,
803 SmallDenseMap<BasicBlock *, Instruction *, 32> &SunkCopies,
804 const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop) {
805 assert(isTriviallyReplacablePHI(*TPN, *I) &&
806 "Expect only trivially replacalbe PHI");
807 BasicBlock *ExitBlock = TPN->getParent();
808 Instruction *New;
809 auto It = SunkCopies.find(ExitBlock);
810 if (It != SunkCopies.end())
811 New = It->second;
812 else
813 New = SunkCopies[ExitBlock] =
814 CloneInstructionInExitBlock(*I, *ExitBlock, *TPN, LI, SafetyInfo);
815 return New;
816}
817
818static bool canSplitPredecessors(PHINode *PN) {
819 BasicBlock *BB = PN->getParent();
820 if (!BB->canSplitPredecessors())
821 return false;
822 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
823 BasicBlock *BBPred = *PI;
824 if (isa<IndirectBrInst>(BBPred->getTerminator()))
825 return false;
826 }
827 return true;
828}
829
830static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT,
831 LoopInfo *LI, const Loop *CurLoop) {
832#ifndef NDEBUG
833 SmallVector<BasicBlock *, 32> ExitBlocks;
834 CurLoop->getUniqueExitBlocks(ExitBlocks);
835 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
836 ExitBlocks.end());
837#endif
838 BasicBlock *ExitBB = PN->getParent();
839 assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
840
841 // Split predecessors of the loop exit to make instructions in the loop are
842 // exposed to exit blocks through trivially replacable PHIs while keeping the
843 // loop in the canonical form where each predecessor of each exit block should
844 // be contained within the loop. For example, this will convert the loop below
845 // from
846 //
847 // LB1:
848 // %v1 =
849 // br %LE, %LB2
850 // LB2:
851 // %v2 =
852 // br %LE, %LB1
853 // LE:
854 // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replacable
855 //
856 // to
857 //
858 // LB1:
859 // %v1 =
860 // br %LE.split, %LB2
861 // LB2:
862 // %v2 =
863 // br %LE.split2, %LB1
864 // LE.split:
865 // %p1 = phi [%v1, %LB1] <-- trivially replacable
866 // br %LE
867 // LE.split2:
868 // %p2 = phi [%v2, %LB2] <-- trivially replacable
869 // br %LE
870 // LE:
871 // %p = phi [%p1, %LE.split], [%p2, %LE.split2]
872 //
873 SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
874 while (!PredBBs.empty()) {
875 BasicBlock *PredBB = *PredBBs.begin();
876 assert(CurLoop->contains(PredBB) &&
877 "Expect all predecessors are in the loop");
878 if (PN->getBasicBlockIndex(PredBB) >= 0)
879 SplitBlockPredecessors(ExitBB, PredBB, ".split.loop.exit", DT, LI, true);
880 PredBBs.remove(PredBB);
881 }
882}
883
Hal Finkel3d4269a2015-02-22 18:35:32 +0000884/// When an instruction is found to only be used outside of the loop, this
885/// function moves it to the exit blocks and patches up SSA form as needed.
Chris Lattner91846012003-12-19 08:18:16 +0000886/// This method is guaranteed to remove the original instruction from its
887/// position, and may either delete it or move it to outside of the loop.
Chris Lattneraaaea512003-12-10 06:41:05 +0000888///
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000889static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
890 const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo,
Adam Nemet358433c2017-01-11 04:39:35 +0000891 OptimizationRemarkEmitter *ORE) {
Nick Lewycky299c6df2010-07-30 20:27:01 +0000892 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000893 ORE->emit([&]() {
894 return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
895 << "sinking " << ore::NV("Inst", &I);
896 });
Hal Finkel3d4269a2015-02-22 18:35:32 +0000897 bool Changed = false;
Dehao Chend55bc4c2016-05-05 00:54:54 +0000898 if (isa<LoadInst>(I))
899 ++NumMovedLoads;
900 else if (isa<CallInst>(I))
901 ++NumMovedCalls;
Chris Lattner55c21132003-12-10 20:43:29 +0000902 ++NumSunk;
903 Changed = true;
904
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000905 // Iterate over users to be ready for actual sinking. Replace users via
906 // unrechable blocks with undef and make all user PHIs trivially replcable.
907 SmallPtrSet<Instruction *, 8> VisitedUsers;
908 for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
909 auto *User = cast<Instruction>(*UI);
910 Use &U = UI.getUse();
911 ++UI;
912
913 if (VisitedUsers.count(User))
914 continue;
915
916 if (!DT->isReachableFromEntry(User->getParent())) {
Jun Bum Lim0f906722017-11-17 20:38:25 +0000917 U = UndefValue::get(I.getType());
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000918 continue;
919 }
920
921 // The user must be a PHI node.
922 PHINode *PN = cast<PHINode>(User);
923
924 // Surprisingly, instructions can be used outside of loops without any
925 // exits. This can only happen in PHI nodes if the incoming block is
926 // unreachable.
927 BasicBlock *BB = PN->getIncomingBlock(U);
928 if (!DT->isReachableFromEntry(BB)) {
929 U = UndefValue::get(I.getType());
930 continue;
931 }
932
933 VisitedUsers.insert(PN);
934 if (isTriviallyReplacablePHI(*PN, I))
935 continue;
936
937 if (!canSplitPredecessors(PN))
938 return false;
939
940 // Split predecessors of the PHI so that we can make users trivially
941 // replacable.
942 splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop);
943
944 // Should rebuild the iterators, as they may be invalidated by
945 // splitPredecessorsOfLoopExit().
946 UI = I.user_begin();
947 UE = I.user_end();
948 }
949
Chandler Carruthfc258542014-02-11 12:52:27 +0000950#ifndef NDEBUG
951 SmallVector<BasicBlock *, 32> ExitBlocks;
952 CurLoop->getUniqueExitBlocks(ExitBlocks);
Dehao Chend55bc4c2016-05-05 00:54:54 +0000953 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
Hal Finkel3d4269a2015-02-22 18:35:32 +0000954 ExitBlocks.end());
Chandler Carruthfc258542014-02-11 12:52:27 +0000955#endif
Chandler Carruth8765cf72014-01-25 04:07:24 +0000956
Evgeniy Stepanov10280da2014-06-25 07:54:58 +0000957 // Clones of this instruction. Don't create more than one per exit block!
958 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies;
959
Chandler Carruthfc258542014-02-11 12:52:27 +0000960 // If this instruction is only used outside of the loop, then all users are
961 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
962 // the instruction.
963 while (!I.use_empty()) {
David Majnemer6bc83e02015-07-12 03:53:05 +0000964 Value::user_iterator UI = I.user_begin();
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000965 PHINode *PN = cast<PHINode>(*UI);
966 assert(ExitBlockSet.count(PN->getParent()) &&
Chandler Carruthfc258542014-02-11 12:52:27 +0000967 "The LCSSA PHI is not in an exit block!");
Jun Bum Limf5fb3d72017-11-03 16:24:53 +0000968 // The PHI must be trivially replacable.
969 Instruction *New = sinkThroughTriviallyReplacablePHI(PN, &I, LI, SunkCopies,
970 SafetyInfo, CurLoop);
Chandler Carruthfc258542014-02-11 12:52:27 +0000971 PN->replaceAllUsesWith(New);
972 PN->eraseFromParent();
Chris Lattnercd96b4d2010-08-29 04:28:20 +0000973 }
Hal Finkel3d4269a2015-02-22 18:35:32 +0000974 return Changed;
Chris Lattneraaaea512003-12-10 06:41:05 +0000975}
Chris Lattner64437692002-09-29 21:46:09 +0000976
Hal Finkel3d4269a2015-02-22 18:35:32 +0000977/// When an instruction is found to only use loop invariant operands that
978/// is safe to hoist, this instruction is called to do the dirty work.
Chris Lattnerf64f2d32002-09-26 16:52:07 +0000979///
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000980static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
Adam Nemet358433c2017-01-11 04:39:35 +0000981 const LoopSafetyInfo *SafetyInfo,
982 OptimizationRemarkEmitter *ORE) {
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000983 auto *Preheader = CurLoop->getLoopPreheader();
Dehao Chend55bc4c2016-05-05 00:54:54 +0000984 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
985 << "\n");
Vivek Pandya95906582017-10-11 17:12:59 +0000986 ORE->emit([&]() {
987 return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
988 << ore::NV("Inst", &I);
989 });
Sanjoy Das7a2e2be2016-01-28 15:51:58 +0000990
991 // Metadata can be dependent on conditions we are hoisting above.
992 // Conservatively strip all metadata on the instruction unless we were
993 // guaranteed to execute I if we entered the loop, in which case the metadata
994 // is valid in the loop preheader.
995 if (I.hasMetadataOtherThanDebugLoc() &&
996 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
997 // time in isGuaranteedToExecute if we don't actually have anything to
998 // drop. It is a compile time optimization, not required for correctness.
999 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
1000 I.dropUnknownNonDebugMetadata();
1001
Chris Lattner6ac06592010-08-29 18:18:40 +00001002 // Move the new node to the Preheader, before its terminator.
1003 I.moveBefore(Preheader->getTerminator());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001004
Wolfgang Piebc17a2792017-01-06 18:38:57 +00001005 // Do not retain debug locations when we are moving instructions to different
1006 // basic blocks, because we want to avoid jumpy line tables. Calls, however,
1007 // need to retain their debug locs because they may be inlined.
1008 // FIXME: How do we retain source locations without causing poor debugging
1009 // behavior?
1010 if (!isa<CallInst>(I))
1011 I.setDebugLoc(DebugLoc());
1012
Dehao Chend55bc4c2016-05-05 00:54:54 +00001013 if (isa<LoadInst>(I))
1014 ++NumMovedLoads;
1015 else if (isa<CallInst>(I))
1016 ++NumMovedCalls;
Chris Lattner718b2212002-09-26 16:38:03 +00001017 ++NumHoisted;
Hal Finkel3d4269a2015-02-22 18:35:32 +00001018 return true;
Chris Lattner6ec05f52002-05-10 22:44:58 +00001019}
1020
Sanjoy Dasf8a0db52015-05-18 18:07:00 +00001021/// Only sink or hoist an instruction if it is not a trapping instruction,
1022/// or if the instruction is known not to trap when moved to the preheader.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001023/// or if it is a trapping instruction and is guaranteed to execute.
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001024static bool isSafeToExecuteUnconditionally(Instruction &Inst,
Pete Cooper0cabcf22015-05-13 01:12:18 +00001025 const DominatorTree *DT,
1026 const Loop *CurLoop,
Evgeniy Stepanov122f9842016-06-10 20:03:17 +00001027 const LoopSafetyInfo *SafetyInfo,
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001028 OptimizationRemarkEmitter *ORE,
Philip Reamesb47b9c22015-05-22 02:14:05 +00001029 const Instruction *CtxI) {
Sean Silva45835e72016-07-02 23:47:27 +00001030 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
Eli Friedmanb8f6a4f2009-07-17 04:28:42 +00001031 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001032
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001033 bool GuaranteedToExecute =
1034 isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
1035
1036 if (!GuaranteedToExecute) {
1037 auto *LI = dyn_cast<LoadInst>(&Inst);
1038 if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
Vivek Pandya95906582017-10-11 17:12:59 +00001039 ORE->emit([&]() {
1040 return OptimizationRemarkMissed(
1041 DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1042 << "failed to hoist load with loop-invariant address "
1043 "because load is conditionally executed";
1044 });
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001045 }
1046
1047 return GuaranteedToExecute;
Eli Friedman0cdc1482011-07-20 21:37:47 +00001048}
1049
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001050namespace {
Dehao Chend55bc4c2016-05-05 00:54:54 +00001051class LoopPromoter : public LoadAndStorePromoter {
1052 Value *SomePtr; // Designated pointer to store to.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001053 const SmallSetVector<Value *, 8> &PointerMustAliases;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001054 SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1055 SmallVectorImpl<Instruction *> &LoopInsertPts;
1056 PredIteratorCache &PredCache;
1057 AliasSetTracker &AST;
1058 LoopInfo &LI;
1059 DebugLoc DL;
1060 int Alignment;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001061 bool UnorderedAtomic;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001062 AAMDNodes AATags;
Chandler Carruthfc258542014-02-11 12:52:27 +00001063
Dehao Chend55bc4c2016-05-05 00:54:54 +00001064 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1065 if (Instruction *I = dyn_cast<Instruction>(V))
1066 if (Loop *L = LI.getLoopFor(I->getParent()))
1067 if (!L->contains(BB)) {
1068 // We need to create an LCSSA PHI node for the incoming value and
1069 // store that.
1070 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1071 I->getName() + ".lcssa", &BB->front());
1072 for (BasicBlock *Pred : PredCache.get(BB))
1073 PN->addIncoming(I, Pred);
1074 return PN;
1075 }
1076 return V;
1077 }
Chandler Carruthfc258542014-02-11 12:52:27 +00001078
Dehao Chend55bc4c2016-05-05 00:54:54 +00001079public:
1080 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001081 const SmallSetVector<Value *, 8> &PMA,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001082 SmallVectorImpl<BasicBlock *> &LEB,
1083 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC,
1084 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001085 bool UnorderedAtomic, const AAMDNodes &AATags)
Dehao Chend55bc4c2016-05-05 00:54:54 +00001086 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
1087 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001088 LI(li), DL(std::move(dl)), Alignment(alignment),
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001089 UnorderedAtomic(UnorderedAtomic), AATags(AATags) {}
Tobias Grossera3928f52011-07-06 19:20:02 +00001090
Dehao Chend55bc4c2016-05-05 00:54:54 +00001091 bool isInstInList(Instruction *I,
1092 const SmallVectorImpl<Instruction *> &) const override {
1093 Value *Ptr;
1094 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1095 Ptr = LI->getOperand(0);
1096 else
1097 Ptr = cast<StoreInst>(I)->getPointerOperand();
1098 return PointerMustAliases.count(Ptr);
1099 }
Tobias Grossera3928f52011-07-06 19:20:02 +00001100
Dehao Chend55bc4c2016-05-05 00:54:54 +00001101 void doExtraRewritesBeforeFinalDeletion() const override {
1102 // Insert stores after in the loop exit blocks. Each exit block gets a
1103 // store of the live-out values that feed them. Since we've already told
1104 // the SSA updater about the defs in the loop and the preheader
1105 // definition, it is all set and we can start using it.
1106 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1107 BasicBlock *ExitBlock = LoopExitBlocks[i];
1108 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1109 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1110 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1111 Instruction *InsertPos = LoopInsertPts[i];
1112 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001113 if (UnorderedAtomic)
1114 NewSI->setOrdering(AtomicOrdering::Unordered);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001115 NewSI->setAlignment(Alignment);
1116 NewSI->setDebugLoc(DL);
1117 if (AATags)
1118 NewSI->setAAMetadata(AATags);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001119 }
Dehao Chend55bc4c2016-05-05 00:54:54 +00001120 }
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001121
Dehao Chend55bc4c2016-05-05 00:54:54 +00001122 void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1123 // Update alias analysis.
1124 AST.copyValue(LI, V);
1125 }
1126 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
1127};
Philip Reames21cc2fa2017-10-26 21:00:15 +00001128
1129
1130/// Return true iff we can prove that a caller of this function can not inspect
1131/// the contents of the provided object in a well defined program.
1132bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) {
1133 if (isa<AllocaInst>(Object))
1134 // Since the alloca goes out of scope, we know the caller can't retain a
1135 // reference to it and be well defined. Thus, we don't need to check for
1136 // capture.
1137 return true;
1138
1139 // For all other objects we need to know that the caller can't possibly
1140 // have gotten a reference to the object. There are two components of
1141 // that:
1142 // 1) Object can't be escaped by this function. This is what
1143 // PointerMayBeCaptured checks.
1144 // 2) Object can't have been captured at definition site. For this, we
1145 // need to know the return value is noalias. At the moment, we use a
1146 // weaker condition and handle only AllocLikeFunctions (which are
1147 // known to be noalias). TODO
1148 return isAllocLikeFn(Object, TLI) &&
1149 !PointerMayBeCaptured(Object, true, true);
1150}
1151
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001152} // namespace
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001153
Hal Finkel3d4269a2015-02-22 18:35:32 +00001154/// Try to promote memory values to scalars by sinking stores out of the
1155/// loop and moving loads to before the loop. We do this by looping over
1156/// the stores in the loop, looking for stores to Must pointers which are
1157/// loop invariant.
Chris Lattner45d67d62003-02-24 03:52:32 +00001158///
Dehao Chend55bc4c2016-05-05 00:54:54 +00001159bool llvm::promoteLoopAccessesToScalars(
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001160 const SmallSetVector<Value *, 8> &PointerMustAliases,
1161 SmallVectorImpl<BasicBlock *> &ExitBlocks,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001162 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC,
1163 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
Adam Nemet358433c2017-01-11 04:39:35 +00001164 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
1165 OptimizationRemarkEmitter *ORE) {
Hal Finkel3d4269a2015-02-22 18:35:32 +00001166 // Verify inputs.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001167 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1168 CurAST != nullptr && SafetyInfo != nullptr &&
Hal Finkel3d4269a2015-02-22 18:35:32 +00001169 "Unexpected Input to promoteLoopAccessesToScalars");
Sanjay Patel99133222016-01-13 23:01:57 +00001170
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001171 Value *SomePtr = *PointerMustAliases.begin();
Dehao Chend55bc4c2016-05-05 00:54:54 +00001172 BasicBlock *Preheader = CurLoop->getLoopPreheader();
Chris Lattner45d67d62003-02-24 03:52:32 +00001173
Chris Lattner1dc98b42010-08-29 06:43:52 +00001174 // It isn't safe to promote a load/store from the loop if the load/store is
1175 // conditional. For example, turning:
Chris Lattner45d67d62003-02-24 03:52:32 +00001176 //
Chris Lattner1dc98b42010-08-29 06:43:52 +00001177 // for () { if (c) *P += 1; }
Chris Lattner45d67d62003-02-24 03:52:32 +00001178 //
Chris Lattner1dc98b42010-08-29 06:43:52 +00001179 // into:
1180 //
1181 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
1182 //
1183 // is not safe, because *P may only be valid to access if 'c' is true.
Tobias Grossera3928f52011-07-06 19:20:02 +00001184 //
Philip Reamesb54c8e62016-03-09 22:59:30 +00001185 // The safety property divides into two parts:
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001186 // p1) The memory may not be dereferenceable on entry to the loop. In this
Philip Reamesb54c8e62016-03-09 22:59:30 +00001187 // case, we can't insert the required load in the preheader.
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001188 // p2) The memory model does not allow us to insert a store along any dynamic
Philip Reamesb54c8e62016-03-09 22:59:30 +00001189 // path which did not originally have one.
1190 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001191 // If at least one store is guaranteed to execute, both properties are
1192 // satisfied, and promotion is legal.
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001193 //
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001194 // This, however, is not a necessary condition. Even if no store/load is
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001195 // guaranteed to execute, we can still establish these properties.
1196 // We can establish (p1) by proving that hoisting the load into the preheader
1197 // is safe (i.e. proving dereferenceability on all paths through the loop). We
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001198 // can use any access within the alias set to prove dereferenceability,
Philip Reamesb54c8e62016-03-09 22:59:30 +00001199 // since they're all must alias.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001200 //
1201 // There are two ways establish (p2):
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001202 // a) Prove the location is thread-local. In this case the memory model
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001203 // requirement does not apply, and stores are safe to insert.
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001204 // b) Prove a store dominates every exit block. In this case, if an exit
1205 // blocks is reached, the original dynamic path would have taken us through
1206 // the store, so inserting a store into the exit block is safe. Note that this
1207 // is different from the store being guaranteed to execute. For instance,
1208 // if an exception is thrown on the first iteration of the loop, the original
1209 // store is never executed, but the exit blocks are not executed either.
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001210
1211 bool DereferenceableInPH = false;
1212 bool SafeToInsertStore = false;
Philip Reamesb54c8e62016-03-09 22:59:30 +00001213
Dehao Chend55bc4c2016-05-05 00:54:54 +00001214 SmallVector<Instruction *, 64> LoopUses;
Chris Lattner45d67d62003-02-24 03:52:32 +00001215
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001216 // We start with an alignment of one and try to find instructions that allow
1217 // us to prove better alignment.
1218 unsigned Alignment = 1;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001219 // Keep track of which types of access we see
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001220 bool SawUnorderedAtomic = false;
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001221 bool SawNotAtomic = false;
Hal Finkelcc39b672014-07-24 12:16:19 +00001222 AAMDNodes AATags;
Dehao Chend55bc4c2016-05-05 00:54:54 +00001223
Philip Reamesb54c8e62016-03-09 22:59:30 +00001224 const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1225
Philip Reames21cc2fa2017-10-26 21:00:15 +00001226 bool IsKnownThreadLocalObject = false;
Evgeniy Stepanov58ccc092017-04-24 18:25:07 +00001227 if (SafetyInfo->MayThrow) {
Eli Friedmanee895052016-06-05 22:13:52 +00001228 // If a loop can throw, we have to insert a store along each unwind edge.
1229 // That said, we can't actually make the unwind edge explicit. Therefore,
Philip Reames21cc2fa2017-10-26 21:00:15 +00001230 // we have to prove that the store is dead along the unwind edge. We do
1231 // this by proving that the caller can't have a reference to the object
1232 // after return and thus can't possibly load from the object.
Xin Tong5ee40ba2017-01-19 19:31:40 +00001233 Value *Object = GetUnderlyingObject(SomePtr, MDL);
Philip Reames21cc2fa2017-10-26 21:00:15 +00001234 if (!isKnownNonEscaping(Object, TLI))
1235 return false;
1236 // Subtlety: Alloca's aren't visible to callers, but *are* potentially
1237 // visible to other threads if captured and used during their lifetimes.
1238 IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
Eli Friedmanee895052016-06-05 22:13:52 +00001239 }
1240
Chris Lattner1dc98b42010-08-29 06:43:52 +00001241 // Check that all of the pointers in the alias set have the same type. We
1242 // cannot (yet) promote a memory location that is loaded and stored in
Hal Finkelcc39b672014-07-24 12:16:19 +00001243 // different sizes. While we are at it, collect alignment and AA info.
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001244 for (Value *ASIV : PointerMustAliases) {
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001245 // Check that all of the pointers in the alias set have the same type. We
1246 // cannot (yet) promote a memory location that is loaded and stored in
1247 // different sizes.
Chris Lattner1dc98b42010-08-29 06:43:52 +00001248 if (SomePtr->getType() != ASIV->getType())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001249 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001250
Chandler Carruthcdf47882014-03-09 03:16:01 +00001251 for (User *U : ASIV->users()) {
Chris Lattner1dc98b42010-08-29 06:43:52 +00001252 // Ignore instructions that are outside the loop.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001253 Instruction *UI = dyn_cast<Instruction>(U);
1254 if (!UI || !CurLoop->contains(UI))
Chris Lattnerf12c08d2008-05-22 00:53:38 +00001255 continue;
Tobias Grossera3928f52011-07-06 19:20:02 +00001256
Chris Lattner1dc98b42010-08-29 06:43:52 +00001257 // If there is an non-load/store instruction in the loop, we can't promote
1258 // it.
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001259 if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
Sanjay Patel9f49b682016-01-08 22:05:03 +00001260 assert(!Load->isVolatile() && "AST broken");
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001261 if (!Load->isUnordered())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001262 return false;
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001263
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001264 SawUnorderedAtomic |= Load->isAtomic();
1265 SawNotAtomic |= !Load->isAtomic();
Philip Reamesb54c8e62016-03-09 22:59:30 +00001266
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001267 if (!DereferenceableInPH)
1268 DereferenceableInPH = isSafeToExecuteUnconditionally(
Adam Nemete2aaf3a2017-01-11 04:39:49 +00001269 *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator());
Sanjay Patel9f49b682016-01-08 22:05:03 +00001270 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
Chris Lattner408a6842010-12-19 05:57:25 +00001271 // Stores *of* the pointer are not interesting, only stores *to* the
1272 // pointer.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001273 if (UI->getOperand(1) != ASIV)
Chris Lattner408a6842010-12-19 05:57:25 +00001274 continue;
Sanjay Patel9f49b682016-01-08 22:05:03 +00001275 assert(!Store->isVolatile() && "AST broken");
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001276 if (!Store->isUnordered())
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001277 return false;
Eli Friedman0cdc1482011-07-20 21:37:47 +00001278
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001279 SawUnorderedAtomic |= Store->isAtomic();
1280 SawNotAtomic |= !Store->isAtomic();
1281
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001282 // If the store is guaranteed to execute, both properties are satisfied.
1283 // We may want to check if a store is guaranteed to execute even if we
1284 // already know that promotion is safe, since it may have higher
1285 // alignment than any other guaranteed stores, in which case we can
1286 // raise the alignment on the promoted store.
Sanjay Patel9f49b682016-01-08 22:05:03 +00001287 unsigned InstAlignment = Store->getAlignment();
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001288 if (!InstAlignment)
1289 InstAlignment =
1290 MDL.getABITypeAlignment(Store->getValueOperand()->getType());
1291
1292 if (!DereferenceableInPH || !SafeToInsertStore ||
1293 (InstAlignment > Alignment)) {
Hal Finkel3d4269a2015-02-22 18:35:32 +00001294 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001295 DereferenceableInPH = true;
1296 SafeToInsertStore = true;
1297 Alignment = std::max(Alignment, InstAlignment);
Eli Friedman0cdc1482011-07-20 21:37:47 +00001298 }
Anna Thomas67151352016-06-24 12:38:45 +00001299 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001300
Michael Kupersteinc9acad12017-01-05 20:42:06 +00001301 // If a store dominates all exit blocks, it is safe to sink.
1302 // As explained above, if an exit block was executed, a dominating
1303 // store must have been been executed at least once, so we are not
1304 // introducing stores on paths that did not have them.
1305 // Note that this only looks at explicit exit blocks. If we ever
1306 // start sinking stores into unwind edges (see above), this will break.
1307 if (!SafeToInsertStore)
1308 SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1309 return DT->dominates(Store->getParent(), Exit);
1310 });
1311
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001312 // If the store is not guaranteed to execute, we may still get
1313 // deref info through it.
1314 if (!DereferenceableInPH) {
1315 DereferenceableInPH = isDereferenceableAndAlignedPointer(
Dehao Chend55bc4c2016-05-05 00:54:54 +00001316 Store->getPointerOperand(), Store->getAlignment(), MDL,
Sean Silva45835e72016-07-02 23:47:27 +00001317 Preheader->getTerminator(), DT);
Philip Reamesb54c8e62016-03-09 22:59:30 +00001318 }
Chris Lattnerbe901902010-09-06 05:11:24 +00001319 } else
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001320 return false; // Not a load or store.
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001321
Hal Finkelcc39b672014-07-24 12:16:19 +00001322 // Merge the AA tags.
Chris Lattnerf5cca682012-12-31 08:37:17 +00001323 if (LoopUses.empty()) {
Hal Finkelcc39b672014-07-24 12:16:19 +00001324 // On the first load/store, just take its AA tags.
1325 UI->getAAMetadata(AATags);
1326 } else if (AATags) {
1327 UI->getAAMetadata(AATags, /* Merge = */ true);
Chris Lattnerf5cca682012-12-31 08:37:17 +00001328 }
Chandler Carruthcdf47882014-03-09 03:16:01 +00001329
1330 LoopUses.push_back(UI);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001331 }
1332 }
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001333
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001334 // If we found both an unordered atomic instruction and a non-atomic memory
1335 // access, bail. We can't blindly promote non-atomic to atomic since we
1336 // might not be able to lower the result. We can't downgrade since that
1337 // would violate memory model. Also, align 0 is an error for atomics.
1338 if (SawUnorderedAtomic && SawNotAtomic)
1339 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001340
1341 // If we couldn't prove we can hoist the load, bail.
1342 if (!DereferenceableInPH)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001343 return false;
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001344
1345 // We know we can hoist the load, but don't have a guaranteed store.
1346 // Check whether the location is thread-local. If it is, then we can insert
1347 // stores along paths which originally didn't have them without violating the
1348 // memory model.
1349 if (!SafeToInsertStore) {
Philip Reames21cc2fa2017-10-26 21:00:15 +00001350 if (IsKnownThreadLocalObject)
Xin Tong5ee40ba2017-01-19 19:31:40 +00001351 SafeToInsertStore = true;
1352 else {
1353 Value *Object = GetUnderlyingObject(SomePtr, MDL);
1354 SafeToInsertStore =
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001355 (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
1356 !PointerMayBeCaptured(Object, true, true);
Xin Tong5ee40ba2017-01-19 19:31:40 +00001357 }
Philip Reamesb54c8e62016-03-09 22:59:30 +00001358 }
Michael Kupersteinff36bae2016-12-29 23:11:19 +00001359
Michael Kuperstein62b98c32016-12-30 00:39:00 +00001360 // If we've still failed to prove we can sink the store, give up.
1361 if (!SafeToInsertStore)
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001362 return false;
Tobias Grossera3928f52011-07-06 19:20:02 +00001363
Chris Lattner1dc98b42010-08-29 06:43:52 +00001364 // Otherwise, this is safe to promote, lets do it!
Dehao Chend55bc4c2016-05-05 00:54:54 +00001365 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1366 << '\n');
Vivek Pandya95906582017-10-11 17:12:59 +00001367 ORE->emit([&]() {
1368 return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
1369 LoopUses[0])
1370 << "Moving accesses to memory location out of the loop";
1371 });
Chris Lattner1dc98b42010-08-29 06:43:52 +00001372 ++NumPromoted;
1373
Eli Friedmanddf7f552011-05-27 20:31:51 +00001374 // Grab a debug location for the inserted loads/stores; given that the
1375 // inserted loads/stores have little relation to the original loads/stores,
1376 // this code just arbitrarily picks a location from one, since any debug
1377 // location is better than none.
1378 DebugLoc DL = LoopUses[0]->getDebugLoc();
1379
Chris Lattner1dc98b42010-08-29 06:43:52 +00001380 // We use the SSAUpdater interface to insert phi nodes as required.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001381 SmallVector<PHINode *, 16> NewPHIs;
Chris Lattner1dc98b42010-08-29 06:43:52 +00001382 SSAUpdater SSA(&NewPHIs);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001383 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001384 InsertPts, PIC, *CurAST, *LI, DL, Alignment,
1385 SawUnorderedAtomic, AATags);
Tobias Grossera3928f52011-07-06 19:20:02 +00001386
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001387 // Set up the preheader to have a definition of the value. It is the live-out
1388 // value from the preheader that uses in the loop will use.
Dehao Chend55bc4c2016-05-05 00:54:54 +00001389 LoadInst *PreheaderLoad = new LoadInst(
1390 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
Philip Reamesb2bca7e2017-02-14 01:38:31 +00001391 if (SawUnorderedAtomic)
1392 PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
Tobias Grosser4a5d9a92011-07-06 19:19:55 +00001393 PreheaderLoad->setAlignment(Alignment);
Eli Friedmanddf7f552011-05-27 20:31:51 +00001394 PreheaderLoad->setDebugLoc(DL);
Dehao Chend55bc4c2016-05-05 00:54:54 +00001395 if (AATags)
1396 PreheaderLoad->setAAMetadata(AATags);
Chris Lattner1dc98b42010-08-29 06:43:52 +00001397 SSA.AddAvailableValue(Preheader, PreheaderLoad);
1398
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001399 // Rewrite all the loads in the loop and remember all the definitions from
1400 // stores in the loop.
1401 Promoter.run(LoopUses);
Eli Friedmanc5f22a72011-04-07 01:35:06 +00001402
1403 // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1404 if (PreheaderLoad->use_empty())
1405 PreheaderLoad->eraseFromParent();
Hal Finkel3d4269a2015-02-22 18:35:32 +00001406
Michael Kuperstein4a86a192016-12-30 00:43:22 +00001407 return true;
Chris Lattnera51fa882002-08-22 21:39:55 +00001408}
Devang Patelb98a0972007-07-31 08:01:41 +00001409
Roman Gareev036c0882016-02-15 14:48:50 +00001410/// Returns an owning pointer to an alias set which incorporates aliasing info
Chandler Carruthad8cb382016-02-27 04:34:07 +00001411/// from L and all subloops of L.
Xinliang David Licbb5e022016-08-11 22:34:00 +00001412/// FIXME: In new pass manager, there is no helper function to handle loop
1413/// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
Dehao Chen9cba1f42016-07-12 22:37:48 +00001414/// from scratch for every loop. Hook up with the helper functions when
1415/// available in the new pass manager to avoid redundant computation.
1416AliasSetTracker *
1417LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1418 AliasAnalysis *AA) {
Roman Gareev036c0882016-02-15 14:48:50 +00001419 AliasSetTracker *CurAST = nullptr;
Chandler Carruthad8cb382016-02-27 04:34:07 +00001420 SmallVector<Loop *, 4> RecomputeLoops;
Roman Gareev036c0882016-02-15 14:48:50 +00001421 for (Loop *InnerL : L->getSubLoops()) {
Chandler Carruthad8cb382016-02-27 04:34:07 +00001422 auto MapI = LoopToAliasSetMap.find(InnerL);
1423 // If the AST for this inner loop is missing it may have been merged into
1424 // some other loop's AST and then that loop unrolled, and so we need to
1425 // recompute it.
1426 if (MapI == LoopToAliasSetMap.end()) {
1427 RecomputeLoops.push_back(InnerL);
1428 continue;
1429 }
1430 AliasSetTracker *InnerAST = MapI->second;
Roman Gareev036c0882016-02-15 14:48:50 +00001431
1432 if (CurAST != nullptr) {
1433 // What if InnerLoop was modified by other passes ?
1434 CurAST->add(*InnerAST);
1435
1436 // Once we've incorporated the inner loop's AST into ours, we don't need
1437 // the subloop's anymore.
1438 delete InnerAST;
1439 } else {
1440 CurAST = InnerAST;
1441 }
Chandler Carruthad8cb382016-02-27 04:34:07 +00001442 LoopToAliasSetMap.erase(MapI);
Roman Gareev036c0882016-02-15 14:48:50 +00001443 }
1444 if (CurAST == nullptr)
1445 CurAST = new AliasSetTracker(*AA);
Chandler Carruthad8cb382016-02-27 04:34:07 +00001446
1447 auto mergeLoop = [&](Loop *L) {
1448 // Loop over the body of this loop, looking for calls, invokes, and stores.
Chandler Carruthad8cb382016-02-27 04:34:07 +00001449 for (BasicBlock *BB : L->blocks())
Alina Sbirlea80b806b2017-09-12 21:18:44 +00001450 CurAST->add(*BB); // Incorporate the specified basic block
Chandler Carruthad8cb382016-02-27 04:34:07 +00001451 };
1452
1453 // Add everything from the sub loops that are no longer directly available.
1454 for (Loop *InnerL : RecomputeLoops)
1455 mergeLoop(InnerL);
1456
1457 // And merge in this loop.
1458 mergeLoop(L);
1459
Roman Gareev036c0882016-02-15 14:48:50 +00001460 return CurAST;
1461}
1462
Ashutosh Nema47802622015-08-13 11:18:35 +00001463/// Simple analysis hook. Clone alias set info.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001464///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001465void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1466 Loop *L) {
1467 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001468 if (!AST)
1469 return;
1470
1471 AST->copyValue(From, To);
1472}
1473
Hal Finkel3d4269a2015-02-22 18:35:32 +00001474/// Simple Analysis hook. Delete value V from alias set
1475///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001476void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1477 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
Devang Patelb98a0972007-07-31 08:01:41 +00001478 if (!AST)
1479 return;
1480
1481 AST->deleteValue(V);
1482}
David Peixotto0d4d5e62014-09-24 16:48:31 +00001483
1484/// Simple Analysis hook. Delete value L from alias set map.
Hal Finkel3d4269a2015-02-22 18:35:32 +00001485///
Dehao Chen9cba1f42016-07-12 22:37:48 +00001486void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1487 AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001488 if (!AST)
1489 return;
1490
1491 delete AST;
Dehao Chen9cba1f42016-07-12 22:37:48 +00001492 LICM.getLoopToAliasSetMap().erase(L);
David Peixotto0d4d5e62014-09-24 16:48:31 +00001493}
Hal Finkel3d4269a2015-02-22 18:35:32 +00001494
Hal Finkel3d4269a2015-02-22 18:35:32 +00001495/// Return true if the body of this loop may store into the memory
1496/// location pointed to by V.
1497///
1498static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
Dehao Chend55bc4c2016-05-05 00:54:54 +00001499 const AAMDNodes &AAInfo,
Hal Finkel3d4269a2015-02-22 18:35:32 +00001500 AliasSetTracker *CurAST) {
1501 // Check to see if any of the basic blocks in CurLoop invalidate *V.
1502 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1503}
1504
1505/// Little predicate that returns true if the specified basic block is in
1506/// a subloop of the current one, not the current one itself.
1507///
1508static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1509 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1510 return LI->getLoopFor(BB) != CurLoop;
1511}