Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Utils/LCSSA.cpp
35271 views
//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//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 pass transforms loops by placing phi nodes at the end of the loops for9// all values that are live across the loop boundary. For example, it turns10// the left into the right code:11//12// for (...) for (...)13// if (c) if (c)14// X1 = ... X1 = ...15// else else16// X2 = ... X2 = ...17// X3 = phi(X1, X2) X3 = phi(X1, X2)18// ... = X3 + 4 X4 = phi(X3)19// ... = X4 + 420//21// This is still valid LLVM; the extra phi nodes are purely redundant, and will22// be trivially eliminated by InstCombine. The major benefit of this23// transformation is that it makes many other loop optimizations, such as24// LoopUnswitching, simpler.25//26//===----------------------------------------------------------------------===//2728#include "llvm/Transforms/Utils/LCSSA.h"29#include "llvm/ADT/STLExtras.h"30#include "llvm/ADT/Statistic.h"31#include "llvm/Analysis/AliasAnalysis.h"32#include "llvm/Analysis/BasicAliasAnalysis.h"33#include "llvm/Analysis/BranchProbabilityInfo.h"34#include "llvm/Analysis/GlobalsModRef.h"35#include "llvm/Analysis/LoopInfo.h"36#include "llvm/Analysis/LoopPass.h"37#include "llvm/Analysis/MemorySSA.h"38#include "llvm/Analysis/ScalarEvolution.h"39#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"40#include "llvm/IR/DebugInfo.h"41#include "llvm/IR/Dominators.h"42#include "llvm/IR/Instructions.h"43#include "llvm/IR/IntrinsicInst.h"44#include "llvm/IR/PredIteratorCache.h"45#include "llvm/InitializePasses.h"46#include "llvm/Pass.h"47#include "llvm/Support/CommandLine.h"48#include "llvm/Transforms/Utils.h"49#include "llvm/Transforms/Utils/LoopUtils.h"50#include "llvm/Transforms/Utils/SSAUpdater.h"51using namespace llvm;5253#define DEBUG_TYPE "lcssa"5455STATISTIC(NumLCSSA, "Number of live out of a loop variables");5657#ifdef EXPENSIVE_CHECKS58static bool VerifyLoopLCSSA = true;59#else60static bool VerifyLoopLCSSA = false;61#endif62static cl::opt<bool, true>63VerifyLoopLCSSAFlag("verify-loop-lcssa", cl::location(VerifyLoopLCSSA),64cl::Hidden,65cl::desc("Verify loop lcssa form (time consuming)"));6667/// Return true if the specified block is in the list.68static bool isExitBlock(BasicBlock *BB,69const SmallVectorImpl<BasicBlock *> &ExitBlocks) {70return is_contained(ExitBlocks, BB);71}7273/// For every instruction from the worklist, check to see if it has any uses74/// that are outside the current loop. If so, insert LCSSA PHI nodes and75/// rewrite the uses.76bool llvm::formLCSSAForInstructions(SmallVectorImpl<Instruction *> &Worklist,77const DominatorTree &DT, const LoopInfo &LI,78ScalarEvolution *SE,79SmallVectorImpl<PHINode *> *PHIsToRemove,80SmallVectorImpl<PHINode *> *InsertedPHIs) {81SmallVector<Use *, 16> UsesToRewrite;82SmallSetVector<PHINode *, 16> LocalPHIsToRemove;83PredIteratorCache PredCache;84bool Changed = false;8586// Cache the Loop ExitBlocks across this loop. We expect to get a lot of87// instructions within the same loops, computing the exit blocks is88// expensive, and we're not mutating the loop structure.89SmallDenseMap<Loop*, SmallVector<BasicBlock *,1>> LoopExitBlocks;9091while (!Worklist.empty()) {92UsesToRewrite.clear();9394Instruction *I = Worklist.pop_back_val();95assert(!I->getType()->isTokenTy() && "Tokens shouldn't be in the worklist");96BasicBlock *InstBB = I->getParent();97Loop *L = LI.getLoopFor(InstBB);98assert(L && "Instruction belongs to a BB that's not part of a loop");99if (!LoopExitBlocks.count(L))100L->getExitBlocks(LoopExitBlocks[L]);101assert(LoopExitBlocks.count(L));102const SmallVectorImpl<BasicBlock *> &ExitBlocks = LoopExitBlocks[L];103104if (ExitBlocks.empty())105continue;106107for (Use &U : make_early_inc_range(I->uses())) {108Instruction *User = cast<Instruction>(U.getUser());109BasicBlock *UserBB = User->getParent();110111// Skip uses in unreachable blocks.112if (!DT.isReachableFromEntry(UserBB)) {113U.set(PoisonValue::get(I->getType()));114continue;115}116117// For practical purposes, we consider that the use in a PHI118// occurs in the respective predecessor block. For more info,119// see the `phi` doc in LangRef and the LCSSA doc.120if (auto *PN = dyn_cast<PHINode>(User))121UserBB = PN->getIncomingBlock(U);122123if (InstBB != UserBB && !L->contains(UserBB))124UsesToRewrite.push_back(&U);125}126127// If there are no uses outside the loop, exit with no change.128if (UsesToRewrite.empty())129continue;130131++NumLCSSA; // We are applying the transformation132133// Invoke instructions are special in that their result value is not134// available along their unwind edge. The code below tests to see whether135// DomBB dominates the value, so adjust DomBB to the normal destination136// block, which is effectively where the value is first usable.137BasicBlock *DomBB = InstBB;138if (auto *Inv = dyn_cast<InvokeInst>(I))139DomBB = Inv->getNormalDest();140141const DomTreeNode *DomNode = DT.getNode(DomBB);142143SmallVector<PHINode *, 16> AddedPHIs;144SmallVector<PHINode *, 8> PostProcessPHIs;145146SmallVector<PHINode *, 4> LocalInsertedPHIs;147SSAUpdater SSAUpdate(&LocalInsertedPHIs);148SSAUpdate.Initialize(I->getType(), I->getName());149150// Insert the LCSSA phi's into all of the exit blocks dominated by the151// value, and add them to the Phi's map.152bool HasSCEV = SE && SE->isSCEVable(I->getType()) &&153SE->getExistingSCEV(I) != nullptr;154for (BasicBlock *ExitBB : ExitBlocks) {155if (!DT.dominates(DomNode, DT.getNode(ExitBB)))156continue;157158// If we already inserted something for this BB, don't reprocess it.159if (SSAUpdate.HasValueForBlock(ExitBB))160continue;161PHINode *PN = PHINode::Create(I->getType(), PredCache.size(ExitBB),162I->getName() + ".lcssa");163PN->insertBefore(ExitBB->begin());164if (InsertedPHIs)165InsertedPHIs->push_back(PN);166// Get the debug location from the original instruction.167PN->setDebugLoc(I->getDebugLoc());168169// Add inputs from inside the loop for this PHI. This is valid170// because `I` dominates `ExitBB` (checked above). This implies171// that every incoming block/edge is dominated by `I` as well,172// i.e. we can add uses of `I` to those incoming edges/append to the incoming173// blocks without violating the SSA dominance property.174for (BasicBlock *Pred : PredCache.get(ExitBB)) {175PN->addIncoming(I, Pred);176177// If the exit block has a predecessor not within the loop, arrange for178// the incoming value use corresponding to that predecessor to be179// rewritten in terms of a different LCSSA PHI.180if (!L->contains(Pred))181UsesToRewrite.push_back(182&PN->getOperandUse(PN->getOperandNumForIncomingValue(183PN->getNumIncomingValues() - 1)));184}185186AddedPHIs.push_back(PN);187188// Remember that this phi makes the value alive in this block.189SSAUpdate.AddAvailableValue(ExitBB, PN);190191// LoopSimplify might fail to simplify some loops (e.g. when indirect192// branches are involved). In such situations, it might happen that an193// exit for Loop L1 is the header of a disjoint Loop L2. Thus, when we194// create PHIs in such an exit block, we are also inserting PHIs into L2's195// header. This could break LCSSA form for L2 because these inserted PHIs196// can also have uses outside of L2. Remember all PHIs in such situation197// as to revisit than later on. FIXME: Remove this if indirectbr support198// into LoopSimplify gets improved.199if (auto *OtherLoop = LI.getLoopFor(ExitBB))200if (!L->contains(OtherLoop))201PostProcessPHIs.push_back(PN);202203// If we have a cached SCEV for the original instruction, make sure the204// new LCSSA phi node is also cached. This makes sures that BECounts205// based on it will be invalidated when the LCSSA phi node is invalidated,206// which some passes rely on.207if (HasSCEV)208SE->getSCEV(PN);209}210211// Rewrite all uses outside the loop in terms of the new PHIs we just212// inserted.213for (Use *UseToRewrite : UsesToRewrite) {214Instruction *User = cast<Instruction>(UseToRewrite->getUser());215BasicBlock *UserBB = User->getParent();216217// For practical purposes, we consider that the use in a PHI218// occurs in the respective predecessor block. For more info,219// see the `phi` doc in LangRef and the LCSSA doc.220if (auto *PN = dyn_cast<PHINode>(User))221UserBB = PN->getIncomingBlock(*UseToRewrite);222223// If this use is in an exit block, rewrite to use the newly inserted PHI.224// This is required for correctness because SSAUpdate doesn't handle uses225// in the same block. It assumes the PHI we inserted is at the end of the226// block.227if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {228UseToRewrite->set(&UserBB->front());229continue;230}231232// If we added a single PHI, it must dominate all uses and we can directly233// rename it.234if (AddedPHIs.size() == 1) {235UseToRewrite->set(AddedPHIs[0]);236continue;237}238239// Otherwise, do full PHI insertion.240SSAUpdate.RewriteUse(*UseToRewrite);241}242243SmallVector<DbgValueInst *, 4> DbgValues;244SmallVector<DbgVariableRecord *, 4> DbgVariableRecords;245llvm::findDbgValues(DbgValues, I, &DbgVariableRecords);246247// Update pre-existing debug value uses that reside outside the loop.248for (auto *DVI : DbgValues) {249BasicBlock *UserBB = DVI->getParent();250if (InstBB == UserBB || L->contains(UserBB))251continue;252// We currently only handle debug values residing in blocks that were253// traversed while rewriting the uses. If we inserted just a single PHI,254// we will handle all relevant debug values.255Value *V = AddedPHIs.size() == 1 ? AddedPHIs[0]256: SSAUpdate.FindValueForBlock(UserBB);257if (V)258DVI->replaceVariableLocationOp(I, V);259}260261// RemoveDIs: copy-paste of block above, using non-instruction debug-info262// records.263for (DbgVariableRecord *DVR : DbgVariableRecords) {264BasicBlock *UserBB = DVR->getMarker()->getParent();265if (InstBB == UserBB || L->contains(UserBB))266continue;267// We currently only handle debug values residing in blocks that were268// traversed while rewriting the uses. If we inserted just a single PHI,269// we will handle all relevant debug values.270Value *V = AddedPHIs.size() == 1 ? AddedPHIs[0]271: SSAUpdate.FindValueForBlock(UserBB);272if (V)273DVR->replaceVariableLocationOp(I, V);274}275276// SSAUpdater might have inserted phi-nodes inside other loops. We'll need277// to post-process them to keep LCSSA form.278for (PHINode *InsertedPN : LocalInsertedPHIs) {279if (auto *OtherLoop = LI.getLoopFor(InsertedPN->getParent()))280if (!L->contains(OtherLoop))281PostProcessPHIs.push_back(InsertedPN);282if (InsertedPHIs)283InsertedPHIs->push_back(InsertedPN);284}285286// Post process PHI instructions that were inserted into another disjoint287// loop and update their exits properly.288for (auto *PostProcessPN : PostProcessPHIs)289if (!PostProcessPN->use_empty())290Worklist.push_back(PostProcessPN);291292// Keep track of PHI nodes that we want to remove because they did not have293// any uses rewritten.294for (PHINode *PN : AddedPHIs)295if (PN->use_empty())296LocalPHIsToRemove.insert(PN);297298Changed = true;299}300301// Remove PHI nodes that did not have any uses rewritten or add them to302// PHIsToRemove, so the caller can remove them after some additional cleanup.303// We need to redo the use_empty() check here, because even if the PHI node304// wasn't used when added to LocalPHIsToRemove, later added PHI nodes can be305// using it. This cleanup is not guaranteed to handle trees/cycles of PHI306// nodes that only are used by each other. Such situations has only been307// noticed when the input IR contains unreachable code, and leaving some extra308// redundant PHI nodes in such situations is considered a minor problem.309if (PHIsToRemove) {310PHIsToRemove->append(LocalPHIsToRemove.begin(), LocalPHIsToRemove.end());311} else {312for (PHINode *PN : LocalPHIsToRemove)313if (PN->use_empty())314PN->eraseFromParent();315}316return Changed;317}318319// Compute the set of BasicBlocks in the loop `L` dominating at least one exit.320static void computeBlocksDominatingExits(321Loop &L, const DominatorTree &DT, SmallVector<BasicBlock *, 8> &ExitBlocks,322SmallSetVector<BasicBlock *, 8> &BlocksDominatingExits) {323// We start from the exit blocks, as every block trivially dominates itself324// (not strictly).325SmallVector<BasicBlock *, 8> BBWorklist(ExitBlocks);326327while (!BBWorklist.empty()) {328BasicBlock *BB = BBWorklist.pop_back_val();329330// Check if this is a loop header. If this is the case, we're done.331if (L.getHeader() == BB)332continue;333334// Otherwise, add its immediate predecessor in the dominator tree to the335// worklist, unless we visited it already.336BasicBlock *IDomBB = DT.getNode(BB)->getIDom()->getBlock();337338// Exit blocks can have an immediate dominator not belonging to the339// loop. For an exit block to be immediately dominated by another block340// outside the loop, it implies not all paths from that dominator, to the341// exit block, go through the loop.342// Example:343//344// |---- A345// | |346// | B<--347// | | |348// |---> C --349// |350// D351//352// C is the exit block of the loop and it's immediately dominated by A,353// which doesn't belong to the loop.354if (!L.contains(IDomBB))355continue;356357if (BlocksDominatingExits.insert(IDomBB))358BBWorklist.push_back(IDomBB);359}360}361362bool llvm::formLCSSA(Loop &L, const DominatorTree &DT, const LoopInfo *LI,363ScalarEvolution *SE) {364bool Changed = false;365366#ifdef EXPENSIVE_CHECKS367// Verify all sub-loops are in LCSSA form already.368for (Loop *SubLoop: L) {369(void)SubLoop; // Silence unused variable warning.370assert(SubLoop->isRecursivelyLCSSAForm(DT, *LI) && "Subloop not in LCSSA!");371}372#endif373374SmallVector<BasicBlock *, 8> ExitBlocks;375L.getExitBlocks(ExitBlocks);376if (ExitBlocks.empty())377return false;378379SmallSetVector<BasicBlock *, 8> BlocksDominatingExits;380381// We want to avoid use-scanning leveraging dominance informations.382// If a block doesn't dominate any of the loop exits, the none of the values383// defined in the loop can be used outside.384// We compute the set of blocks fullfilling the conditions in advance385// walking the dominator tree upwards until we hit a loop header.386computeBlocksDominatingExits(L, DT, ExitBlocks, BlocksDominatingExits);387388SmallVector<Instruction *, 8> Worklist;389390// Look at all the instructions in the loop, checking to see if they have uses391// outside the loop. If so, put them into the worklist to rewrite those uses.392for (BasicBlock *BB : BlocksDominatingExits) {393// Skip blocks that are part of any sub-loops, they must be in LCSSA394// already.395if (LI->getLoopFor(BB) != &L)396continue;397for (Instruction &I : *BB) {398// Reject two common cases fast: instructions with no uses (like stores)399// and instructions with one use that is in the same block as this.400if (I.use_empty() ||401(I.hasOneUse() && I.user_back()->getParent() == BB &&402!isa<PHINode>(I.user_back())))403continue;404405// Tokens cannot be used in PHI nodes, so we skip over them.406// We can run into tokens which are live out of a loop with catchswitch407// instructions in Windows EH if the catchswitch has one catchpad which408// is inside the loop and another which is not.409if (I.getType()->isTokenTy())410continue;411412Worklist.push_back(&I);413}414}415416Changed = formLCSSAForInstructions(Worklist, DT, *LI, SE);417418assert(L.isLCSSAForm(DT));419420return Changed;421}422423/// Process a loop nest depth first.424bool llvm::formLCSSARecursively(Loop &L, const DominatorTree &DT,425const LoopInfo *LI, ScalarEvolution *SE) {426bool Changed = false;427428// Recurse depth-first through inner loops.429for (Loop *SubLoop : L.getSubLoops())430Changed |= formLCSSARecursively(*SubLoop, DT, LI, SE);431432Changed |= formLCSSA(L, DT, LI, SE);433return Changed;434}435436/// Process all loops in the function, inner-most out.437static bool formLCSSAOnAllLoops(const LoopInfo *LI, const DominatorTree &DT,438ScalarEvolution *SE) {439bool Changed = false;440for (const auto &L : *LI)441Changed |= formLCSSARecursively(*L, DT, LI, SE);442return Changed;443}444445namespace {446struct LCSSAWrapperPass : public FunctionPass {447static char ID; // Pass identification, replacement for typeid448LCSSAWrapperPass() : FunctionPass(ID) {449initializeLCSSAWrapperPassPass(*PassRegistry::getPassRegistry());450}451452// Cached analysis information for the current function.453DominatorTree *DT;454LoopInfo *LI;455ScalarEvolution *SE;456457bool runOnFunction(Function &F) override;458void verifyAnalysis() const override {459// This check is very expensive. On the loop intensive compiles it may cause460// up to 10x slowdown. Currently it's disabled by default. LPPassManager461// always does limited form of the LCSSA verification. Similar reasoning462// was used for the LoopInfo verifier.463if (VerifyLoopLCSSA) {464assert(all_of(*LI,465[&](Loop *L) {466return L->isRecursivelyLCSSAForm(*DT, *LI);467}) &&468"LCSSA form is broken!");469}470};471472/// This transformation requires natural loop information & requires that473/// loop preheaders be inserted into the CFG. It maintains both of these,474/// as well as the CFG. It also requires dominator information.475void getAnalysisUsage(AnalysisUsage &AU) const override {476AU.setPreservesCFG();477478AU.addRequired<DominatorTreeWrapperPass>();479AU.addRequired<LoopInfoWrapperPass>();480AU.addPreservedID(LoopSimplifyID);481AU.addPreserved<AAResultsWrapperPass>();482AU.addPreserved<BasicAAWrapperPass>();483AU.addPreserved<GlobalsAAWrapperPass>();484AU.addPreserved<ScalarEvolutionWrapperPass>();485AU.addPreserved<SCEVAAWrapperPass>();486AU.addPreserved<BranchProbabilityInfoWrapperPass>();487AU.addPreserved<MemorySSAWrapperPass>();488489// This is needed to perform LCSSA verification inside LPPassManager490AU.addRequired<LCSSAVerificationPass>();491AU.addPreserved<LCSSAVerificationPass>();492}493};494}495496char LCSSAWrapperPass::ID = 0;497INITIALIZE_PASS_BEGIN(LCSSAWrapperPass, "lcssa", "Loop-Closed SSA Form Pass",498false, false)499INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)500INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)501INITIALIZE_PASS_DEPENDENCY(LCSSAVerificationPass)502INITIALIZE_PASS_END(LCSSAWrapperPass, "lcssa", "Loop-Closed SSA Form Pass",503false, false)504505Pass *llvm::createLCSSAPass() { return new LCSSAWrapperPass(); }506char &llvm::LCSSAID = LCSSAWrapperPass::ID;507508/// Transform \p F into loop-closed SSA form.509bool LCSSAWrapperPass::runOnFunction(Function &F) {510LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();511DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();512auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();513SE = SEWP ? &SEWP->getSE() : nullptr;514515return formLCSSAOnAllLoops(LI, *DT, SE);516}517518PreservedAnalyses LCSSAPass::run(Function &F, FunctionAnalysisManager &AM) {519auto &LI = AM.getResult<LoopAnalysis>(F);520auto &DT = AM.getResult<DominatorTreeAnalysis>(F);521auto *SE = AM.getCachedResult<ScalarEvolutionAnalysis>(F);522if (!formLCSSAOnAllLoops(&LI, DT, SE))523return PreservedAnalyses::all();524525PreservedAnalyses PA;526PA.preserveSet<CFGAnalyses>();527PA.preserve<ScalarEvolutionAnalysis>();528// BPI maps terminators to probabilities, since we don't modify the CFG, no529// updates are needed to preserve it.530PA.preserve<BranchProbabilityAnalysis>();531PA.preserve<MemorySSAAnalysis>();532return PA;533}534535536