Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Scalar/LoopDistribute.cpp
35266 views
//===- LoopDistribute.cpp - Loop Distribution Pass ------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the Loop Distribution Pass. Its main focus is to9// distribute loops that cannot be vectorized due to dependence cycles. It10// tries to isolate the offending dependences into a new loop allowing11// vectorization of the remaining parts.12//13// For dependence analysis, the pass uses the LoopVectorizer's14// LoopAccessAnalysis. Because this analysis presumes no change in the order of15// memory operations, special care is taken to preserve the lexical order of16// these operations.17//18// Similarly to the Vectorizer, the pass also supports loop versioning to19// run-time disambiguate potentially overlapping arrays.20//21//===----------------------------------------------------------------------===//2223#include "llvm/Transforms/Scalar/LoopDistribute.h"24#include "llvm/ADT/DenseMap.h"25#include "llvm/ADT/DepthFirstIterator.h"26#include "llvm/ADT/EquivalenceClasses.h"27#include "llvm/ADT/STLExtras.h"28#include "llvm/ADT/SetVector.h"29#include "llvm/ADT/SmallVector.h"30#include "llvm/ADT/Statistic.h"31#include "llvm/ADT/StringRef.h"32#include "llvm/ADT/Twine.h"33#include "llvm/ADT/iterator_range.h"34#include "llvm/Analysis/AssumptionCache.h"35#include "llvm/Analysis/GlobalsModRef.h"36#include "llvm/Analysis/LoopAccessAnalysis.h"37#include "llvm/Analysis/LoopAnalysisManager.h"38#include "llvm/Analysis/LoopInfo.h"39#include "llvm/Analysis/OptimizationRemarkEmitter.h"40#include "llvm/Analysis/ScalarEvolution.h"41#include "llvm/Analysis/TargetLibraryInfo.h"42#include "llvm/Analysis/TargetTransformInfo.h"43#include "llvm/IR/BasicBlock.h"44#include "llvm/IR/Constants.h"45#include "llvm/IR/DiagnosticInfo.h"46#include "llvm/IR/Dominators.h"47#include "llvm/IR/Function.h"48#include "llvm/IR/Instruction.h"49#include "llvm/IR/Instructions.h"50#include "llvm/IR/LLVMContext.h"51#include "llvm/IR/Metadata.h"52#include "llvm/IR/PassManager.h"53#include "llvm/IR/Value.h"54#include "llvm/Support/Casting.h"55#include "llvm/Support/CommandLine.h"56#include "llvm/Support/Debug.h"57#include "llvm/Support/raw_ostream.h"58#include "llvm/Transforms/Utils/BasicBlockUtils.h"59#include "llvm/Transforms/Utils/Cloning.h"60#include "llvm/Transforms/Utils/LoopUtils.h"61#include "llvm/Transforms/Utils/LoopVersioning.h"62#include "llvm/Transforms/Utils/ValueMapper.h"63#include <cassert>64#include <functional>65#include <list>66#include <tuple>67#include <utility>6869using namespace llvm;7071#define LDIST_NAME "loop-distribute"72#define DEBUG_TYPE LDIST_NAME7374/// @{75/// Metadata attribute names76static const char *const LLVMLoopDistributeFollowupAll =77"llvm.loop.distribute.followup_all";78static const char *const LLVMLoopDistributeFollowupCoincident =79"llvm.loop.distribute.followup_coincident";80static const char *const LLVMLoopDistributeFollowupSequential =81"llvm.loop.distribute.followup_sequential";82static const char *const LLVMLoopDistributeFollowupFallback =83"llvm.loop.distribute.followup_fallback";84/// @}8586static cl::opt<bool>87LDistVerify("loop-distribute-verify", cl::Hidden,88cl::desc("Turn on DominatorTree and LoopInfo verification "89"after Loop Distribution"),90cl::init(false));9192static cl::opt<bool> DistributeNonIfConvertible(93"loop-distribute-non-if-convertible", cl::Hidden,94cl::desc("Whether to distribute into a loop that may not be "95"if-convertible by the loop vectorizer"),96cl::init(false));9798static cl::opt<unsigned> DistributeSCEVCheckThreshold(99"loop-distribute-scev-check-threshold", cl::init(8), cl::Hidden,100cl::desc("The maximum number of SCEV checks allowed for Loop "101"Distribution"));102103static cl::opt<unsigned> PragmaDistributeSCEVCheckThreshold(104"loop-distribute-scev-check-threshold-with-pragma", cl::init(128),105cl::Hidden,106cl::desc("The maximum number of SCEV checks allowed for Loop "107"Distribution for loop marked with #pragma clang loop "108"distribute(enable)"));109110static cl::opt<bool> EnableLoopDistribute(111"enable-loop-distribute", cl::Hidden,112cl::desc("Enable the new, experimental LoopDistribution Pass"),113cl::init(false));114115STATISTIC(NumLoopsDistributed, "Number of loops distributed");116117namespace {118119/// Maintains the set of instructions of the loop for a partition before120/// cloning. After cloning, it hosts the new loop.121class InstPartition {122using InstructionSet = SmallSetVector<Instruction *, 8>;123124public:125InstPartition(Instruction *I, Loop *L, bool DepCycle = false)126: DepCycle(DepCycle), OrigLoop(L) {127Set.insert(I);128}129130/// Returns whether this partition contains a dependence cycle.131bool hasDepCycle() const { return DepCycle; }132133/// Adds an instruction to this partition.134void add(Instruction *I) { Set.insert(I); }135136/// Collection accessors.137InstructionSet::iterator begin() { return Set.begin(); }138InstructionSet::iterator end() { return Set.end(); }139InstructionSet::const_iterator begin() const { return Set.begin(); }140InstructionSet::const_iterator end() const { return Set.end(); }141bool empty() const { return Set.empty(); }142143/// Moves this partition into \p Other. This partition becomes empty144/// after this.145void moveTo(InstPartition &Other) {146Other.Set.insert(Set.begin(), Set.end());147Set.clear();148Other.DepCycle |= DepCycle;149}150151/// Populates the partition with a transitive closure of all the152/// instructions that the seeded instructions dependent on.153void populateUsedSet() {154// FIXME: We currently don't use control-dependence but simply include all155// blocks (possibly empty at the end) and let simplifycfg mostly clean this156// up.157for (auto *B : OrigLoop->getBlocks())158Set.insert(B->getTerminator());159160// Follow the use-def chains to form a transitive closure of all the161// instructions that the originally seeded instructions depend on.162SmallVector<Instruction *, 8> Worklist(Set.begin(), Set.end());163while (!Worklist.empty()) {164Instruction *I = Worklist.pop_back_val();165// Insert instructions from the loop that we depend on.166for (Value *V : I->operand_values()) {167auto *I = dyn_cast<Instruction>(V);168if (I && OrigLoop->contains(I->getParent()) && Set.insert(I))169Worklist.push_back(I);170}171}172}173174/// Clones the original loop.175///176/// Updates LoopInfo and DominatorTree using the information that block \p177/// LoopDomBB dominates the loop.178Loop *cloneLoopWithPreheader(BasicBlock *InsertBefore, BasicBlock *LoopDomBB,179unsigned Index, LoopInfo *LI,180DominatorTree *DT) {181ClonedLoop = ::cloneLoopWithPreheader(InsertBefore, LoopDomBB, OrigLoop,182VMap, Twine(".ldist") + Twine(Index),183LI, DT, ClonedLoopBlocks);184return ClonedLoop;185}186187/// The cloned loop. If this partition is mapped to the original loop,188/// this is null.189const Loop *getClonedLoop() const { return ClonedLoop; }190191/// Returns the loop where this partition ends up after distribution.192/// If this partition is mapped to the original loop then use the block from193/// the loop.194Loop *getDistributedLoop() const {195return ClonedLoop ? ClonedLoop : OrigLoop;196}197198/// The VMap that is populated by cloning and then used in199/// remapinstruction to remap the cloned instructions.200ValueToValueMapTy &getVMap() { return VMap; }201202/// Remaps the cloned instructions using VMap.203void remapInstructions() {204remapInstructionsInBlocks(ClonedLoopBlocks, VMap);205}206207/// Based on the set of instructions selected for this partition,208/// removes the unnecessary ones.209void removeUnusedInsts() {210SmallVector<Instruction *, 8> Unused;211212for (auto *Block : OrigLoop->getBlocks())213for (auto &Inst : *Block)214if (!Set.count(&Inst)) {215Instruction *NewInst = &Inst;216if (!VMap.empty())217NewInst = cast<Instruction>(VMap[NewInst]);218219assert(!isa<BranchInst>(NewInst) &&220"Branches are marked used early on");221Unused.push_back(NewInst);222}223224// Delete the instructions backwards, as it has a reduced likelihood of225// having to update as many def-use and use-def chains.226for (auto *Inst : reverse(Unused)) {227if (!Inst->use_empty())228Inst->replaceAllUsesWith(PoisonValue::get(Inst->getType()));229Inst->eraseFromParent();230}231}232233void print(raw_ostream &OS) const {234OS << (DepCycle ? " (cycle)\n" : "\n");235for (auto *I : Set)236// Prefix with the block name.237OS << " " << I->getParent()->getName() << ":" << *I << "\n";238}239240void printBlocks(raw_ostream &OS) const {241for (auto *BB : getDistributedLoop()->getBlocks())242OS << *BB;243}244245private:246/// Instructions from OrigLoop selected for this partition.247InstructionSet Set;248249/// Whether this partition contains a dependence cycle.250bool DepCycle;251252/// The original loop.253Loop *OrigLoop;254255/// The cloned loop. If this partition is mapped to the original loop,256/// this is null.257Loop *ClonedLoop = nullptr;258259/// The blocks of ClonedLoop including the preheader. If this260/// partition is mapped to the original loop, this is empty.261SmallVector<BasicBlock *, 8> ClonedLoopBlocks;262263/// These gets populated once the set of instructions have been264/// finalized. If this partition is mapped to the original loop, these are not265/// set.266ValueToValueMapTy VMap;267};268269/// Holds the set of Partitions. It populates them, merges them and then270/// clones the loops.271class InstPartitionContainer {272using InstToPartitionIdT = DenseMap<Instruction *, int>;273274public:275InstPartitionContainer(Loop *L, LoopInfo *LI, DominatorTree *DT)276: L(L), LI(LI), DT(DT) {}277278/// Returns the number of partitions.279unsigned getSize() const { return PartitionContainer.size(); }280281/// Adds \p Inst into the current partition if that is marked to282/// contain cycles. Otherwise start a new partition for it.283void addToCyclicPartition(Instruction *Inst) {284// If the current partition is non-cyclic. Start a new one.285if (PartitionContainer.empty() || !PartitionContainer.back().hasDepCycle())286PartitionContainer.emplace_back(Inst, L, /*DepCycle=*/true);287else288PartitionContainer.back().add(Inst);289}290291/// Adds \p Inst into a partition that is not marked to contain292/// dependence cycles.293///294// Initially we isolate memory instructions into as many partitions as295// possible, then later we may merge them back together.296void addToNewNonCyclicPartition(Instruction *Inst) {297PartitionContainer.emplace_back(Inst, L);298}299300/// Merges adjacent non-cyclic partitions.301///302/// The idea is that we currently only want to isolate the non-vectorizable303/// partition. We could later allow more distribution among these partition304/// too.305void mergeAdjacentNonCyclic() {306mergeAdjacentPartitionsIf(307[](const InstPartition *P) { return !P->hasDepCycle(); });308}309310/// If a partition contains only conditional stores, we won't vectorize311/// it. Try to merge it with a previous cyclic partition.312void mergeNonIfConvertible() {313mergeAdjacentPartitionsIf([&](const InstPartition *Partition) {314if (Partition->hasDepCycle())315return true;316317// Now, check if all stores are conditional in this partition.318bool seenStore = false;319320for (auto *Inst : *Partition)321if (isa<StoreInst>(Inst)) {322seenStore = true;323if (!LoopAccessInfo::blockNeedsPredication(Inst->getParent(), L, DT))324return false;325}326return seenStore;327});328}329330/// Merges the partitions according to various heuristics.331void mergeBeforePopulating() {332mergeAdjacentNonCyclic();333if (!DistributeNonIfConvertible)334mergeNonIfConvertible();335}336337/// Merges partitions in order to ensure that no loads are duplicated.338///339/// We can't duplicate loads because that could potentially reorder them.340/// LoopAccessAnalysis provides dependency information with the context that341/// the order of memory operation is preserved.342///343/// Return if any partitions were merged.344bool mergeToAvoidDuplicatedLoads() {345using LoadToPartitionT = DenseMap<Instruction *, InstPartition *>;346using ToBeMergedT = EquivalenceClasses<InstPartition *>;347348LoadToPartitionT LoadToPartition;349ToBeMergedT ToBeMerged;350351// Step through the partitions and create equivalence between partitions352// that contain the same load. Also put partitions in between them in the353// same equivalence class to avoid reordering of memory operations.354for (PartitionContainerT::iterator I = PartitionContainer.begin(),355E = PartitionContainer.end();356I != E; ++I) {357auto *PartI = &*I;358359// If a load occurs in two partitions PartI and PartJ, merge all360// partitions (PartI, PartJ] into PartI.361for (Instruction *Inst : *PartI)362if (isa<LoadInst>(Inst)) {363bool NewElt;364LoadToPartitionT::iterator LoadToPart;365366std::tie(LoadToPart, NewElt) =367LoadToPartition.insert(std::make_pair(Inst, PartI));368if (!NewElt) {369LLVM_DEBUG(370dbgs()371<< "LDist: Merging partitions due to this load in multiple "372<< "partitions: " << PartI << ", " << LoadToPart->second << "\n"373<< *Inst << "\n");374375auto PartJ = I;376do {377--PartJ;378ToBeMerged.unionSets(PartI, &*PartJ);379} while (&*PartJ != LoadToPart->second);380}381}382}383if (ToBeMerged.empty())384return false;385386// Merge the member of an equivalence class into its class leader. This387// makes the members empty.388for (ToBeMergedT::iterator I = ToBeMerged.begin(), E = ToBeMerged.end();389I != E; ++I) {390if (!I->isLeader())391continue;392393auto PartI = I->getData();394for (auto *PartJ : make_range(std::next(ToBeMerged.member_begin(I)),395ToBeMerged.member_end())) {396PartJ->moveTo(*PartI);397}398}399400// Remove the empty partitions.401PartitionContainer.remove_if(402[](const InstPartition &P) { return P.empty(); });403404return true;405}406407/// Sets up the mapping between instructions to partitions. If the408/// instruction is duplicated across multiple partitions, set the entry to -1.409void setupPartitionIdOnInstructions() {410int PartitionID = 0;411for (const auto &Partition : PartitionContainer) {412for (Instruction *Inst : Partition) {413bool NewElt;414InstToPartitionIdT::iterator Iter;415416std::tie(Iter, NewElt) =417InstToPartitionId.insert(std::make_pair(Inst, PartitionID));418if (!NewElt)419Iter->second = -1;420}421++PartitionID;422}423}424425/// Populates the partition with everything that the seeding426/// instructions require.427void populateUsedSet() {428for (auto &P : PartitionContainer)429P.populateUsedSet();430}431432/// This performs the main chunk of the work of cloning the loops for433/// the partitions.434void cloneLoops() {435BasicBlock *OrigPH = L->getLoopPreheader();436// At this point the predecessor of the preheader is either the memcheck437// block or the top part of the original preheader.438BasicBlock *Pred = OrigPH->getSinglePredecessor();439assert(Pred && "Preheader does not have a single predecessor");440BasicBlock *ExitBlock = L->getExitBlock();441assert(ExitBlock && "No single exit block");442Loop *NewLoop;443444assert(!PartitionContainer.empty() && "at least two partitions expected");445// We're cloning the preheader along with the loop so we already made sure446// it was empty.447assert(&*OrigPH->begin() == OrigPH->getTerminator() &&448"preheader not empty");449450// Preserve the original loop ID for use after the transformation.451MDNode *OrigLoopID = L->getLoopID();452453// Create a loop for each partition except the last. Clone the original454// loop before PH along with adding a preheader for the cloned loop. Then455// update PH to point to the newly added preheader.456BasicBlock *TopPH = OrigPH;457unsigned Index = getSize() - 1;458for (auto &Part : llvm::drop_begin(llvm::reverse(PartitionContainer))) {459NewLoop = Part.cloneLoopWithPreheader(TopPH, Pred, Index, LI, DT);460461Part.getVMap()[ExitBlock] = TopPH;462Part.remapInstructions();463setNewLoopID(OrigLoopID, &Part);464--Index;465TopPH = NewLoop->getLoopPreheader();466}467Pred->getTerminator()->replaceUsesOfWith(OrigPH, TopPH);468469// Also set a new loop ID for the last loop.470setNewLoopID(OrigLoopID, &PartitionContainer.back());471472// Now go in forward order and update the immediate dominator for the473// preheaders with the exiting block of the previous loop. Dominance474// within the loop is updated in cloneLoopWithPreheader.475for (auto Curr = PartitionContainer.cbegin(),476Next = std::next(PartitionContainer.cbegin()),477E = PartitionContainer.cend();478Next != E; ++Curr, ++Next)479DT->changeImmediateDominator(480Next->getDistributedLoop()->getLoopPreheader(),481Curr->getDistributedLoop()->getExitingBlock());482}483484/// Removes the dead instructions from the cloned loops.485void removeUnusedInsts() {486for (auto &Partition : PartitionContainer)487Partition.removeUnusedInsts();488}489490/// For each memory pointer, it computes the partitionId the pointer is491/// used in.492///493/// This returns an array of int where the I-th entry corresponds to I-th494/// entry in LAI.getRuntimePointerCheck(). If the pointer is used in multiple495/// partitions its entry is set to -1.496SmallVector<int, 8>497computePartitionSetForPointers(const LoopAccessInfo &LAI) {498const RuntimePointerChecking *RtPtrCheck = LAI.getRuntimePointerChecking();499500unsigned N = RtPtrCheck->Pointers.size();501SmallVector<int, 8> PtrToPartitions(N);502for (unsigned I = 0; I < N; ++I) {503Value *Ptr = RtPtrCheck->Pointers[I].PointerValue;504auto Instructions =505LAI.getInstructionsForAccess(Ptr, RtPtrCheck->Pointers[I].IsWritePtr);506507int &Partition = PtrToPartitions[I];508// First set it to uninitialized.509Partition = -2;510for (Instruction *Inst : Instructions) {511// Note that this could be -1 if Inst is duplicated across multiple512// partitions.513int ThisPartition = this->InstToPartitionId[Inst];514if (Partition == -2)515Partition = ThisPartition;516// -1 means belonging to multiple partitions.517else if (Partition == -1)518break;519else if (Partition != (int)ThisPartition)520Partition = -1;521}522assert(Partition != -2 && "Pointer not belonging to any partition");523}524525return PtrToPartitions;526}527528void print(raw_ostream &OS) const {529unsigned Index = 0;530for (const auto &P : PartitionContainer) {531OS << "LDist: Partition " << Index++ << ":";532P.print(OS);533}534}535536void dump() const { print(dbgs()); }537538#ifndef NDEBUG539friend raw_ostream &operator<<(raw_ostream &OS,540const InstPartitionContainer &Partitions) {541Partitions.print(OS);542return OS;543}544#endif545546void printBlocks(raw_ostream &OS) const {547unsigned Index = 0;548for (const auto &P : PartitionContainer) {549OS << "LDist: Partition " << Index++ << ":";550P.printBlocks(OS);551}552}553554private:555using PartitionContainerT = std::list<InstPartition>;556557/// List of partitions.558PartitionContainerT PartitionContainer;559560/// Mapping from Instruction to partition Id. If the instruction561/// belongs to multiple partitions the entry contains -1.562InstToPartitionIdT InstToPartitionId;563564Loop *L;565LoopInfo *LI;566DominatorTree *DT;567568/// The control structure to merge adjacent partitions if both satisfy569/// the \p Predicate.570template <class UnaryPredicate>571void mergeAdjacentPartitionsIf(UnaryPredicate Predicate) {572InstPartition *PrevMatch = nullptr;573for (auto I = PartitionContainer.begin(); I != PartitionContainer.end();) {574auto DoesMatch = Predicate(&*I);575if (PrevMatch == nullptr && DoesMatch) {576PrevMatch = &*I;577++I;578} else if (PrevMatch != nullptr && DoesMatch) {579I->moveTo(*PrevMatch);580I = PartitionContainer.erase(I);581} else {582PrevMatch = nullptr;583++I;584}585}586}587588/// Assign new LoopIDs for the partition's cloned loop.589void setNewLoopID(MDNode *OrigLoopID, InstPartition *Part) {590std::optional<MDNode *> PartitionID = makeFollowupLoopID(591OrigLoopID,592{LLVMLoopDistributeFollowupAll,593Part->hasDepCycle() ? LLVMLoopDistributeFollowupSequential594: LLVMLoopDistributeFollowupCoincident});595if (PartitionID) {596Loop *NewLoop = Part->getDistributedLoop();597NewLoop->setLoopID(*PartitionID);598}599}600};601602/// For each memory instruction, this class maintains difference of the603/// number of unsafe dependences that start out from this instruction minus604/// those that end here.605///606/// By traversing the memory instructions in program order and accumulating this607/// number, we know whether any unsafe dependence crosses over a program point.608class MemoryInstructionDependences {609using Dependence = MemoryDepChecker::Dependence;610611public:612struct Entry {613Instruction *Inst;614unsigned NumUnsafeDependencesStartOrEnd = 0;615616Entry(Instruction *Inst) : Inst(Inst) {}617};618619using AccessesType = SmallVector<Entry, 8>;620621AccessesType::const_iterator begin() const { return Accesses.begin(); }622AccessesType::const_iterator end() const { return Accesses.end(); }623624MemoryInstructionDependences(625const SmallVectorImpl<Instruction *> &Instructions,626const SmallVectorImpl<Dependence> &Dependences) {627Accesses.append(Instructions.begin(), Instructions.end());628629LLVM_DEBUG(dbgs() << "LDist: Backward dependences:\n");630for (const auto &Dep : Dependences)631if (Dep.isPossiblyBackward()) {632// Note that the designations source and destination follow the program633// order, i.e. source is always first. (The direction is given by the634// DepType.)635++Accesses[Dep.Source].NumUnsafeDependencesStartOrEnd;636--Accesses[Dep.Destination].NumUnsafeDependencesStartOrEnd;637638LLVM_DEBUG(Dep.print(dbgs(), 2, Instructions));639}640}641642private:643AccessesType Accesses;644};645646/// The actual class performing the per-loop work.647class LoopDistributeForLoop {648public:649LoopDistributeForLoop(Loop *L, Function *F, LoopInfo *LI, DominatorTree *DT,650ScalarEvolution *SE, LoopAccessInfoManager &LAIs,651OptimizationRemarkEmitter *ORE)652: L(L), F(F), LI(LI), DT(DT), SE(SE), LAIs(LAIs), ORE(ORE) {653setForced();654}655656/// Try to distribute an inner-most loop.657bool processLoop() {658assert(L->isInnermost() && "Only process inner loops.");659660LLVM_DEBUG(dbgs() << "\nLDist: Checking a loop in '"661<< L->getHeader()->getParent()->getName() << "' from "662<< L->getLocStr() << "\n");663664// Having a single exit block implies there's also one exiting block.665if (!L->getExitBlock())666return fail("MultipleExitBlocks", "multiple exit blocks");667if (!L->isLoopSimplifyForm())668return fail("NotLoopSimplifyForm",669"loop is not in loop-simplify form");670if (!L->isRotatedForm())671return fail("NotBottomTested", "loop is not bottom tested");672673BasicBlock *PH = L->getLoopPreheader();674675LAI = &LAIs.getInfo(*L);676677// Currently, we only distribute to isolate the part of the loop with678// dependence cycles to enable partial vectorization.679if (LAI->canVectorizeMemory())680return fail("MemOpsCanBeVectorized",681"memory operations are safe for vectorization");682683auto *Dependences = LAI->getDepChecker().getDependences();684if (!Dependences || Dependences->empty())685return fail("NoUnsafeDeps", "no unsafe dependences to isolate");686687LLVM_DEBUG(dbgs() << "LDist: Found a candidate loop: "688<< L->getHeader()->getName() << "\n");689690InstPartitionContainer Partitions(L, LI, DT);691692// First, go through each memory operation and assign them to consecutive693// partitions (the order of partitions follows program order). Put those694// with unsafe dependences into "cyclic" partition otherwise put each store695// in its own "non-cyclic" partition (we'll merge these later).696//697// Note that a memory operation (e.g. Load2 below) at a program point that698// has an unsafe dependence (Store3->Load1) spanning over it must be699// included in the same cyclic partition as the dependent operations. This700// is to preserve the original program order after distribution. E.g.:701//702// NumUnsafeDependencesStartOrEnd NumUnsafeDependencesActive703// Load1 -. 1 0->1704// Load2 | /Unsafe/ 0 1705// Store3 -' -1 1->0706// Load4 0 0707//708// NumUnsafeDependencesActive > 0 indicates this situation and in this case709// we just keep assigning to the same cyclic partition until710// NumUnsafeDependencesActive reaches 0.711const MemoryDepChecker &DepChecker = LAI->getDepChecker();712MemoryInstructionDependences MID(DepChecker.getMemoryInstructions(),713*Dependences);714715int NumUnsafeDependencesActive = 0;716for (const auto &InstDep : MID) {717Instruction *I = InstDep.Inst;718// We update NumUnsafeDependencesActive post-instruction, catch the719// start of a dependence directly via NumUnsafeDependencesStartOrEnd.720if (NumUnsafeDependencesActive ||721InstDep.NumUnsafeDependencesStartOrEnd > 0)722Partitions.addToCyclicPartition(I);723else724Partitions.addToNewNonCyclicPartition(I);725NumUnsafeDependencesActive += InstDep.NumUnsafeDependencesStartOrEnd;726assert(NumUnsafeDependencesActive >= 0 &&727"Negative number of dependences active");728}729730// Add partitions for values used outside. These partitions can be out of731// order from the original program order. This is OK because if the732// partition uses a load we will merge this partition with the original733// partition of the load that we set up in the previous loop (see734// mergeToAvoidDuplicatedLoads).735auto DefsUsedOutside = findDefsUsedOutsideOfLoop(L);736for (auto *Inst : DefsUsedOutside)737Partitions.addToNewNonCyclicPartition(Inst);738739LLVM_DEBUG(dbgs() << "LDist: Seeded partitions:\n" << Partitions);740if (Partitions.getSize() < 2)741return fail("CantIsolateUnsafeDeps",742"cannot isolate unsafe dependencies");743744// Run the merge heuristics: Merge non-cyclic adjacent partitions since we745// should be able to vectorize these together.746Partitions.mergeBeforePopulating();747LLVM_DEBUG(dbgs() << "LDist: Merged partitions:\n" << Partitions);748if (Partitions.getSize() < 2)749return fail("CantIsolateUnsafeDeps",750"cannot isolate unsafe dependencies");751752// Now, populate the partitions with non-memory operations.753Partitions.populateUsedSet();754LLVM_DEBUG(dbgs() << "LDist: Populated partitions:\n" << Partitions);755756// In order to preserve original lexical order for loads, keep them in the757// partition that we set up in the MemoryInstructionDependences loop.758if (Partitions.mergeToAvoidDuplicatedLoads()) {759LLVM_DEBUG(dbgs() << "LDist: Partitions merged to ensure unique loads:\n"760<< Partitions);761if (Partitions.getSize() < 2)762return fail("CantIsolateUnsafeDeps",763"cannot isolate unsafe dependencies");764}765766// Don't distribute the loop if we need too many SCEV run-time checks, or767// any if it's illegal.768const SCEVPredicate &Pred = LAI->getPSE().getPredicate();769if (LAI->hasConvergentOp() && !Pred.isAlwaysTrue()) {770return fail("RuntimeCheckWithConvergent",771"may not insert runtime check with convergent operation");772}773774if (Pred.getComplexity() > (IsForced.value_or(false)775? PragmaDistributeSCEVCheckThreshold776: DistributeSCEVCheckThreshold))777return fail("TooManySCEVRuntimeChecks",778"too many SCEV run-time checks needed.\n");779780if (!IsForced.value_or(false) && hasDisableAllTransformsHint(L))781return fail("HeuristicDisabled", "distribution heuristic disabled");782783LLVM_DEBUG(dbgs() << "LDist: Distributing loop: "784<< L->getHeader()->getName() << "\n");785// We're done forming the partitions set up the reverse mapping from786// instructions to partitions.787Partitions.setupPartitionIdOnInstructions();788789// If we need run-time checks, version the loop now.790auto PtrToPartition = Partitions.computePartitionSetForPointers(*LAI);791const auto *RtPtrChecking = LAI->getRuntimePointerChecking();792const auto &AllChecks = RtPtrChecking->getChecks();793auto Checks = includeOnlyCrossPartitionChecks(AllChecks, PtrToPartition,794RtPtrChecking);795796if (LAI->hasConvergentOp() && !Checks.empty()) {797return fail("RuntimeCheckWithConvergent",798"may not insert runtime check with convergent operation");799}800801// To keep things simple have an empty preheader before we version or clone802// the loop. (Also split if this has no predecessor, i.e. entry, because we803// rely on PH having a predecessor.)804if (!PH->getSinglePredecessor() || &*PH->begin() != PH->getTerminator())805SplitBlock(PH, PH->getTerminator(), DT, LI);806807if (!Pred.isAlwaysTrue() || !Checks.empty()) {808assert(!LAI->hasConvergentOp() && "inserting illegal loop versioning");809810MDNode *OrigLoopID = L->getLoopID();811812LLVM_DEBUG(dbgs() << "LDist: Pointers:\n");813LLVM_DEBUG(LAI->getRuntimePointerChecking()->printChecks(dbgs(), Checks));814LoopVersioning LVer(*LAI, Checks, L, LI, DT, SE);815LVer.versionLoop(DefsUsedOutside);816LVer.annotateLoopWithNoAlias();817818// The unversioned loop will not be changed, so we inherit all attributes819// from the original loop, but remove the loop distribution metadata to820// avoid to distribute it again.821MDNode *UnversionedLoopID = *makeFollowupLoopID(822OrigLoopID,823{LLVMLoopDistributeFollowupAll, LLVMLoopDistributeFollowupFallback},824"llvm.loop.distribute.", true);825LVer.getNonVersionedLoop()->setLoopID(UnversionedLoopID);826}827828// Create identical copies of the original loop for each partition and hook829// them up sequentially.830Partitions.cloneLoops();831832// Now, we remove the instruction from each loop that don't belong to that833// partition.834Partitions.removeUnusedInsts();835LLVM_DEBUG(dbgs() << "LDist: After removing unused Instrs:\n");836LLVM_DEBUG(Partitions.printBlocks(dbgs()));837838if (LDistVerify) {839LI->verify(*DT);840assert(DT->verify(DominatorTree::VerificationLevel::Fast));841}842843++NumLoopsDistributed;844// Report the success.845ORE->emit([&]() {846return OptimizationRemark(LDIST_NAME, "Distribute", L->getStartLoc(),847L->getHeader())848<< "distributed loop";849});850return true;851}852853/// Provide diagnostics then \return with false.854bool fail(StringRef RemarkName, StringRef Message) {855LLVMContext &Ctx = F->getContext();856bool Forced = isForced().value_or(false);857858LLVM_DEBUG(dbgs() << "LDist: Skipping; " << Message << "\n");859860// With Rpass-missed report that distribution failed.861ORE->emit([&]() {862return OptimizationRemarkMissed(LDIST_NAME, "NotDistributed",863L->getStartLoc(), L->getHeader())864<< "loop not distributed: use -Rpass-analysis=loop-distribute for "865"more "866"info";867});868869// With Rpass-analysis report why. This is on by default if distribution870// was requested explicitly.871ORE->emit(OptimizationRemarkAnalysis(872Forced ? OptimizationRemarkAnalysis::AlwaysPrint : LDIST_NAME,873RemarkName, L->getStartLoc(), L->getHeader())874<< "loop not distributed: " << Message);875876// Also issue a warning if distribution was requested explicitly but it877// failed.878if (Forced)879Ctx.diagnose(DiagnosticInfoOptimizationFailure(880*F, L->getStartLoc(), "loop not distributed: failed "881"explicitly specified loop distribution"));882883return false;884}885886/// Return if distribution forced to be enabled/disabled for the loop.887///888/// If the optional has a value, it indicates whether distribution was forced889/// to be enabled (true) or disabled (false). If the optional has no value890/// distribution was not forced either way.891const std::optional<bool> &isForced() const { return IsForced; }892893private:894/// Filter out checks between pointers from the same partition.895///896/// \p PtrToPartition contains the partition number for pointers. Partition897/// number -1 means that the pointer is used in multiple partitions. In this898/// case we can't safely omit the check.899SmallVector<RuntimePointerCheck, 4> includeOnlyCrossPartitionChecks(900const SmallVectorImpl<RuntimePointerCheck> &AllChecks,901const SmallVectorImpl<int> &PtrToPartition,902const RuntimePointerChecking *RtPtrChecking) {903SmallVector<RuntimePointerCheck, 4> Checks;904905copy_if(AllChecks, std::back_inserter(Checks),906[&](const RuntimePointerCheck &Check) {907for (unsigned PtrIdx1 : Check.first->Members)908for (unsigned PtrIdx2 : Check.second->Members)909// Only include this check if there is a pair of pointers910// that require checking and the pointers fall into911// separate partitions.912//913// (Note that we already know at this point that the two914// pointer groups need checking but it doesn't follow915// that each pair of pointers within the two groups need916// checking as well.917//918// In other words we don't want to include a check just919// because there is a pair of pointers between the two920// pointer groups that require checks and a different921// pair whose pointers fall into different partitions.)922if (RtPtrChecking->needsChecking(PtrIdx1, PtrIdx2) &&923!RuntimePointerChecking::arePointersInSamePartition(924PtrToPartition, PtrIdx1, PtrIdx2))925return true;926return false;927});928929return Checks;930}931932/// Check whether the loop metadata is forcing distribution to be933/// enabled/disabled.934void setForced() {935std::optional<const MDOperand *> Value =936findStringMetadataForLoop(L, "llvm.loop.distribute.enable");937if (!Value)938return;939940const MDOperand *Op = *Value;941assert(Op && mdconst::hasa<ConstantInt>(*Op) && "invalid metadata");942IsForced = mdconst::extract<ConstantInt>(*Op)->getZExtValue();943}944945Loop *L;946Function *F;947948// Analyses used.949LoopInfo *LI;950const LoopAccessInfo *LAI = nullptr;951DominatorTree *DT;952ScalarEvolution *SE;953LoopAccessInfoManager &LAIs;954OptimizationRemarkEmitter *ORE;955956/// Indicates whether distribution is forced to be enabled/disabled for957/// the loop.958///959/// If the optional has a value, it indicates whether distribution was forced960/// to be enabled (true) or disabled (false). If the optional has no value961/// distribution was not forced either way.962std::optional<bool> IsForced;963};964965} // end anonymous namespace966967static bool runImpl(Function &F, LoopInfo *LI, DominatorTree *DT,968ScalarEvolution *SE, OptimizationRemarkEmitter *ORE,969LoopAccessInfoManager &LAIs) {970// Build up a worklist of inner-loops to distribute. This is necessary as the971// act of distributing a loop creates new loops and can invalidate iterators972// across the loops.973SmallVector<Loop *, 8> Worklist;974975for (Loop *TopLevelLoop : *LI)976for (Loop *L : depth_first(TopLevelLoop))977// We only handle inner-most loops.978if (L->isInnermost())979Worklist.push_back(L);980981// Now walk the identified inner loops.982bool Changed = false;983for (Loop *L : Worklist) {984LoopDistributeForLoop LDL(L, &F, LI, DT, SE, LAIs, ORE);985986// If distribution was forced for the specific loop to be987// enabled/disabled, follow that. Otherwise use the global flag.988if (LDL.isForced().value_or(EnableLoopDistribute))989Changed |= LDL.processLoop();990}991992// Process each loop nest in the function.993return Changed;994}995996PreservedAnalyses LoopDistributePass::run(Function &F,997FunctionAnalysisManager &AM) {998auto &LI = AM.getResult<LoopAnalysis>(F);999auto &DT = AM.getResult<DominatorTreeAnalysis>(F);1000auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);1001auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);10021003LoopAccessInfoManager &LAIs = AM.getResult<LoopAccessAnalysis>(F);1004bool Changed = runImpl(F, &LI, &DT, &SE, &ORE, LAIs);1005if (!Changed)1006return PreservedAnalyses::all();1007PreservedAnalyses PA;1008PA.preserve<LoopAnalysis>();1009PA.preserve<DominatorTreeAnalysis>();1010return PA;1011}101210131014