blob: 06083a4f5086c1c99e876b1d1f0a095af817490a [file] [log] [blame]
Adam Nemet938d3d62015-05-14 12:05:18 +00001//===- LoopDistribute.cpp - Loop Distribution Pass ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Loop Distribution Pass. Its main focus is to
11// distribute loops that cannot be vectorized due to dependence cycles. It
12// tries to isolate the offending dependences into a new loop allowing
13// vectorization of the remaining parts.
14//
15// For dependence analysis, the pass uses the LoopVectorizer's
16// LoopAccessAnalysis. Because this analysis presumes no change in the order of
17// memory operations, special care is taken to preserve the lexical order of
18// these operations.
19//
20// Similarly to the Vectorizer, the pass also supports loop versioning to
21// run-time disambiguate potentially overlapping arrays.
22//
23//===----------------------------------------------------------------------===//
24
Adam Nemetb2593f72016-07-18 16:29:27 +000025#include "llvm/Transforms/Scalar/LoopDistribute.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000026#include "llvm/ADT/DenseMap.h"
Adam Nemet938d3d62015-05-14 12:05:18 +000027#include "llvm/ADT/DepthFirstIterator.h"
28#include "llvm/ADT/EquivalenceClasses.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000029#include "llvm/ADT/Optional.h"
Adam Nemet938d3d62015-05-14 12:05:18 +000030#include "llvm/ADT/STLExtras.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000031#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/ADT/SmallVector.h"
Adam Nemet938d3d62015-05-14 12:05:18 +000033#include "llvm/ADT/Statistic.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000034#include "llvm/ADT/StringRef.h"
35#include "llvm/ADT/Twine.h"
36#include "llvm/ADT/iterator_range.h"
37#include "llvm/Analysis/AliasAnalysis.h"
38#include "llvm/Analysis/AssumptionCache.h"
Eli Friedman66fdba82016-09-16 18:01:48 +000039#include "llvm/Analysis/GlobalsModRef.h"
Adam Nemet938d3d62015-05-14 12:05:18 +000040#include "llvm/Analysis/LoopAccessAnalysis.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000041#include "llvm/Analysis/LoopAnalysisManager.h"
Adam Nemet938d3d62015-05-14 12:05:18 +000042#include "llvm/Analysis/LoopInfo.h"
Adam Nemet0965da22017-10-09 23:19:02 +000043#include "llvm/Analysis/OptimizationRemarkEmitter.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000044#include "llvm/Analysis/ScalarEvolution.h"
45#include "llvm/Analysis/TargetLibraryInfo.h"
46#include "llvm/Analysis/TargetTransformInfo.h"
47#include "llvm/IR/BasicBlock.h"
48#include "llvm/IR/Constants.h"
Adam Nemet0ba164b2016-04-28 23:08:32 +000049#include "llvm/IR/DiagnosticInfo.h"
Adam Nemet938d3d62015-05-14 12:05:18 +000050#include "llvm/IR/Dominators.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000051#include "llvm/IR/Function.h"
52#include "llvm/IR/InstrTypes.h"
53#include "llvm/IR/Instruction.h"
54#include "llvm/IR/Instructions.h"
55#include "llvm/IR/LLVMContext.h"
56#include "llvm/IR/Metadata.h"
57#include "llvm/IR/PassManager.h"
58#include "llvm/IR/Value.h"
Adam Nemet938d3d62015-05-14 12:05:18 +000059#include "llvm/Pass.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000060#include "llvm/Support/Casting.h"
Adam Nemet938d3d62015-05-14 12:05:18 +000061#include "llvm/Support/CommandLine.h"
62#include "llvm/Support/Debug.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000063#include "llvm/Support/raw_ostream.h"
64#include "llvm/Transforms/Scalar.h"
Adam Nemet938d3d62015-05-14 12:05:18 +000065#include "llvm/Transforms/Utils/BasicBlockUtils.h"
66#include "llvm/Transforms/Utils/Cloning.h"
Ashutosh Nemac5b7b552015-08-19 05:40:42 +000067#include "llvm/Transforms/Utils/LoopUtils.h"
Adam Nemet215746b2015-07-10 18:55:13 +000068#include "llvm/Transforms/Utils/LoopVersioning.h"
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000069#include "llvm/Transforms/Utils/ValueMapper.h"
70#include <cassert>
71#include <functional>
Adam Nemet938d3d62015-05-14 12:05:18 +000072#include <list>
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +000073#include <tuple>
74#include <utility>
75
76using namespace llvm;
Adam Nemet938d3d62015-05-14 12:05:18 +000077
78#define LDIST_NAME "loop-distribute"
79#define DEBUG_TYPE LDIST_NAME
80
Adam Nemet938d3d62015-05-14 12:05:18 +000081static cl::opt<bool>
82 LDistVerify("loop-distribute-verify", cl::Hidden,
83 cl::desc("Turn on DominatorTree and LoopInfo verification "
84 "after Loop Distribution"),
85 cl::init(false));
86
87static cl::opt<bool> DistributeNonIfConvertible(
88 "loop-distribute-non-if-convertible", cl::Hidden,
89 cl::desc("Whether to distribute into a loop that may not be "
90 "if-convertible by the loop vectorizer"),
91 cl::init(false));
92
Silviu Baranga2910a4f2015-11-09 13:26:09 +000093static cl::opt<unsigned> DistributeSCEVCheckThreshold(
94 "loop-distribute-scev-check-threshold", cl::init(8), cl::Hidden,
95 cl::desc("The maximum number of SCEV checks allowed for Loop "
96 "Distribution"));
97
Adam Nemetd2fa4142016-04-27 05:28:18 +000098static cl::opt<unsigned> PragmaDistributeSCEVCheckThreshold(
99 "loop-distribute-scev-check-threshold-with-pragma", cl::init(128),
100 cl::Hidden,
101 cl::desc(
102 "The maximum number of SCEV checks allowed for Loop "
103 "Distribution for loop marked with #pragma loop distribute(enable)"));
104
Adam Nemetd2fa4142016-04-27 05:28:18 +0000105static cl::opt<bool> EnableLoopDistribute(
106 "enable-loop-distribute", cl::Hidden,
Adam Nemet32e6a342016-12-21 04:07:40 +0000107 cl::desc("Enable the new, experimental LoopDistribution Pass"),
108 cl::init(false));
Adam Nemetd2fa4142016-04-27 05:28:18 +0000109
Adam Nemet938d3d62015-05-14 12:05:18 +0000110STATISTIC(NumLoopsDistributed, "Number of loops distributed");
111
Adam Nemet2f85b732015-05-14 12:33:32 +0000112namespace {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000113
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000114/// Maintains the set of instructions of the loop for a partition before
Adam Nemet938d3d62015-05-14 12:05:18 +0000115/// cloning. After cloning, it hosts the new loop.
116class InstPartition {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000117 using InstructionSet = SmallPtrSet<Instruction *, 8>;
Adam Nemet938d3d62015-05-14 12:05:18 +0000118
119public:
120 InstPartition(Instruction *I, Loop *L, bool DepCycle = false)
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000121 : DepCycle(DepCycle), OrigLoop(L) {
Adam Nemet938d3d62015-05-14 12:05:18 +0000122 Set.insert(I);
123 }
124
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000125 /// Returns whether this partition contains a dependence cycle.
Adam Nemet938d3d62015-05-14 12:05:18 +0000126 bool hasDepCycle() const { return DepCycle; }
127
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000128 /// Adds an instruction to this partition.
Adam Nemet938d3d62015-05-14 12:05:18 +0000129 void add(Instruction *I) { Set.insert(I); }
130
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000131 /// Collection accessors.
Adam Nemet938d3d62015-05-14 12:05:18 +0000132 InstructionSet::iterator begin() { return Set.begin(); }
133 InstructionSet::iterator end() { return Set.end(); }
134 InstructionSet::const_iterator begin() const { return Set.begin(); }
135 InstructionSet::const_iterator end() const { return Set.end(); }
136 bool empty() const { return Set.empty(); }
137
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000138 /// Moves this partition into \p Other. This partition becomes empty
Adam Nemet938d3d62015-05-14 12:05:18 +0000139 /// after this.
140 void moveTo(InstPartition &Other) {
141 Other.Set.insert(Set.begin(), Set.end());
142 Set.clear();
143 Other.DepCycle |= DepCycle;
144 }
145
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000146 /// Populates the partition with a transitive closure of all the
Adam Nemet938d3d62015-05-14 12:05:18 +0000147 /// instructions that the seeded instructions dependent on.
148 void populateUsedSet() {
149 // FIXME: We currently don't use control-dependence but simply include all
150 // blocks (possibly empty at the end) and let simplifycfg mostly clean this
151 // up.
152 for (auto *B : OrigLoop->getBlocks())
153 Set.insert(B->getTerminator());
154
155 // Follow the use-def chains to form a transitive closure of all the
156 // instructions that the originally seeded instructions depend on.
157 SmallVector<Instruction *, 8> Worklist(Set.begin(), Set.end());
158 while (!Worklist.empty()) {
159 Instruction *I = Worklist.pop_back_val();
160 // Insert instructions from the loop that we depend on.
161 for (Value *V : I->operand_values()) {
162 auto *I = dyn_cast<Instruction>(V);
163 if (I && OrigLoop->contains(I->getParent()) && Set.insert(I).second)
164 Worklist.push_back(I);
165 }
166 }
167 }
168
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000169 /// Clones the original loop.
Adam Nemet938d3d62015-05-14 12:05:18 +0000170 ///
171 /// Updates LoopInfo and DominatorTree using the information that block \p
172 /// LoopDomBB dominates the loop.
173 Loop *cloneLoopWithPreheader(BasicBlock *InsertBefore, BasicBlock *LoopDomBB,
174 unsigned Index, LoopInfo *LI,
175 DominatorTree *DT) {
176 ClonedLoop = ::cloneLoopWithPreheader(InsertBefore, LoopDomBB, OrigLoop,
177 VMap, Twine(".ldist") + Twine(Index),
178 LI, DT, ClonedLoopBlocks);
179 return ClonedLoop;
180 }
181
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000182 /// The cloned loop. If this partition is mapped to the original loop,
Adam Nemet938d3d62015-05-14 12:05:18 +0000183 /// this is null.
184 const Loop *getClonedLoop() const { return ClonedLoop; }
185
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000186 /// Returns the loop where this partition ends up after distribution.
Adam Nemet938d3d62015-05-14 12:05:18 +0000187 /// If this partition is mapped to the original loop then use the block from
188 /// the loop.
189 const Loop *getDistributedLoop() const {
190 return ClonedLoop ? ClonedLoop : OrigLoop;
191 }
192
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000193 /// The VMap that is populated by cloning and then used in
Adam Nemet938d3d62015-05-14 12:05:18 +0000194 /// remapinstruction to remap the cloned instructions.
195 ValueToValueMapTy &getVMap() { return VMap; }
196
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000197 /// Remaps the cloned instructions using VMap.
Adam Nemet1a689182015-07-10 18:55:09 +0000198 void remapInstructions() {
199 remapInstructionsInBlocks(ClonedLoopBlocks, VMap);
200 }
Adam Nemet938d3d62015-05-14 12:05:18 +0000201
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000202 /// Based on the set of instructions selected for this partition,
Adam Nemet938d3d62015-05-14 12:05:18 +0000203 /// removes the unnecessary ones.
204 void removeUnusedInsts() {
205 SmallVector<Instruction *, 8> Unused;
206
207 for (auto *Block : OrigLoop->getBlocks())
208 for (auto &Inst : *Block)
209 if (!Set.count(&Inst)) {
210 Instruction *NewInst = &Inst;
211 if (!VMap.empty())
212 NewInst = cast<Instruction>(VMap[NewInst]);
213
214 assert(!isa<BranchInst>(NewInst) &&
215 "Branches are marked used early on");
216 Unused.push_back(NewInst);
217 }
218
219 // Delete the instructions backwards, as it has a reduced likelihood of
220 // having to update as many def-use and use-def chains.
David Majnemerd7708772016-06-24 04:05:21 +0000221 for (auto *Inst : reverse(Unused)) {
Adam Nemet938d3d62015-05-14 12:05:18 +0000222 if (!Inst->use_empty())
223 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
224 Inst->eraseFromParent();
225 }
226 }
227
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000228 void print() const {
Adam Nemet938d3d62015-05-14 12:05:18 +0000229 if (DepCycle)
230 dbgs() << " (cycle)\n";
231 for (auto *I : Set)
232 // Prefix with the block name.
233 dbgs() << " " << I->getParent()->getName() << ":" << *I << "\n";
234 }
235
236 void printBlocks() const {
237 for (auto *BB : getDistributedLoop()->getBlocks())
238 dbgs() << *BB;
239 }
240
241private:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000242 /// Instructions from OrigLoop selected for this partition.
Adam Nemet938d3d62015-05-14 12:05:18 +0000243 InstructionSet Set;
244
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000245 /// Whether this partition contains a dependence cycle.
Adam Nemet938d3d62015-05-14 12:05:18 +0000246 bool DepCycle;
247
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000248 /// The original loop.
Adam Nemet938d3d62015-05-14 12:05:18 +0000249 Loop *OrigLoop;
250
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000251 /// The cloned loop. If this partition is mapped to the original loop,
Adam Nemet938d3d62015-05-14 12:05:18 +0000252 /// this is null.
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000253 Loop *ClonedLoop = nullptr;
Adam Nemet938d3d62015-05-14 12:05:18 +0000254
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000255 /// The blocks of ClonedLoop including the preheader. If this
Adam Nemet938d3d62015-05-14 12:05:18 +0000256 /// partition is mapped to the original loop, this is empty.
257 SmallVector<BasicBlock *, 8> ClonedLoopBlocks;
258
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000259 /// These gets populated once the set of instructions have been
Adam Nemet938d3d62015-05-14 12:05:18 +0000260 /// finalized. If this partition is mapped to the original loop, these are not
261 /// set.
262 ValueToValueMapTy VMap;
263};
264
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000265/// Holds the set of Partitions. It populates them, merges them and then
Adam Nemet938d3d62015-05-14 12:05:18 +0000266/// clones the loops.
267class InstPartitionContainer {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000268 using InstToPartitionIdT = DenseMap<Instruction *, int>;
Adam Nemet938d3d62015-05-14 12:05:18 +0000269
270public:
271 InstPartitionContainer(Loop *L, LoopInfo *LI, DominatorTree *DT)
272 : L(L), LI(LI), DT(DT) {}
273
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000274 /// Returns the number of partitions.
Adam Nemet938d3d62015-05-14 12:05:18 +0000275 unsigned getSize() const { return PartitionContainer.size(); }
276
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000277 /// Adds \p Inst into the current partition if that is marked to
Adam Nemet938d3d62015-05-14 12:05:18 +0000278 /// contain cycles. Otherwise start a new partition for it.
279 void addToCyclicPartition(Instruction *Inst) {
280 // If the current partition is non-cyclic. Start a new one.
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000281 if (PartitionContainer.empty() || !PartitionContainer.back().hasDepCycle())
282 PartitionContainer.emplace_back(Inst, L, /*DepCycle=*/true);
Adam Nemet938d3d62015-05-14 12:05:18 +0000283 else
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000284 PartitionContainer.back().add(Inst);
Adam Nemet938d3d62015-05-14 12:05:18 +0000285 }
286
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000287 /// Adds \p Inst into a partition that is not marked to contain
Adam Nemet938d3d62015-05-14 12:05:18 +0000288 /// dependence cycles.
289 ///
290 // Initially we isolate memory instructions into as many partitions as
291 // possible, then later we may merge them back together.
292 void addToNewNonCyclicPartition(Instruction *Inst) {
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000293 PartitionContainer.emplace_back(Inst, L);
Adam Nemet938d3d62015-05-14 12:05:18 +0000294 }
295
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000296 /// Merges adjacent non-cyclic partitions.
Adam Nemet938d3d62015-05-14 12:05:18 +0000297 ///
298 /// The idea is that we currently only want to isolate the non-vectorizable
299 /// partition. We could later allow more distribution among these partition
300 /// too.
301 void mergeAdjacentNonCyclic() {
302 mergeAdjacentPartitionsIf(
303 [](const InstPartition *P) { return !P->hasDepCycle(); });
304 }
305
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000306 /// If a partition contains only conditional stores, we won't vectorize
Adam Nemet938d3d62015-05-14 12:05:18 +0000307 /// it. Try to merge it with a previous cyclic partition.
308 void mergeNonIfConvertible() {
309 mergeAdjacentPartitionsIf([&](const InstPartition *Partition) {
310 if (Partition->hasDepCycle())
311 return true;
312
313 // Now, check if all stores are conditional in this partition.
314 bool seenStore = false;
315
316 for (auto *Inst : *Partition)
317 if (isa<StoreInst>(Inst)) {
318 seenStore = true;
319 if (!LoopAccessInfo::blockNeedsPredication(Inst->getParent(), L, DT))
320 return false;
321 }
322 return seenStore;
323 });
324 }
325
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000326 /// Merges the partitions according to various heuristics.
Adam Nemet938d3d62015-05-14 12:05:18 +0000327 void mergeBeforePopulating() {
328 mergeAdjacentNonCyclic();
329 if (!DistributeNonIfConvertible)
330 mergeNonIfConvertible();
331 }
332
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000333 /// Merges partitions in order to ensure that no loads are duplicated.
Adam Nemet938d3d62015-05-14 12:05:18 +0000334 ///
335 /// We can't duplicate loads because that could potentially reorder them.
336 /// LoopAccessAnalysis provides dependency information with the context that
337 /// the order of memory operation is preserved.
338 ///
339 /// Return if any partitions were merged.
340 bool mergeToAvoidDuplicatedLoads() {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000341 using LoadToPartitionT = DenseMap<Instruction *, InstPartition *>;
342 using ToBeMergedT = EquivalenceClasses<InstPartition *>;
Adam Nemet938d3d62015-05-14 12:05:18 +0000343
344 LoadToPartitionT LoadToPartition;
345 ToBeMergedT ToBeMerged;
346
347 // Step through the partitions and create equivalence between partitions
348 // that contain the same load. Also put partitions in between them in the
349 // same equivalence class to avoid reordering of memory operations.
350 for (PartitionContainerT::iterator I = PartitionContainer.begin(),
351 E = PartitionContainer.end();
352 I != E; ++I) {
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000353 auto *PartI = &*I;
Adam Nemet938d3d62015-05-14 12:05:18 +0000354
355 // If a load occurs in two partitions PartI and PartJ, merge all
356 // partitions (PartI, PartJ] into PartI.
357 for (Instruction *Inst : *PartI)
358 if (isa<LoadInst>(Inst)) {
359 bool NewElt;
360 LoadToPartitionT::iterator LoadToPart;
361
362 std::tie(LoadToPart, NewElt) =
363 LoadToPartition.insert(std::make_pair(Inst, PartI));
364 if (!NewElt) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000365 LLVM_DEBUG(dbgs()
366 << "Merging partitions due to this load in multiple "
367 << "partitions: " << PartI << ", " << LoadToPart->second
368 << "\n"
369 << *Inst << "\n");
Adam Nemet938d3d62015-05-14 12:05:18 +0000370
371 auto PartJ = I;
372 do {
373 --PartJ;
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000374 ToBeMerged.unionSets(PartI, &*PartJ);
375 } while (&*PartJ != LoadToPart->second);
Adam Nemet938d3d62015-05-14 12:05:18 +0000376 }
377 }
378 }
379 if (ToBeMerged.empty())
380 return false;
381
382 // Merge the member of an equivalence class into its class leader. This
383 // makes the members empty.
384 for (ToBeMergedT::iterator I = ToBeMerged.begin(), E = ToBeMerged.end();
385 I != E; ++I) {
386 if (!I->isLeader())
387 continue;
388
389 auto PartI = I->getData();
390 for (auto PartJ : make_range(std::next(ToBeMerged.member_begin(I)),
391 ToBeMerged.member_end())) {
392 PartJ->moveTo(*PartI);
393 }
394 }
395
396 // Remove the empty partitions.
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000397 PartitionContainer.remove_if(
398 [](const InstPartition &P) { return P.empty(); });
Adam Nemet938d3d62015-05-14 12:05:18 +0000399
400 return true;
401 }
402
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000403 /// Sets up the mapping between instructions to partitions. If the
Adam Nemet938d3d62015-05-14 12:05:18 +0000404 /// instruction is duplicated across multiple partitions, set the entry to -1.
405 void setupPartitionIdOnInstructions() {
406 int PartitionID = 0;
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000407 for (const auto &Partition : PartitionContainer) {
408 for (Instruction *Inst : Partition) {
Adam Nemet938d3d62015-05-14 12:05:18 +0000409 bool NewElt;
410 InstToPartitionIdT::iterator Iter;
411
412 std::tie(Iter, NewElt) =
413 InstToPartitionId.insert(std::make_pair(Inst, PartitionID));
414 if (!NewElt)
415 Iter->second = -1;
416 }
417 ++PartitionID;
418 }
419 }
420
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000421 /// Populates the partition with everything that the seeding
Adam Nemet938d3d62015-05-14 12:05:18 +0000422 /// instructions require.
423 void populateUsedSet() {
424 for (auto &P : PartitionContainer)
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000425 P.populateUsedSet();
Adam Nemet938d3d62015-05-14 12:05:18 +0000426 }
427
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000428 /// This performs the main chunk of the work of cloning the loops for
Adam Nemet938d3d62015-05-14 12:05:18 +0000429 /// the partitions.
Justin Bogner843fb202015-12-15 19:40:57 +0000430 void cloneLoops() {
Adam Nemet938d3d62015-05-14 12:05:18 +0000431 BasicBlock *OrigPH = L->getLoopPreheader();
432 // At this point the predecessor of the preheader is either the memcheck
433 // block or the top part of the original preheader.
434 BasicBlock *Pred = OrigPH->getSinglePredecessor();
435 assert(Pred && "Preheader does not have a single predecessor");
436 BasicBlock *ExitBlock = L->getExitBlock();
437 assert(ExitBlock && "No single exit block");
438 Loop *NewLoop;
439
440 assert(!PartitionContainer.empty() && "at least two partitions expected");
441 // We're cloning the preheader along with the loop so we already made sure
442 // it was empty.
443 assert(&*OrigPH->begin() == OrigPH->getTerminator() &&
444 "preheader not empty");
445
446 // Create a loop for each partition except the last. Clone the original
447 // loop before PH along with adding a preheader for the cloned loop. Then
448 // update PH to point to the newly added preheader.
449 BasicBlock *TopPH = OrigPH;
450 unsigned Index = getSize() - 1;
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000451 for (auto I = std::next(PartitionContainer.rbegin()),
452 E = PartitionContainer.rend();
Adam Nemet938d3d62015-05-14 12:05:18 +0000453 I != E; ++I, --Index, TopPH = NewLoop->getLoopPreheader()) {
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000454 auto *Part = &*I;
Adam Nemet938d3d62015-05-14 12:05:18 +0000455
456 NewLoop = Part->cloneLoopWithPreheader(TopPH, Pred, Index, LI, DT);
457
458 Part->getVMap()[ExitBlock] = TopPH;
459 Part->remapInstructions();
460 }
461 Pred->getTerminator()->replaceUsesOfWith(OrigPH, TopPH);
462
463 // Now go in forward order and update the immediate dominator for the
464 // preheaders with the exiting block of the previous loop. Dominance
465 // within the loop is updated in cloneLoopWithPreheader.
466 for (auto Curr = PartitionContainer.cbegin(),
467 Next = std::next(PartitionContainer.cbegin()),
468 E = PartitionContainer.cend();
469 Next != E; ++Curr, ++Next)
470 DT->changeImmediateDominator(
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000471 Next->getDistributedLoop()->getLoopPreheader(),
472 Curr->getDistributedLoop()->getExitingBlock());
Adam Nemet938d3d62015-05-14 12:05:18 +0000473 }
474
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000475 /// Removes the dead instructions from the cloned loops.
Adam Nemet938d3d62015-05-14 12:05:18 +0000476 void removeUnusedInsts() {
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000477 for (auto &Partition : PartitionContainer)
478 Partition.removeUnusedInsts();
Adam Nemet938d3d62015-05-14 12:05:18 +0000479 }
480
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000481 /// For each memory pointer, it computes the partitionId the pointer is
Adam Nemet938d3d62015-05-14 12:05:18 +0000482 /// used in.
483 ///
484 /// This returns an array of int where the I-th entry corresponds to I-th
485 /// entry in LAI.getRuntimePointerCheck(). If the pointer is used in multiple
486 /// partitions its entry is set to -1.
487 SmallVector<int, 8>
488 computePartitionSetForPointers(const LoopAccessInfo &LAI) {
Adam Nemet7cdebac2015-07-14 22:32:44 +0000489 const RuntimePointerChecking *RtPtrCheck = LAI.getRuntimePointerChecking();
Adam Nemet938d3d62015-05-14 12:05:18 +0000490
491 unsigned N = RtPtrCheck->Pointers.size();
492 SmallVector<int, 8> PtrToPartitions(N);
493 for (unsigned I = 0; I < N; ++I) {
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000494 Value *Ptr = RtPtrCheck->Pointers[I].PointerValue;
Adam Nemet938d3d62015-05-14 12:05:18 +0000495 auto Instructions =
Adam Nemet9f7dedc2015-07-14 22:32:50 +0000496 LAI.getInstructionsForAccess(Ptr, RtPtrCheck->Pointers[I].IsWritePtr);
Adam Nemet938d3d62015-05-14 12:05:18 +0000497
498 int &Partition = PtrToPartitions[I];
499 // First set it to uninitialized.
500 Partition = -2;
501 for (Instruction *Inst : Instructions) {
502 // Note that this could be -1 if Inst is duplicated across multiple
503 // partitions.
504 int ThisPartition = this->InstToPartitionId[Inst];
505 if (Partition == -2)
506 Partition = ThisPartition;
507 // -1 means belonging to multiple partitions.
508 else if (Partition == -1)
509 break;
510 else if (Partition != (int)ThisPartition)
511 Partition = -1;
512 }
513 assert(Partition != -2 && "Pointer not belonging to any partition");
514 }
515
516 return PtrToPartitions;
517 }
518
519 void print(raw_ostream &OS) const {
520 unsigned Index = 0;
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000521 for (const auto &P : PartitionContainer) {
522 OS << "Partition " << Index++ << " (" << &P << "):\n";
523 P.print();
Adam Nemet938d3d62015-05-14 12:05:18 +0000524 }
525 }
526
527 void dump() const { print(dbgs()); }
528
529#ifndef NDEBUG
530 friend raw_ostream &operator<<(raw_ostream &OS,
531 const InstPartitionContainer &Partitions) {
532 Partitions.print(OS);
533 return OS;
534 }
535#endif
536
537 void printBlocks() const {
538 unsigned Index = 0;
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000539 for (const auto &P : PartitionContainer) {
540 dbgs() << "\nPartition " << Index++ << " (" << &P << "):\n";
541 P.printBlocks();
Adam Nemet938d3d62015-05-14 12:05:18 +0000542 }
543 }
544
545private:
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000546 using PartitionContainerT = std::list<InstPartition>;
Adam Nemet938d3d62015-05-14 12:05:18 +0000547
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000548 /// List of partitions.
Adam Nemet938d3d62015-05-14 12:05:18 +0000549 PartitionContainerT PartitionContainer;
550
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000551 /// Mapping from Instruction to partition Id. If the instruction
Adam Nemet938d3d62015-05-14 12:05:18 +0000552 /// belongs to multiple partitions the entry contains -1.
553 InstToPartitionIdT InstToPartitionId;
554
555 Loop *L;
556 LoopInfo *LI;
557 DominatorTree *DT;
558
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000559 /// The control structure to merge adjacent partitions if both satisfy
Adam Nemet938d3d62015-05-14 12:05:18 +0000560 /// the \p Predicate.
561 template <class UnaryPredicate>
562 void mergeAdjacentPartitionsIf(UnaryPredicate Predicate) {
563 InstPartition *PrevMatch = nullptr;
564 for (auto I = PartitionContainer.begin(); I != PartitionContainer.end();) {
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000565 auto DoesMatch = Predicate(&*I);
Adam Nemet938d3d62015-05-14 12:05:18 +0000566 if (PrevMatch == nullptr && DoesMatch) {
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000567 PrevMatch = &*I;
Adam Nemet938d3d62015-05-14 12:05:18 +0000568 ++I;
569 } else if (PrevMatch != nullptr && DoesMatch) {
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000570 I->moveTo(*PrevMatch);
Adam Nemet938d3d62015-05-14 12:05:18 +0000571 I = PartitionContainer.erase(I);
572 } else {
573 PrevMatch = nullptr;
574 ++I;
575 }
576 }
577 }
578};
579
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000580/// For each memory instruction, this class maintains difference of the
Adam Nemet938d3d62015-05-14 12:05:18 +0000581/// number of unsafe dependences that start out from this instruction minus
582/// those that end here.
583///
584/// By traversing the memory instructions in program order and accumulating this
585/// number, we know whether any unsafe dependence crosses over a program point.
586class MemoryInstructionDependences {
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000587 using Dependence = MemoryDepChecker::Dependence;
Adam Nemet938d3d62015-05-14 12:05:18 +0000588
589public:
590 struct Entry {
591 Instruction *Inst;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000592 unsigned NumUnsafeDependencesStartOrEnd = 0;
Adam Nemet938d3d62015-05-14 12:05:18 +0000593
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000594 Entry(Instruction *Inst) : Inst(Inst) {}
Adam Nemet938d3d62015-05-14 12:05:18 +0000595 };
596
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000597 using AccessesType = SmallVector<Entry, 8>;
Adam Nemet938d3d62015-05-14 12:05:18 +0000598
599 AccessesType::const_iterator begin() const { return Accesses.begin(); }
600 AccessesType::const_iterator end() const { return Accesses.end(); }
601
602 MemoryInstructionDependences(
603 const SmallVectorImpl<Instruction *> &Instructions,
Adam Nemeta2df7502015-11-03 21:39:52 +0000604 const SmallVectorImpl<Dependence> &Dependences) {
Benjamin Kramere6987bf2015-05-21 18:32:07 +0000605 Accesses.append(Instructions.begin(), Instructions.end());
Adam Nemet938d3d62015-05-14 12:05:18 +0000606
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000607 LLVM_DEBUG(dbgs() << "Backward dependences:\n");
Adam Nemeta2df7502015-11-03 21:39:52 +0000608 for (auto &Dep : Dependences)
Adam Nemet938d3d62015-05-14 12:05:18 +0000609 if (Dep.isPossiblyBackward()) {
610 // Note that the designations source and destination follow the program
611 // order, i.e. source is always first. (The direction is given by the
612 // DepType.)
613 ++Accesses[Dep.Source].NumUnsafeDependencesStartOrEnd;
614 --Accesses[Dep.Destination].NumUnsafeDependencesStartOrEnd;
615
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000616 LLVM_DEBUG(Dep.print(dbgs(), 2, Instructions));
Adam Nemet938d3d62015-05-14 12:05:18 +0000617 }
618 }
619
620private:
621 AccessesType Accesses;
622};
623
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000624/// The actual class performing the per-loop work.
Adam Nemet61399ac2016-04-27 00:31:03 +0000625class LoopDistributeForLoop {
Adam Nemet938d3d62015-05-14 12:05:18 +0000626public:
Adam Nemeteff76642016-05-13 04:20:31 +0000627 LoopDistributeForLoop(Loop *L, Function *F, LoopInfo *LI, DominatorTree *DT,
Adam Nemetaad81602016-07-15 17:23:20 +0000628 ScalarEvolution *SE, OptimizationRemarkEmitter *ORE)
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000629 : L(L), F(F), LI(LI), DT(DT), SE(SE), ORE(ORE) {
Adam Nemetd2fa4142016-04-27 05:28:18 +0000630 setForced();
631 }
Adam Nemetc75ad692015-07-30 03:29:16 +0000632
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000633 /// Try to distribute an inner-most loop.
Adam Nemetb2593f72016-07-18 16:29:27 +0000634 bool processLoop(std::function<const LoopAccessInfo &(Loop &)> &GetLAA) {
Adam Nemet938d3d62015-05-14 12:05:18 +0000635 assert(L->empty() && "Only process inner loops.");
636
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000637 LLVM_DEBUG(dbgs() << "\nLDist: In \""
638 << L->getHeader()->getParent()->getName()
639 << "\" checking " << *L << "\n");
Adam Nemet938d3d62015-05-14 12:05:18 +0000640
Adam Nemet7f38e112016-04-28 23:08:27 +0000641 if (!L->getExitBlock())
Adam Nemetf744ad72016-09-30 04:56:25 +0000642 return fail("MultipleExitBlocks", "multiple exit blocks");
Florian Hahn2e032132016-12-19 17:13:37 +0000643 if (!L->isLoopSimplifyForm())
644 return fail("NotLoopSimplifyForm",
645 "loop is not in loop-simplify form");
646
647 BasicBlock *PH = L->getLoopPreheader();
Adam Nemeteff76642016-05-13 04:20:31 +0000648
Adam Nemet938d3d62015-05-14 12:05:18 +0000649 // LAA will check that we only have a single exiting block.
Adam Nemetb2593f72016-07-18 16:29:27 +0000650 LAI = &GetLAA(*L);
Adam Nemet938d3d62015-05-14 12:05:18 +0000651
Adam Nemet938d3d62015-05-14 12:05:18 +0000652 // Currently, we only distribute to isolate the part of the loop with
653 // dependence cycles to enable partial vectorization.
Adam Nemeteff76642016-05-13 04:20:31 +0000654 if (LAI->canVectorizeMemory())
Adam Nemetf744ad72016-09-30 04:56:25 +0000655 return fail("MemOpsCanBeVectorized",
656 "memory operations are safe for vectorization");
Adam Nemet7f38e112016-04-28 23:08:27 +0000657
Adam Nemeteff76642016-05-13 04:20:31 +0000658 auto *Dependences = LAI->getDepChecker().getDependences();
Adam Nemet7f38e112016-04-28 23:08:27 +0000659 if (!Dependences || Dependences->empty())
Adam Nemetf744ad72016-09-30 04:56:25 +0000660 return fail("NoUnsafeDeps", "no unsafe dependences to isolate");
Adam Nemet938d3d62015-05-14 12:05:18 +0000661
662 InstPartitionContainer Partitions(L, LI, DT);
663
664 // First, go through each memory operation and assign them to consecutive
665 // partitions (the order of partitions follows program order). Put those
666 // with unsafe dependences into "cyclic" partition otherwise put each store
667 // in its own "non-cyclic" partition (we'll merge these later).
668 //
669 // Note that a memory operation (e.g. Load2 below) at a program point that
670 // has an unsafe dependence (Store3->Load1) spanning over it must be
671 // included in the same cyclic partition as the dependent operations. This
672 // is to preserve the original program order after distribution. E.g.:
673 //
674 // NumUnsafeDependencesStartOrEnd NumUnsafeDependencesActive
675 // Load1 -. 1 0->1
676 // Load2 | /Unsafe/ 0 1
677 // Store3 -' -1 1->0
678 // Load4 0 0
679 //
680 // NumUnsafeDependencesActive > 0 indicates this situation and in this case
681 // we just keep assigning to the same cyclic partition until
682 // NumUnsafeDependencesActive reaches 0.
Adam Nemeteff76642016-05-13 04:20:31 +0000683 const MemoryDepChecker &DepChecker = LAI->getDepChecker();
Adam Nemet938d3d62015-05-14 12:05:18 +0000684 MemoryInstructionDependences MID(DepChecker.getMemoryInstructions(),
Adam Nemeta2df7502015-11-03 21:39:52 +0000685 *Dependences);
Adam Nemet938d3d62015-05-14 12:05:18 +0000686
687 int NumUnsafeDependencesActive = 0;
688 for (auto &InstDep : MID) {
689 Instruction *I = InstDep.Inst;
690 // We update NumUnsafeDependencesActive post-instruction, catch the
691 // start of a dependence directly via NumUnsafeDependencesStartOrEnd.
692 if (NumUnsafeDependencesActive ||
693 InstDep.NumUnsafeDependencesStartOrEnd > 0)
694 Partitions.addToCyclicPartition(I);
695 else
696 Partitions.addToNewNonCyclicPartition(I);
697 NumUnsafeDependencesActive += InstDep.NumUnsafeDependencesStartOrEnd;
698 assert(NumUnsafeDependencesActive >= 0 &&
699 "Negative number of dependences active");
700 }
701
702 // Add partitions for values used outside. These partitions can be out of
703 // order from the original program order. This is OK because if the
704 // partition uses a load we will merge this partition with the original
705 // partition of the load that we set up in the previous loop (see
706 // mergeToAvoidDuplicatedLoads).
707 auto DefsUsedOutside = findDefsUsedOutsideOfLoop(L);
708 for (auto *Inst : DefsUsedOutside)
709 Partitions.addToNewNonCyclicPartition(Inst);
710
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000711 LLVM_DEBUG(dbgs() << "Seeded partitions:\n" << Partitions);
Adam Nemet938d3d62015-05-14 12:05:18 +0000712 if (Partitions.getSize() < 2)
Adam Nemetf744ad72016-09-30 04:56:25 +0000713 return fail("CantIsolateUnsafeDeps",
714 "cannot isolate unsafe dependencies");
Adam Nemet938d3d62015-05-14 12:05:18 +0000715
716 // Run the merge heuristics: Merge non-cyclic adjacent partitions since we
717 // should be able to vectorize these together.
718 Partitions.mergeBeforePopulating();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000719 LLVM_DEBUG(dbgs() << "\nMerged partitions:\n" << Partitions);
Adam Nemet938d3d62015-05-14 12:05:18 +0000720 if (Partitions.getSize() < 2)
Adam Nemetf744ad72016-09-30 04:56:25 +0000721 return fail("CantIsolateUnsafeDeps",
722 "cannot isolate unsafe dependencies");
Adam Nemet938d3d62015-05-14 12:05:18 +0000723
724 // Now, populate the partitions with non-memory operations.
725 Partitions.populateUsedSet();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000726 LLVM_DEBUG(dbgs() << "\nPopulated partitions:\n" << Partitions);
Adam Nemet938d3d62015-05-14 12:05:18 +0000727
728 // In order to preserve original lexical order for loads, keep them in the
729 // partition that we set up in the MemoryInstructionDependences loop.
730 if (Partitions.mergeToAvoidDuplicatedLoads()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000731 LLVM_DEBUG(dbgs() << "\nPartitions merged to ensure unique loads:\n"
732 << Partitions);
Adam Nemet938d3d62015-05-14 12:05:18 +0000733 if (Partitions.getSize() < 2)
Adam Nemetf744ad72016-09-30 04:56:25 +0000734 return fail("CantIsolateUnsafeDeps",
735 "cannot isolate unsafe dependencies");
Adam Nemet938d3d62015-05-14 12:05:18 +0000736 }
737
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000738 // Don't distribute the loop if we need too many SCEV run-time checks.
Xinliang David Li94734ee2016-07-01 05:59:55 +0000739 const SCEVUnionPredicate &Pred = LAI->getPSE().getUnionPredicate();
Adam Nemetd2fa4142016-04-27 05:28:18 +0000740 if (Pred.getComplexity() > (IsForced.getValueOr(false)
741 ? PragmaDistributeSCEVCheckThreshold
Adam Nemet7f38e112016-04-28 23:08:27 +0000742 : DistributeSCEVCheckThreshold))
Adam Nemetf744ad72016-09-30 04:56:25 +0000743 return fail("TooManySCEVRuntimeChecks",
744 "too many SCEV run-time checks needed.\n");
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000745
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000746 LLVM_DEBUG(dbgs() << "\nDistributing loop: " << *L << "\n");
Adam Nemet938d3d62015-05-14 12:05:18 +0000747 // We're done forming the partitions set up the reverse mapping from
748 // instructions to partitions.
749 Partitions.setupPartitionIdOnInstructions();
750
751 // To keep things simple have an empty preheader before we version or clone
752 // the loop. (Also split if this has no predecessor, i.e. entry, because we
753 // rely on PH having a predecessor.)
754 if (!PH->getSinglePredecessor() || &*PH->begin() != PH->getTerminator())
755 SplitBlock(PH, PH->getTerminator(), DT, LI);
756
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000757 // If we need run-time checks, version the loop now.
Adam Nemeteff76642016-05-13 04:20:31 +0000758 auto PtrToPartition = Partitions.computePartitionSetForPointers(*LAI);
759 const auto *RtPtrChecking = LAI->getRuntimePointerChecking();
Adam Nemet15840392015-08-07 22:44:15 +0000760 const auto &AllChecks = RtPtrChecking->getChecks();
Adam Nemetc75ad692015-07-30 03:29:16 +0000761 auto Checks = includeOnlyCrossPartitionChecks(AllChecks, PtrToPartition,
762 RtPtrChecking);
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000763
764 if (!Pred.isAlwaysTrue() || !Checks.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000765 LLVM_DEBUG(dbgs() << "\nPointers:\n");
766 LLVM_DEBUG(LAI->getRuntimePointerChecking()->printChecks(dbgs(), Checks));
Adam Nemeteff76642016-05-13 04:20:31 +0000767 LoopVersioning LVer(*LAI, L, LI, DT, SE, false);
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000768 LVer.setAliasChecks(std::move(Checks));
Xinliang David Li94734ee2016-07-01 05:59:55 +0000769 LVer.setSCEVChecks(LAI->getPSE().getUnionPredicate());
Adam Nemete4813402015-08-20 17:22:29 +0000770 LVer.versionLoop(DefsUsedOutside);
Adam Nemet5eccf072016-03-17 20:32:32 +0000771 LVer.annotateLoopWithNoAlias();
Adam Nemet938d3d62015-05-14 12:05:18 +0000772 }
773
774 // Create identical copies of the original loop for each partition and hook
775 // them up sequentially.
Justin Bogner843fb202015-12-15 19:40:57 +0000776 Partitions.cloneLoops();
Adam Nemet938d3d62015-05-14 12:05:18 +0000777
778 // Now, we remove the instruction from each loop that don't belong to that
779 // partition.
780 Partitions.removeUnusedInsts();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000781 LLVM_DEBUG(dbgs() << "\nAfter removing unused Instrs:\n");
782 LLVM_DEBUG(Partitions.printBlocks());
Adam Nemet938d3d62015-05-14 12:05:18 +0000783
784 if (LDistVerify) {
Michael Zolotukhine0b2d972016-08-31 19:26:19 +0000785 LI->verify(*DT);
David Green7c35de12018-02-28 11:00:08 +0000786 assert(DT->verify(DominatorTree::VerificationLevel::Fast));
Adam Nemet938d3d62015-05-14 12:05:18 +0000787 }
788
789 ++NumLoopsDistributed;
Adam Nemet88ec4912016-04-29 07:10:46 +0000790 // Report the success.
Vivek Pandya95906582017-10-11 17:12:59 +0000791 ORE->emit([&]() {
792 return OptimizationRemark(LDIST_NAME, "Distribute", L->getStartLoc(),
793 L->getHeader())
794 << "distributed loop";
795 });
Adam Nemet938d3d62015-05-14 12:05:18 +0000796 return true;
797 }
798
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000799 /// Provide diagnostics then \return with false.
Adam Nemetf744ad72016-09-30 04:56:25 +0000800 bool fail(StringRef RemarkName, StringRef Message) {
Adam Nemet0ba164b2016-04-28 23:08:32 +0000801 LLVMContext &Ctx = F->getContext();
802 bool Forced = isForced().getValueOr(false);
803
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000804 LLVM_DEBUG(dbgs() << "Skipping; " << Message << "\n");
Adam Nemet0ba164b2016-04-28 23:08:32 +0000805
806 // With Rpass-missed report that distribution failed.
Vivek Pandya95906582017-10-11 17:12:59 +0000807 ORE->emit([&]() {
808 return OptimizationRemarkMissed(LDIST_NAME, "NotDistributed",
809 L->getStartLoc(), L->getHeader())
810 << "loop not distributed: use -Rpass-analysis=loop-distribute for "
811 "more "
812 "info";
813 });
Adam Nemet0ba164b2016-04-28 23:08:32 +0000814
815 // With Rpass-analysis report why. This is on by default if distribution
816 // was requested explicitly.
Adam Nemetf744ad72016-09-30 04:56:25 +0000817 ORE->emit(OptimizationRemarkAnalysis(
818 Forced ? OptimizationRemarkAnalysis::AlwaysPrint : LDIST_NAME,
819 RemarkName, L->getStartLoc(), L->getHeader())
820 << "loop not distributed: " << Message);
Adam Nemet0ba164b2016-04-28 23:08:32 +0000821
822 // Also issue a warning if distribution was requested explicitly but it
823 // failed.
824 if (Forced)
825 Ctx.diagnose(DiagnosticInfoOptimizationFailure(
Adam Nemet74730d92016-07-14 22:33:46 +0000826 *F, L->getStartLoc(), "loop not distributed: failed "
Adam Nemet0ba164b2016-04-28 23:08:32 +0000827 "explicitly specified loop distribution"));
828
Adam Nemet7f38e112016-04-28 23:08:27 +0000829 return false;
830 }
831
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000832 /// Return if distribution forced to be enabled/disabled for the loop.
Adam Nemetd2fa4142016-04-27 05:28:18 +0000833 ///
834 /// If the optional has a value, it indicates whether distribution was forced
835 /// to be enabled (true) or disabled (false). If the optional has no value
836 /// distribution was not forced either way.
837 const Optional<bool> &isForced() const { return IsForced; }
838
Adam Nemet61399ac2016-04-27 00:31:03 +0000839private:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000840 /// Filter out checks between pointers from the same partition.
Adam Nemet61399ac2016-04-27 00:31:03 +0000841 ///
842 /// \p PtrToPartition contains the partition number for pointers. Partition
843 /// number -1 means that the pointer is used in multiple partitions. In this
844 /// case we can't safely omit the check.
845 SmallVector<RuntimePointerChecking::PointerCheck, 4>
846 includeOnlyCrossPartitionChecks(
847 const SmallVectorImpl<RuntimePointerChecking::PointerCheck> &AllChecks,
848 const SmallVectorImpl<int> &PtrToPartition,
849 const RuntimePointerChecking *RtPtrChecking) {
850 SmallVector<RuntimePointerChecking::PointerCheck, 4> Checks;
851
Sanjoy Das90208722017-02-21 00:38:44 +0000852 copy_if(AllChecks, std::back_inserter(Checks),
853 [&](const RuntimePointerChecking::PointerCheck &Check) {
854 for (unsigned PtrIdx1 : Check.first->Members)
855 for (unsigned PtrIdx2 : Check.second->Members)
856 // Only include this check if there is a pair of pointers
857 // that require checking and the pointers fall into
858 // separate partitions.
859 //
860 // (Note that we already know at this point that the two
861 // pointer groups need checking but it doesn't follow
862 // that each pair of pointers within the two groups need
863 // checking as well.
864 //
865 // In other words we don't want to include a check just
866 // because there is a pair of pointers between the two
867 // pointer groups that require checks and a different
868 // pair whose pointers fall into different partitions.)
869 if (RtPtrChecking->needsChecking(PtrIdx1, PtrIdx2) &&
870 !RuntimePointerChecking::arePointersInSamePartition(
871 PtrToPartition, PtrIdx1, PtrIdx2))
872 return true;
873 return false;
874 });
Adam Nemet61399ac2016-04-27 00:31:03 +0000875
876 return Checks;
877 }
878
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000879 /// Check whether the loop metadata is forcing distribution to be
Adam Nemetd2fa4142016-04-27 05:28:18 +0000880 /// enabled/disabled.
881 void setForced() {
882 Optional<const MDOperand *> Value =
883 findStringMetadataForLoop(L, "llvm.loop.distribute.enable");
884 if (!Value)
885 return;
886
887 const MDOperand *Op = *Value;
888 assert(Op && mdconst::hasa<ConstantInt>(*Op) && "invalid metadata");
889 IsForced = mdconst::extract<ConstantInt>(*Op)->getZExtValue();
890 }
891
Adam Nemet61399ac2016-04-27 00:31:03 +0000892 Loop *L;
Adam Nemet4338d672016-04-29 07:10:39 +0000893 Function *F;
894
895 // Analyses used.
Adam Nemet938d3d62015-05-14 12:05:18 +0000896 LoopInfo *LI;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000897 const LoopAccessInfo *LAI = nullptr;
Adam Nemet938d3d62015-05-14 12:05:18 +0000898 DominatorTree *DT;
Silviu Baranga2910a4f2015-11-09 13:26:09 +0000899 ScalarEvolution *SE;
Adam Nemetaad81602016-07-15 17:23:20 +0000900 OptimizationRemarkEmitter *ORE;
Adam Nemetd2fa4142016-04-27 05:28:18 +0000901
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000902 /// Indicates whether distribution is forced to be enabled/disabled for
Adam Nemetd2fa4142016-04-27 05:28:18 +0000903 /// the loop.
904 ///
905 /// If the optional has a value, it indicates whether distribution was forced
906 /// to be enabled (true) or disabled (false). If the optional has no value
907 /// distribution was not forced either way.
908 Optional<bool> IsForced;
Adam Nemet938d3d62015-05-14 12:05:18 +0000909};
Adam Nemet61399ac2016-04-27 00:31:03 +0000910
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000911} // end anonymous namespace
912
Adam Nemetb2593f72016-07-18 16:29:27 +0000913/// Shared implementation between new and old PMs.
914static bool runImpl(Function &F, LoopInfo *LI, DominatorTree *DT,
915 ScalarEvolution *SE, OptimizationRemarkEmitter *ORE,
Adam Nemet32e6a342016-12-21 04:07:40 +0000916 std::function<const LoopAccessInfo &(Loop &)> &GetLAA) {
Adam Nemetb2593f72016-07-18 16:29:27 +0000917 // Build up a worklist of inner-loops to vectorize. This is necessary as the
918 // act of distributing a loop creates new loops and can invalidate iterators
919 // across the loops.
920 SmallVector<Loop *, 8> Worklist;
921
922 for (Loop *TopLevelLoop : *LI)
923 for (Loop *L : depth_first(TopLevelLoop))
924 // We only handle inner-most loops.
925 if (L->empty())
926 Worklist.push_back(L);
927
928 // Now walk the identified inner loops.
929 bool Changed = false;
930 for (Loop *L : Worklist) {
931 LoopDistributeForLoop LDL(L, &F, LI, DT, SE, ORE);
932
933 // If distribution was forced for the specific loop to be
934 // enabled/disabled, follow that. Otherwise use the global flag.
Adam Nemet32e6a342016-12-21 04:07:40 +0000935 if (LDL.isForced().getValueOr(EnableLoopDistribute))
Adam Nemetb2593f72016-07-18 16:29:27 +0000936 Changed |= LDL.processLoop(GetLAA);
937 }
938
939 // Process each loop nest in the function.
940 return Changed;
941}
942
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000943namespace {
944
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000945/// The pass class.
Adam Nemetb2593f72016-07-18 16:29:27 +0000946class LoopDistributeLegacy : public FunctionPass {
Adam Nemet61399ac2016-04-27 00:31:03 +0000947public:
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000948 static char ID;
949
Adam Nemet32e6a342016-12-21 04:07:40 +0000950 LoopDistributeLegacy() : FunctionPass(ID) {
Adam Nemetd2fa4142016-04-27 05:28:18 +0000951 // The default is set by the caller.
Adam Nemetb2593f72016-07-18 16:29:27 +0000952 initializeLoopDistributeLegacyPass(*PassRegistry::getPassRegistry());
Adam Nemet61399ac2016-04-27 00:31:03 +0000953 }
954
955 bool runOnFunction(Function &F) override {
Andrew Kaylor50271f72016-05-03 22:32:30 +0000956 if (skipFunction(F))
957 return false;
958
Adam Nemet61399ac2016-04-27 00:31:03 +0000959 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000960 auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
Adam Nemet61399ac2016-04-27 00:31:03 +0000961 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
962 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Adam Nemet79ac42a2016-07-18 16:29:21 +0000963 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
Adam Nemetb2593f72016-07-18 16:29:27 +0000964 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
965 [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
Adam Nemet61399ac2016-04-27 00:31:03 +0000966
Adam Nemet32e6a342016-12-21 04:07:40 +0000967 return runImpl(F, LI, DT, SE, ORE, GetLAA);
Adam Nemet61399ac2016-04-27 00:31:03 +0000968 }
969
970 void getAnalysisUsage(AnalysisUsage &AU) const override {
971 AU.addRequired<ScalarEvolutionWrapperPass>();
972 AU.addRequired<LoopInfoWrapperPass>();
973 AU.addPreserved<LoopInfoWrapperPass>();
Xinliang David Li7853c1d2016-07-08 20:55:26 +0000974 AU.addRequired<LoopAccessLegacyAnalysis>();
Adam Nemet61399ac2016-04-27 00:31:03 +0000975 AU.addRequired<DominatorTreeWrapperPass>();
976 AU.addPreserved<DominatorTreeWrapperPass>();
Adam Nemet79ac42a2016-07-18 16:29:21 +0000977 AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
Eli Friedman66fdba82016-09-16 18:01:48 +0000978 AU.addPreserved<GlobalsAAWrapperPass>();
Adam Nemet61399ac2016-04-27 00:31:03 +0000979 }
Adam Nemet61399ac2016-04-27 00:31:03 +0000980};
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +0000981
982} // end anonymous namespace
Adam Nemet938d3d62015-05-14 12:05:18 +0000983
Adam Nemetb2593f72016-07-18 16:29:27 +0000984PreservedAnalyses LoopDistributePass::run(Function &F,
985 FunctionAnalysisManager &AM) {
Adam Nemetb2593f72016-07-18 16:29:27 +0000986 auto &LI = AM.getResult<LoopAnalysis>(F);
987 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
988 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
989 auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
990
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000991 // We don't directly need these analyses but they're required for loop
992 // analyses so provide them below.
993 auto &AA = AM.getResult<AAManager>(F);
994 auto &AC = AM.getResult<AssumptionAnalysis>(F);
995 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
996 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
997
Adam Nemetb2593f72016-07-18 16:29:27 +0000998 auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
999 std::function<const LoopAccessInfo &(Loop &)> GetLAA =
1000 [&](Loop &L) -> const LoopAccessInfo & {
Alina Sbirleaff8b8ae2017-11-21 15:45:46 +00001001 LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI, nullptr};
Chandler Carruth410eaeb2017-01-11 06:23:21 +00001002 return LAM.getResult<LoopAccessAnalysis>(L, AR);
Adam Nemetb2593f72016-07-18 16:29:27 +00001003 };
1004
Adam Nemet32e6a342016-12-21 04:07:40 +00001005 bool Changed = runImpl(F, &LI, &DT, &SE, &ORE, GetLAA);
Adam Nemetb2593f72016-07-18 16:29:27 +00001006 if (!Changed)
1007 return PreservedAnalyses::all();
1008 PreservedAnalyses PA;
1009 PA.preserve<LoopAnalysis>();
1010 PA.preserve<DominatorTreeAnalysis>();
Davide Italiano11a871b2016-11-08 19:52:32 +00001011 PA.preserve<GlobalsAA>();
Adam Nemetb2593f72016-07-18 16:29:27 +00001012 return PA;
1013}
1014
1015char LoopDistributeLegacy::ID;
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001016
Michael Zolotukhin5cda89a2016-10-05 00:44:52 +00001017static const char ldist_name[] = "Loop Distribution";
Adam Nemet938d3d62015-05-14 12:05:18 +00001018
Adam Nemetb2593f72016-07-18 16:29:27 +00001019INITIALIZE_PASS_BEGIN(LoopDistributeLegacy, LDIST_NAME, ldist_name, false,
1020 false)
Adam Nemet938d3d62015-05-14 12:05:18 +00001021INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Xinliang David Li7853c1d2016-07-08 20:55:26 +00001022INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
Adam Nemet938d3d62015-05-14 12:05:18 +00001023INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Silviu Baranga2910a4f2015-11-09 13:26:09 +00001024INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Adam Nemet79ac42a2016-07-18 16:29:21 +00001025INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
Adam Nemetb2593f72016-07-18 16:29:27 +00001026INITIALIZE_PASS_END(LoopDistributeLegacy, LDIST_NAME, ldist_name, false, false)
Adam Nemet938d3d62015-05-14 12:05:18 +00001027
Eugene Zelenkodd40f5e2017-10-16 21:34:24 +00001028FunctionPass *llvm::createLoopDistributePass() { return new LoopDistributeLegacy(); }