LoopDistribute.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. //===- 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. #include "llvm/ADT/DepthFirstIterator.h"
  25. #include "llvm/ADT/EquivalenceClasses.h"
  26. #include "llvm/ADT/STLExtras.h"
  27. #include "llvm/ADT/Statistic.h"
  28. #include "llvm/Analysis/LoopAccessAnalysis.h"
  29. #include "llvm/Analysis/LoopInfo.h"
  30. #include "llvm/IR/Dominators.h"
  31. #include "llvm/Pass.h"
  32. #include "llvm/Support/CommandLine.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  35. #include "llvm/Transforms/Utils/Cloning.h"
  36. #include "llvm/Transforms/Utils/LoopVersioning.h"
  37. #include <list>
  38. #define LDIST_NAME "loop-distribute"
  39. #define DEBUG_TYPE LDIST_NAME
  40. using namespace llvm;
  41. static cl::opt<bool>
  42. LDistVerify("loop-distribute-verify", cl::Hidden,
  43. cl::desc("Turn on DominatorTree and LoopInfo verification "
  44. "after Loop Distribution"),
  45. cl::init(false));
  46. static cl::opt<bool> DistributeNonIfConvertible(
  47. "loop-distribute-non-if-convertible", cl::Hidden,
  48. cl::desc("Whether to distribute into a loop that may not be "
  49. "if-convertible by the loop vectorizer"),
  50. cl::init(false));
  51. STATISTIC(NumLoopsDistributed, "Number of loops distributed");
  52. namespace {
  53. /// \brief Maintains the set of instructions of the loop for a partition before
  54. /// cloning. After cloning, it hosts the new loop.
  55. class InstPartition {
  56. typedef SmallPtrSet<Instruction *, 8> InstructionSet;
  57. public:
  58. InstPartition(Instruction *I, Loop *L, bool DepCycle = false)
  59. : DepCycle(DepCycle), OrigLoop(L), ClonedLoop(nullptr) {
  60. Set.insert(I);
  61. }
  62. /// \brief Returns whether this partition contains a dependence cycle.
  63. bool hasDepCycle() const { return DepCycle; }
  64. /// \brief Adds an instruction to this partition.
  65. void add(Instruction *I) { Set.insert(I); }
  66. /// \brief Collection accessors.
  67. InstructionSet::iterator begin() { return Set.begin(); }
  68. InstructionSet::iterator end() { return Set.end(); }
  69. InstructionSet::const_iterator begin() const { return Set.begin(); }
  70. InstructionSet::const_iterator end() const { return Set.end(); }
  71. bool empty() const { return Set.empty(); }
  72. /// \brief Moves this partition into \p Other. This partition becomes empty
  73. /// after this.
  74. void moveTo(InstPartition &Other) {
  75. Other.Set.insert(Set.begin(), Set.end());
  76. Set.clear();
  77. Other.DepCycle |= DepCycle;
  78. }
  79. /// \brief Populates the partition with a transitive closure of all the
  80. /// instructions that the seeded instructions dependent on.
  81. void populateUsedSet() {
  82. // FIXME: We currently don't use control-dependence but simply include all
  83. // blocks (possibly empty at the end) and let simplifycfg mostly clean this
  84. // up.
  85. for (auto *B : OrigLoop->getBlocks())
  86. Set.insert(B->getTerminator());
  87. // Follow the use-def chains to form a transitive closure of all the
  88. // instructions that the originally seeded instructions depend on.
  89. SmallVector<Instruction *, 8> Worklist(Set.begin(), Set.end());
  90. while (!Worklist.empty()) {
  91. Instruction *I = Worklist.pop_back_val();
  92. // Insert instructions from the loop that we depend on.
  93. for (Value *V : I->operand_values()) {
  94. auto *I = dyn_cast<Instruction>(V);
  95. if (I && OrigLoop->contains(I->getParent()) && Set.insert(I).second)
  96. Worklist.push_back(I);
  97. }
  98. }
  99. }
  100. /// \brief Clones the original loop.
  101. ///
  102. /// Updates LoopInfo and DominatorTree using the information that block \p
  103. /// LoopDomBB dominates the loop.
  104. Loop *cloneLoopWithPreheader(BasicBlock *InsertBefore, BasicBlock *LoopDomBB,
  105. unsigned Index, LoopInfo *LI,
  106. DominatorTree *DT) {
  107. ClonedLoop = ::cloneLoopWithPreheader(InsertBefore, LoopDomBB, OrigLoop,
  108. VMap, Twine(".ldist") + Twine(Index),
  109. LI, DT, ClonedLoopBlocks);
  110. return ClonedLoop;
  111. }
  112. /// \brief The cloned loop. If this partition is mapped to the original loop,
  113. /// this is null.
  114. const Loop *getClonedLoop() const { return ClonedLoop; }
  115. /// \brief Returns the loop where this partition ends up after distribution.
  116. /// If this partition is mapped to the original loop then use the block from
  117. /// the loop.
  118. const Loop *getDistributedLoop() const {
  119. return ClonedLoop ? ClonedLoop : OrigLoop;
  120. }
  121. /// \brief The VMap that is populated by cloning and then used in
  122. /// remapinstruction to remap the cloned instructions.
  123. ValueToValueMapTy &getVMap() { return VMap; }
  124. /// \brief Remaps the cloned instructions using VMap.
  125. void remapInstructions() {
  126. remapInstructionsInBlocks(ClonedLoopBlocks, VMap);
  127. }
  128. /// \brief Based on the set of instructions selected for this partition,
  129. /// removes the unnecessary ones.
  130. void removeUnusedInsts() {
  131. SmallVector<Instruction *, 8> Unused;
  132. for (auto *Block : OrigLoop->getBlocks())
  133. for (auto &Inst : *Block)
  134. if (!Set.count(&Inst)) {
  135. Instruction *NewInst = &Inst;
  136. if (!VMap.empty())
  137. NewInst = cast<Instruction>(VMap[NewInst]);
  138. assert(!isa<BranchInst>(NewInst) &&
  139. "Branches are marked used early on");
  140. Unused.push_back(NewInst);
  141. }
  142. // Delete the instructions backwards, as it has a reduced likelihood of
  143. // having to update as many def-use and use-def chains.
  144. for (auto I = Unused.rbegin(), E = Unused.rend(); I != E; ++I) {
  145. auto *Inst = *I;
  146. if (!Inst->use_empty())
  147. Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
  148. Inst->eraseFromParent();
  149. }
  150. }
  151. void print() const {
  152. if (DepCycle)
  153. dbgs() << " (cycle)\n";
  154. for (auto *I : Set)
  155. // Prefix with the block name.
  156. dbgs() << " " << I->getParent()->getName() << ":" << *I << "\n";
  157. }
  158. void printBlocks() const {
  159. for (auto *BB : getDistributedLoop()->getBlocks())
  160. dbgs() << *BB;
  161. }
  162. private:
  163. /// \brief Instructions from OrigLoop selected for this partition.
  164. InstructionSet Set;
  165. /// \brief Whether this partition contains a dependence cycle.
  166. bool DepCycle;
  167. /// \brief The original loop.
  168. Loop *OrigLoop;
  169. /// \brief The cloned loop. If this partition is mapped to the original loop,
  170. /// this is null.
  171. Loop *ClonedLoop;
  172. /// \brief The blocks of ClonedLoop including the preheader. If this
  173. /// partition is mapped to the original loop, this is empty.
  174. SmallVector<BasicBlock *, 8> ClonedLoopBlocks;
  175. /// \brief These gets populated once the set of instructions have been
  176. /// finalized. If this partition is mapped to the original loop, these are not
  177. /// set.
  178. ValueToValueMapTy VMap;
  179. };
  180. /// \brief Holds the set of Partitions. It populates them, merges them and then
  181. /// clones the loops.
  182. class InstPartitionContainer {
  183. typedef DenseMap<Instruction *, int> InstToPartitionIdT;
  184. public:
  185. InstPartitionContainer(Loop *L, LoopInfo *LI, DominatorTree *DT)
  186. : L(L), LI(LI), DT(DT) {}
  187. /// \brief Returns the number of partitions.
  188. unsigned getSize() const { return PartitionContainer.size(); }
  189. /// \brief Adds \p Inst into the current partition if that is marked to
  190. /// contain cycles. Otherwise start a new partition for it.
  191. void addToCyclicPartition(Instruction *Inst) {
  192. // If the current partition is non-cyclic. Start a new one.
  193. if (PartitionContainer.empty() || !PartitionContainer.back().hasDepCycle())
  194. PartitionContainer.emplace_back(Inst, L, /*DepCycle=*/true);
  195. else
  196. PartitionContainer.back().add(Inst);
  197. }
  198. /// \brief Adds \p Inst into a partition that is not marked to contain
  199. /// dependence cycles.
  200. ///
  201. // Initially we isolate memory instructions into as many partitions as
  202. // possible, then later we may merge them back together.
  203. void addToNewNonCyclicPartition(Instruction *Inst) {
  204. PartitionContainer.emplace_back(Inst, L);
  205. }
  206. /// \brief Merges adjacent non-cyclic partitions.
  207. ///
  208. /// The idea is that we currently only want to isolate the non-vectorizable
  209. /// partition. We could later allow more distribution among these partition
  210. /// too.
  211. void mergeAdjacentNonCyclic() {
  212. mergeAdjacentPartitionsIf(
  213. [](const InstPartition *P) { return !P->hasDepCycle(); });
  214. }
  215. /// \brief If a partition contains only conditional stores, we won't vectorize
  216. /// it. Try to merge it with a previous cyclic partition.
  217. void mergeNonIfConvertible() {
  218. mergeAdjacentPartitionsIf([&](const InstPartition *Partition) {
  219. if (Partition->hasDepCycle())
  220. return true;
  221. // Now, check if all stores are conditional in this partition.
  222. bool seenStore = false;
  223. for (auto *Inst : *Partition)
  224. if (isa<StoreInst>(Inst)) {
  225. seenStore = true;
  226. if (!LoopAccessInfo::blockNeedsPredication(Inst->getParent(), L, DT))
  227. return false;
  228. }
  229. return seenStore;
  230. });
  231. }
  232. /// \brief Merges the partitions according to various heuristics.
  233. void mergeBeforePopulating() {
  234. mergeAdjacentNonCyclic();
  235. if (!DistributeNonIfConvertible)
  236. mergeNonIfConvertible();
  237. }
  238. /// \brief Merges partitions in order to ensure that no loads are duplicated.
  239. ///
  240. /// We can't duplicate loads because that could potentially reorder them.
  241. /// LoopAccessAnalysis provides dependency information with the context that
  242. /// the order of memory operation is preserved.
  243. ///
  244. /// Return if any partitions were merged.
  245. bool mergeToAvoidDuplicatedLoads() {
  246. typedef DenseMap<Instruction *, InstPartition *> LoadToPartitionT;
  247. typedef EquivalenceClasses<InstPartition *> ToBeMergedT;
  248. LoadToPartitionT LoadToPartition;
  249. ToBeMergedT ToBeMerged;
  250. // Step through the partitions and create equivalence between partitions
  251. // that contain the same load. Also put partitions in between them in the
  252. // same equivalence class to avoid reordering of memory operations.
  253. for (PartitionContainerT::iterator I = PartitionContainer.begin(),
  254. E = PartitionContainer.end();
  255. I != E; ++I) {
  256. auto *PartI = &*I;
  257. // If a load occurs in two partitions PartI and PartJ, merge all
  258. // partitions (PartI, PartJ] into PartI.
  259. for (Instruction *Inst : *PartI)
  260. if (isa<LoadInst>(Inst)) {
  261. bool NewElt;
  262. LoadToPartitionT::iterator LoadToPart;
  263. std::tie(LoadToPart, NewElt) =
  264. LoadToPartition.insert(std::make_pair(Inst, PartI));
  265. if (!NewElt) {
  266. DEBUG(dbgs() << "Merging partitions due to this load in multiple "
  267. << "partitions: " << PartI << ", "
  268. << LoadToPart->second << "\n" << *Inst << "\n");
  269. auto PartJ = I;
  270. do {
  271. --PartJ;
  272. ToBeMerged.unionSets(PartI, &*PartJ);
  273. } while (&*PartJ != LoadToPart->second);
  274. }
  275. }
  276. }
  277. if (ToBeMerged.empty())
  278. return false;
  279. // Merge the member of an equivalence class into its class leader. This
  280. // makes the members empty.
  281. for (ToBeMergedT::iterator I = ToBeMerged.begin(), E = ToBeMerged.end();
  282. I != E; ++I) {
  283. if (!I->isLeader())
  284. continue;
  285. auto PartI = I->getData();
  286. for (auto PartJ : make_range(std::next(ToBeMerged.member_begin(I)),
  287. ToBeMerged.member_end())) {
  288. PartJ->moveTo(*PartI);
  289. }
  290. }
  291. // Remove the empty partitions.
  292. PartitionContainer.remove_if(
  293. [](const InstPartition &P) { return P.empty(); });
  294. return true;
  295. }
  296. /// \brief Sets up the mapping between instructions to partitions. If the
  297. /// instruction is duplicated across multiple partitions, set the entry to -1.
  298. void setupPartitionIdOnInstructions() {
  299. int PartitionID = 0;
  300. for (const auto &Partition : PartitionContainer) {
  301. for (Instruction *Inst : Partition) {
  302. bool NewElt;
  303. InstToPartitionIdT::iterator Iter;
  304. std::tie(Iter, NewElt) =
  305. InstToPartitionId.insert(std::make_pair(Inst, PartitionID));
  306. if (!NewElt)
  307. Iter->second = -1;
  308. }
  309. ++PartitionID;
  310. }
  311. }
  312. /// \brief Populates the partition with everything that the seeding
  313. /// instructions require.
  314. void populateUsedSet() {
  315. for (auto &P : PartitionContainer)
  316. P.populateUsedSet();
  317. }
  318. /// \brief This performs the main chunk of the work of cloning the loops for
  319. /// the partitions.
  320. void cloneLoops(Pass *P) {
  321. BasicBlock *OrigPH = L->getLoopPreheader();
  322. // At this point the predecessor of the preheader is either the memcheck
  323. // block or the top part of the original preheader.
  324. BasicBlock *Pred = OrigPH->getSinglePredecessor();
  325. assert(Pred && "Preheader does not have a single predecessor");
  326. BasicBlock *ExitBlock = L->getExitBlock();
  327. assert(ExitBlock && "No single exit block");
  328. Loop *NewLoop;
  329. assert(!PartitionContainer.empty() && "at least two partitions expected");
  330. // We're cloning the preheader along with the loop so we already made sure
  331. // it was empty.
  332. assert(&*OrigPH->begin() == OrigPH->getTerminator() &&
  333. "preheader not empty");
  334. // Create a loop for each partition except the last. Clone the original
  335. // loop before PH along with adding a preheader for the cloned loop. Then
  336. // update PH to point to the newly added preheader.
  337. BasicBlock *TopPH = OrigPH;
  338. unsigned Index = getSize() - 1;
  339. for (auto I = std::next(PartitionContainer.rbegin()),
  340. E = PartitionContainer.rend();
  341. I != E; ++I, --Index, TopPH = NewLoop->getLoopPreheader()) {
  342. auto *Part = &*I;
  343. NewLoop = Part->cloneLoopWithPreheader(TopPH, Pred, Index, LI, DT);
  344. Part->getVMap()[ExitBlock] = TopPH;
  345. Part->remapInstructions();
  346. }
  347. Pred->getTerminator()->replaceUsesOfWith(OrigPH, TopPH);
  348. // Now go in forward order and update the immediate dominator for the
  349. // preheaders with the exiting block of the previous loop. Dominance
  350. // within the loop is updated in cloneLoopWithPreheader.
  351. for (auto Curr = PartitionContainer.cbegin(),
  352. Next = std::next(PartitionContainer.cbegin()),
  353. E = PartitionContainer.cend();
  354. Next != E; ++Curr, ++Next)
  355. DT->changeImmediateDominator(
  356. Next->getDistributedLoop()->getLoopPreheader(),
  357. Curr->getDistributedLoop()->getExitingBlock());
  358. }
  359. /// \brief Removes the dead instructions from the cloned loops.
  360. void removeUnusedInsts() {
  361. for (auto &Partition : PartitionContainer)
  362. Partition.removeUnusedInsts();
  363. }
  364. /// \brief For each memory pointer, it computes the partitionId the pointer is
  365. /// used in.
  366. ///
  367. /// This returns an array of int where the I-th entry corresponds to I-th
  368. /// entry in LAI.getRuntimePointerCheck(). If the pointer is used in multiple
  369. /// partitions its entry is set to -1.
  370. SmallVector<int, 8>
  371. computePartitionSetForPointers(const LoopAccessInfo &LAI) {
  372. const RuntimePointerChecking *RtPtrCheck = LAI.getRuntimePointerChecking();
  373. unsigned N = RtPtrCheck->Pointers.size();
  374. SmallVector<int, 8> PtrToPartitions(N);
  375. for (unsigned I = 0; I < N; ++I) {
  376. Value *Ptr = RtPtrCheck->Pointers[I].PointerValue;
  377. auto Instructions =
  378. LAI.getInstructionsForAccess(Ptr, RtPtrCheck->Pointers[I].IsWritePtr);
  379. int &Partition = PtrToPartitions[I];
  380. // First set it to uninitialized.
  381. Partition = -2;
  382. for (Instruction *Inst : Instructions) {
  383. // Note that this could be -1 if Inst is duplicated across multiple
  384. // partitions.
  385. int ThisPartition = this->InstToPartitionId[Inst];
  386. if (Partition == -2)
  387. Partition = ThisPartition;
  388. // -1 means belonging to multiple partitions.
  389. else if (Partition == -1)
  390. break;
  391. else if (Partition != (int)ThisPartition)
  392. Partition = -1;
  393. }
  394. assert(Partition != -2 && "Pointer not belonging to any partition");
  395. }
  396. return PtrToPartitions;
  397. }
  398. void print(raw_ostream &OS) const {
  399. unsigned Index = 0;
  400. for (const auto &P : PartitionContainer) {
  401. OS << "Partition " << Index++ << " (" << &P << "):\n";
  402. P.print();
  403. }
  404. }
  405. void dump() const { print(dbgs()); }
  406. #ifndef NDEBUG
  407. friend raw_ostream &operator<<(raw_ostream &OS,
  408. const InstPartitionContainer &Partitions) {
  409. Partitions.print(OS);
  410. return OS;
  411. }
  412. #endif
  413. void printBlocks() const {
  414. unsigned Index = 0;
  415. for (const auto &P : PartitionContainer) {
  416. dbgs() << "\nPartition " << Index++ << " (" << &P << "):\n";
  417. P.printBlocks();
  418. }
  419. }
  420. private:
  421. typedef std::list<InstPartition> PartitionContainerT;
  422. /// \brief List of partitions.
  423. PartitionContainerT PartitionContainer;
  424. /// \brief Mapping from Instruction to partition Id. If the instruction
  425. /// belongs to multiple partitions the entry contains -1.
  426. InstToPartitionIdT InstToPartitionId;
  427. Loop *L;
  428. LoopInfo *LI;
  429. DominatorTree *DT;
  430. /// \brief The control structure to merge adjacent partitions if both satisfy
  431. /// the \p Predicate.
  432. template <class UnaryPredicate>
  433. void mergeAdjacentPartitionsIf(UnaryPredicate Predicate) {
  434. InstPartition *PrevMatch = nullptr;
  435. for (auto I = PartitionContainer.begin(); I != PartitionContainer.end();) {
  436. auto DoesMatch = Predicate(&*I);
  437. if (PrevMatch == nullptr && DoesMatch) {
  438. PrevMatch = &*I;
  439. ++I;
  440. } else if (PrevMatch != nullptr && DoesMatch) {
  441. I->moveTo(*PrevMatch);
  442. I = PartitionContainer.erase(I);
  443. } else {
  444. PrevMatch = nullptr;
  445. ++I;
  446. }
  447. }
  448. }
  449. };
  450. /// \brief For each memory instruction, this class maintains difference of the
  451. /// number of unsafe dependences that start out from this instruction minus
  452. /// those that end here.
  453. ///
  454. /// By traversing the memory instructions in program order and accumulating this
  455. /// number, we know whether any unsafe dependence crosses over a program point.
  456. class MemoryInstructionDependences {
  457. typedef MemoryDepChecker::Dependence Dependence;
  458. public:
  459. struct Entry {
  460. Instruction *Inst;
  461. unsigned NumUnsafeDependencesStartOrEnd;
  462. Entry(Instruction *Inst) : Inst(Inst), NumUnsafeDependencesStartOrEnd(0) {}
  463. };
  464. typedef SmallVector<Entry, 8> AccessesType;
  465. AccessesType::const_iterator begin() const { return Accesses.begin(); }
  466. AccessesType::const_iterator end() const { return Accesses.end(); }
  467. MemoryInstructionDependences(
  468. const SmallVectorImpl<Instruction *> &Instructions,
  469. const SmallVectorImpl<Dependence> &InterestingDependences) {
  470. Accesses.append(Instructions.begin(), Instructions.end());
  471. DEBUG(dbgs() << "Backward dependences:\n");
  472. for (auto &Dep : InterestingDependences)
  473. if (Dep.isPossiblyBackward()) {
  474. // Note that the designations source and destination follow the program
  475. // order, i.e. source is always first. (The direction is given by the
  476. // DepType.)
  477. ++Accesses[Dep.Source].NumUnsafeDependencesStartOrEnd;
  478. --Accesses[Dep.Destination].NumUnsafeDependencesStartOrEnd;
  479. DEBUG(Dep.print(dbgs(), 2, Instructions));
  480. }
  481. }
  482. private:
  483. AccessesType Accesses;
  484. };
  485. /// \brief Returns the instructions that use values defined in the loop.
  486. static SmallVector<Instruction *, 8> findDefsUsedOutsideOfLoop(Loop *L) {
  487. SmallVector<Instruction *, 8> UsedOutside;
  488. for (auto *Block : L->getBlocks())
  489. // FIXME: I believe that this could use copy_if if the Inst reference could
  490. // be adapted into a pointer.
  491. for (auto &Inst : *Block) {
  492. auto Users = Inst.users();
  493. if (std::any_of(Users.begin(), Users.end(), [&](User *U) {
  494. auto *Use = cast<Instruction>(U);
  495. return !L->contains(Use->getParent());
  496. }))
  497. UsedOutside.push_back(&Inst);
  498. }
  499. return UsedOutside;
  500. }
  501. /// \brief The pass class.
  502. class LoopDistribute : public FunctionPass {
  503. public:
  504. LoopDistribute() : FunctionPass(ID) {
  505. initializeLoopDistributePass(*PassRegistry::getPassRegistry());
  506. }
  507. bool runOnFunction(Function &F) override {
  508. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  509. LAA = &getAnalysis<LoopAccessAnalysis>();
  510. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  511. // Build up a worklist of inner-loops to vectorize. This is necessary as the
  512. // act of distributing a loop creates new loops and can invalidate iterators
  513. // across the loops.
  514. SmallVector<Loop *, 8> Worklist;
  515. for (Loop *TopLevelLoop : *LI)
  516. for (Loop *L : depth_first(TopLevelLoop))
  517. // We only handle inner-most loops.
  518. if (L->empty())
  519. Worklist.push_back(L);
  520. // Now walk the identified inner loops.
  521. bool Changed = false;
  522. for (Loop *L : Worklist)
  523. Changed |= processLoop(L);
  524. // Process each loop nest in the function.
  525. return Changed;
  526. }
  527. void getAnalysisUsage(AnalysisUsage &AU) const override {
  528. AU.addRequired<LoopInfoWrapperPass>();
  529. AU.addPreserved<LoopInfoWrapperPass>();
  530. AU.addRequired<LoopAccessAnalysis>();
  531. AU.addRequired<DominatorTreeWrapperPass>();
  532. AU.addPreserved<DominatorTreeWrapperPass>();
  533. }
  534. static char ID;
  535. private:
  536. /// \brief Try to distribute an inner-most loop.
  537. bool processLoop(Loop *L) {
  538. assert(L->empty() && "Only process inner loops.");
  539. DEBUG(dbgs() << "\nLDist: In \"" << L->getHeader()->getParent()->getName()
  540. << "\" checking " << *L << "\n");
  541. BasicBlock *PH = L->getLoopPreheader();
  542. if (!PH) {
  543. DEBUG(dbgs() << "Skipping; no preheader");
  544. return false;
  545. }
  546. if (!L->getExitBlock()) {
  547. DEBUG(dbgs() << "Skipping; multiple exit blocks");
  548. return false;
  549. }
  550. // LAA will check that we only have a single exiting block.
  551. const LoopAccessInfo &LAI = LAA->getInfo(L, ValueToValueMap());
  552. // Currently, we only distribute to isolate the part of the loop with
  553. // dependence cycles to enable partial vectorization.
  554. if (LAI.canVectorizeMemory()) {
  555. DEBUG(dbgs() << "Skipping; memory operations are safe for vectorization");
  556. return false;
  557. }
  558. auto *InterestingDependences =
  559. LAI.getDepChecker().getInterestingDependences();
  560. if (!InterestingDependences || InterestingDependences->empty()) {
  561. DEBUG(dbgs() << "Skipping; No unsafe dependences to isolate");
  562. return false;
  563. }
  564. InstPartitionContainer Partitions(L, LI, DT);
  565. // First, go through each memory operation and assign them to consecutive
  566. // partitions (the order of partitions follows program order). Put those
  567. // with unsafe dependences into "cyclic" partition otherwise put each store
  568. // in its own "non-cyclic" partition (we'll merge these later).
  569. //
  570. // Note that a memory operation (e.g. Load2 below) at a program point that
  571. // has an unsafe dependence (Store3->Load1) spanning over it must be
  572. // included in the same cyclic partition as the dependent operations. This
  573. // is to preserve the original program order after distribution. E.g.:
  574. //
  575. // NumUnsafeDependencesStartOrEnd NumUnsafeDependencesActive
  576. // Load1 -. 1 0->1
  577. // Load2 | /Unsafe/ 0 1
  578. // Store3 -' -1 1->0
  579. // Load4 0 0
  580. //
  581. // NumUnsafeDependencesActive > 0 indicates this situation and in this case
  582. // we just keep assigning to the same cyclic partition until
  583. // NumUnsafeDependencesActive reaches 0.
  584. const MemoryDepChecker &DepChecker = LAI.getDepChecker();
  585. MemoryInstructionDependences MID(DepChecker.getMemoryInstructions(),
  586. *InterestingDependences);
  587. int NumUnsafeDependencesActive = 0;
  588. for (auto &InstDep : MID) {
  589. Instruction *I = InstDep.Inst;
  590. // We update NumUnsafeDependencesActive post-instruction, catch the
  591. // start of a dependence directly via NumUnsafeDependencesStartOrEnd.
  592. if (NumUnsafeDependencesActive ||
  593. InstDep.NumUnsafeDependencesStartOrEnd > 0)
  594. Partitions.addToCyclicPartition(I);
  595. else
  596. Partitions.addToNewNonCyclicPartition(I);
  597. NumUnsafeDependencesActive += InstDep.NumUnsafeDependencesStartOrEnd;
  598. assert(NumUnsafeDependencesActive >= 0 &&
  599. "Negative number of dependences active");
  600. }
  601. // Add partitions for values used outside. These partitions can be out of
  602. // order from the original program order. This is OK because if the
  603. // partition uses a load we will merge this partition with the original
  604. // partition of the load that we set up in the previous loop (see
  605. // mergeToAvoidDuplicatedLoads).
  606. auto DefsUsedOutside = findDefsUsedOutsideOfLoop(L);
  607. for (auto *Inst : DefsUsedOutside)
  608. Partitions.addToNewNonCyclicPartition(Inst);
  609. DEBUG(dbgs() << "Seeded partitions:\n" << Partitions);
  610. if (Partitions.getSize() < 2)
  611. return false;
  612. // Run the merge heuristics: Merge non-cyclic adjacent partitions since we
  613. // should be able to vectorize these together.
  614. Partitions.mergeBeforePopulating();
  615. DEBUG(dbgs() << "\nMerged partitions:\n" << Partitions);
  616. if (Partitions.getSize() < 2)
  617. return false;
  618. // Now, populate the partitions with non-memory operations.
  619. Partitions.populateUsedSet();
  620. DEBUG(dbgs() << "\nPopulated partitions:\n" << Partitions);
  621. // In order to preserve original lexical order for loads, keep them in the
  622. // partition that we set up in the MemoryInstructionDependences loop.
  623. if (Partitions.mergeToAvoidDuplicatedLoads()) {
  624. DEBUG(dbgs() << "\nPartitions merged to ensure unique loads:\n"
  625. << Partitions);
  626. if (Partitions.getSize() < 2)
  627. return false;
  628. }
  629. DEBUG(dbgs() << "\nDistributing loop: " << *L << "\n");
  630. // We're done forming the partitions set up the reverse mapping from
  631. // instructions to partitions.
  632. Partitions.setupPartitionIdOnInstructions();
  633. // To keep things simple have an empty preheader before we version or clone
  634. // the loop. (Also split if this has no predecessor, i.e. entry, because we
  635. // rely on PH having a predecessor.)
  636. if (!PH->getSinglePredecessor() || &*PH->begin() != PH->getTerminator())
  637. SplitBlock(PH, PH->getTerminator(), DT, LI);
  638. // If we need run-time checks to disambiguate pointers are run-time, version
  639. // the loop now.
  640. auto PtrToPartition = Partitions.computePartitionSetForPointers(LAI);
  641. LoopVersioning LVer(LAI, L, LI, DT, &PtrToPartition);
  642. if (LVer.needsRuntimeChecks()) {
  643. DEBUG(dbgs() << "\nPointers:\n");
  644. DEBUG(LAI.getRuntimePointerChecking()->print(dbgs(), 0, &PtrToPartition));
  645. LVer.versionLoop(this);
  646. LVer.addPHINodes(DefsUsedOutside);
  647. }
  648. // Create identical copies of the original loop for each partition and hook
  649. // them up sequentially.
  650. Partitions.cloneLoops(this);
  651. // Now, we remove the instruction from each loop that don't belong to that
  652. // partition.
  653. Partitions.removeUnusedInsts();
  654. DEBUG(dbgs() << "\nAfter removing unused Instrs:\n");
  655. DEBUG(Partitions.printBlocks());
  656. if (LDistVerify) {
  657. LI->verify();
  658. DT->verifyDomTree();
  659. }
  660. ++NumLoopsDistributed;
  661. return true;
  662. }
  663. // Analyses used.
  664. LoopInfo *LI;
  665. LoopAccessAnalysis *LAA;
  666. DominatorTree *DT;
  667. };
  668. } // anonymous namespace
  669. char LoopDistribute::ID;
  670. static const char ldist_name[] = "Loop Distribition";
  671. INITIALIZE_PASS_BEGIN(LoopDistribute, LDIST_NAME, ldist_name, false, false)
  672. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  673. INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
  674. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  675. INITIALIZE_PASS_END(LoopDistribute, LDIST_NAME, ldist_name, false, false)
  676. namespace llvm {
  677. FunctionPass *createLoopDistributePass() { return new LoopDistribute(); }
  678. }