brintos

brintos / llvm-project-archived public Read only

0
0
Text · 21.4 KiB · a9e08ad Raw
554 lines · cpp
1//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// This pass transforms loops by placing phi nodes at the end of the loops for10// all values that are live across the loop boundary.  For example, it turns11// the left into the right code:12//13// for (...)                for (...)14//   if (c)                   if (c)15//     X1 = ...                 X1 = ...16//   else                     else17//     X2 = ...                 X2 = ...18//   X3 = phi(X1, X2)         X3 = phi(X1, X2)19// ... = X3 + 4             X4 = phi(X3)20//                          ... = X4 + 421//22// This is still valid LLVM; the extra phi nodes are purely redundant, and will23// be trivially eliminated by InstCombine.  The major benefit of this24// transformation is that it makes many other loop optimizations, such as25// LoopUnswitching, simpler.26//27//===----------------------------------------------------------------------===//28 29#include "llvm/Transforms/Utils/LCSSA.h"30#include "llvm/ADT/STLExtras.h"31#include "llvm/ADT/Statistic.h"32#include "llvm/Analysis/AliasAnalysis.h"33#include "llvm/Analysis/BasicAliasAnalysis.h"34#include "llvm/Analysis/BranchProbabilityInfo.h"35#include "llvm/Analysis/GlobalsModRef.h"36#include "llvm/Analysis/LoopInfo.h"37#include "llvm/Analysis/LoopPass.h"38#include "llvm/Analysis/MemorySSA.h"39#include "llvm/Analysis/ScalarEvolution.h"40#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"41#include "llvm/IR/DebugInfo.h"42#include "llvm/IR/Dominators.h"43#include "llvm/IR/Instructions.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;52 53#define DEBUG_TYPE "lcssa"54 55STATISTIC(NumLCSSA, "Number of live out of a loop variables");56 57#ifdef EXPENSIVE_CHECKS58static bool VerifyLoopLCSSA = true;59#else60static bool VerifyLoopLCSSA = false;61#endif62static cl::opt<bool, true>63    VerifyLoopLCSSAFlag("verify-loop-lcssa", cl::location(VerifyLoopLCSSA),64                        cl::Hidden,65                        cl::desc("Verify loop lcssa form (time consuming)"));66 67/// Return true if the specified block is in the list.68static bool isExitBlock(BasicBlock *BB,69                        const SmallVectorImpl<BasicBlock *> &ExitBlocks) {70  return is_contained(ExitBlocks, BB);71}72 73// Cache the Loop ExitBlocks computed during the analysis.  We expect to get a74// lot of instructions within the same loops, computing the exit blocks is75// expensive, and we're not mutating the loop structure.76using LoopExitBlocksTy = SmallDenseMap<Loop *, SmallVector<BasicBlock *, 1>>;77 78/// For every instruction from the worklist, check to see if it has any uses79/// that are outside the current loop.  If so, insert LCSSA PHI nodes and80/// rewrite the uses.81static bool82formLCSSAForInstructionsImpl(SmallVectorImpl<Instruction *> &Worklist,83                             const DominatorTree &DT, const LoopInfo &LI,84                             ScalarEvolution *SE,85                             SmallVectorImpl<PHINode *> *PHIsToRemove,86                             SmallVectorImpl<PHINode *> *InsertedPHIs,87                             LoopExitBlocksTy &LoopExitBlocks) {88  SmallVector<Use *, 16> UsesToRewrite;89  SmallSetVector<PHINode *, 16> LocalPHIsToRemove;90  PredIteratorCache PredCache;91  bool Changed = false;92 93  while (!Worklist.empty()) {94    UsesToRewrite.clear();95 96    Instruction *I = Worklist.pop_back_val();97    assert(!I->getType()->isTokenTy() && "Tokens shouldn't be in the worklist");98    BasicBlock *InstBB = I->getParent();99    Loop *L = LI.getLoopFor(InstBB);100    assert(L && "Instruction belongs to a BB that's not part of a loop");101    auto [It, Inserted] = LoopExitBlocks.try_emplace(L);102    if (Inserted)103      L->getExitBlocks(It->second);104    const SmallVectorImpl<BasicBlock *> &ExitBlocks = It->second;105 106    if (ExitBlocks.empty())107      continue;108 109    for (Use &U : make_early_inc_range(I->uses())) {110      Instruction *User = cast<Instruction>(U.getUser());111      BasicBlock *UserBB = User->getParent();112 113      // Skip uses in unreachable blocks.114      if (!DT.isReachableFromEntry(UserBB)) {115        U.set(PoisonValue::get(I->getType()));116        continue;117      }118 119      // For practical purposes, we consider that the use in a PHI120      // occurs in the respective predecessor block. For more info,121      // see the `phi` doc in LangRef and the LCSSA doc.122      if (auto *PN = dyn_cast<PHINode>(User))123        UserBB = PN->getIncomingBlock(U);124 125      if (InstBB != UserBB && !L->contains(UserBB))126        UsesToRewrite.push_back(&U);127    }128 129    // If there are no uses outside the loop, exit with no change.130    if (UsesToRewrite.empty())131      continue;132 133    ++NumLCSSA; // We are applying the transformation134 135    // Invoke instructions are special in that their result value is not136    // available along their unwind edge. The code below tests to see whether137    // DomBB dominates the value, so adjust DomBB to the normal destination138    // block, which is effectively where the value is first usable.139    BasicBlock *DomBB = InstBB;140    if (auto *Inv = dyn_cast<InvokeInst>(I))141      DomBB = Inv->getNormalDest();142 143    const DomTreeNode *DomNode = DT.getNode(DomBB);144 145    SmallVector<PHINode *, 16> AddedPHIs;146    SmallVector<PHINode *, 8> PostProcessPHIs;147 148    SmallVector<PHINode *, 4> LocalInsertedPHIs;149    SSAUpdater SSAUpdate(&LocalInsertedPHIs);150    SSAUpdate.Initialize(I->getType(), I->getName());151 152    // Insert the LCSSA phi's into all of the exit blocks dominated by the153    // value, and add them to the Phi's map.154    bool HasSCEV = SE && SE->isSCEVable(I->getType()) &&155                   SE->getExistingSCEV(I) != nullptr;156    for (BasicBlock *ExitBB : ExitBlocks) {157      if (!DT.dominates(DomNode, DT.getNode(ExitBB)))158        continue;159 160      // If we already inserted something for this BB, don't reprocess it.161      if (SSAUpdate.HasValueForBlock(ExitBB))162        continue;163      PHINode *PN = PHINode::Create(I->getType(), PredCache.size(ExitBB),164                                    I->getName() + ".lcssa");165      PN->insertBefore(ExitBB->begin());166      if (InsertedPHIs)167        InsertedPHIs->push_back(PN);168      // Get the debug location from the original instruction.169      PN->setDebugLoc(I->getDebugLoc());170 171      // Add inputs from inside the loop for this PHI. This is valid172      // because `I` dominates `ExitBB` (checked above).  This implies173      // that every incoming block/edge is dominated by `I` as well,174      // i.e. we can add uses of `I` to those incoming edges/append to the incoming175      // blocks without violating the SSA dominance property.176      for (BasicBlock *Pred : PredCache.get(ExitBB)) {177        PN->addIncoming(I, Pred);178 179        // If the exit block has a predecessor not within the loop, arrange for180        // the incoming value use corresponding to that predecessor to be181        // rewritten in terms of a different LCSSA PHI.182        if (!L->contains(Pred))183          UsesToRewrite.push_back(184              &PN->getOperandUse(PN->getOperandNumForIncomingValue(185                  PN->getNumIncomingValues() - 1)));186      }187 188      AddedPHIs.push_back(PN);189 190      // Remember that this phi makes the value alive in this block.191      SSAUpdate.AddAvailableValue(ExitBB, PN);192 193      // LoopSimplify might fail to simplify some loops (e.g. when indirect194      // branches are involved). In such situations, it might happen that an195      // exit for Loop L1 is the header of a disjoint Loop L2. Thus, when we196      // create PHIs in such an exit block, we are also inserting PHIs into L2's197      // header. This could break LCSSA form for L2 because these inserted PHIs198      // can also have uses outside of L2. Remember all PHIs in such situation199      // as to revisit than later on. FIXME: Remove this if indirectbr support200      // into LoopSimplify gets improved.201      if (auto *OtherLoop = LI.getLoopFor(ExitBB))202        if (!L->contains(OtherLoop))203          PostProcessPHIs.push_back(PN);204 205      // If we have a cached SCEV for the original instruction, make sure the206      // new LCSSA phi node is also cached. This makes sures that BECounts207      // based on it will be invalidated when the LCSSA phi node is invalidated,208      // which some passes rely on.209      if (HasSCEV)210        SE->getSCEV(PN);211    }212 213    // Rewrite all uses outside the loop in terms of the new PHIs we just214    // inserted.215    for (Use *UseToRewrite : UsesToRewrite) {216      Instruction *User = cast<Instruction>(UseToRewrite->getUser());217      BasicBlock *UserBB = User->getParent();218 219      // For practical purposes, we consider that the use in a PHI220      // occurs in the respective predecessor block. For more info,221      // see the `phi` doc in LangRef and the LCSSA doc.222      if (auto *PN = dyn_cast<PHINode>(User))223        UserBB = PN->getIncomingBlock(*UseToRewrite);224 225      // If this use is in an exit block, rewrite to use the newly inserted PHI.226      // This is required for correctness because SSAUpdate doesn't handle uses227      // in the same block.  It assumes the PHI we inserted is at the end of the228      // block.229      if (isa<PHINode>(UserBB->begin()) && isExitBlock(UserBB, ExitBlocks)) {230        UseToRewrite->set(&UserBB->front());231        continue;232      }233 234      // If we added a single PHI, it must dominate all uses and we can directly235      // rename it.236      if (AddedPHIs.size() == 1) {237        UseToRewrite->set(AddedPHIs[0]);238        continue;239      }240 241      // Otherwise, do full PHI insertion.242      SSAUpdate.RewriteUse(*UseToRewrite);243    }244 245    SmallVector<DbgVariableRecord *, 4> DbgVariableRecords;246    llvm::findDbgValues(I, DbgVariableRecords);247 248    // Update pre-existing debug value uses that reside outside the loop.249    for (DbgVariableRecord *DVR : DbgVariableRecords) {250      BasicBlock *UserBB = DVR->getMarker()->getParent();251      if (InstBB == UserBB || L->contains(UserBB))252        continue;253      // We currently only handle debug values residing in blocks that were254      // traversed while rewriting the uses. If we inserted just a single PHI,255      // we will handle all relevant debug values.256      Value *V = AddedPHIs.size() == 1 ? AddedPHIs[0]257                                       : SSAUpdate.FindValueForBlock(UserBB);258      if (V)259        DVR->replaceVariableLocationOp(I, V);260    }261 262    // SSAUpdater might have inserted phi-nodes inside other loops. We'll need263    // to post-process them to keep LCSSA form.264    for (PHINode *InsertedPN : LocalInsertedPHIs) {265      if (auto *OtherLoop = LI.getLoopFor(InsertedPN->getParent()))266        if (!L->contains(OtherLoop))267          PostProcessPHIs.push_back(InsertedPN);268      if (InsertedPHIs)269        InsertedPHIs->push_back(InsertedPN);270    }271 272    // Post process PHI instructions that were inserted into another disjoint273    // loop and update their exits properly.274    for (auto *PostProcessPN : PostProcessPHIs)275      if (!PostProcessPN->use_empty())276        Worklist.push_back(PostProcessPN);277 278    // Keep track of PHI nodes that we want to remove because they did not have279    // any uses rewritten.280    for (PHINode *PN : AddedPHIs)281      if (PN->use_empty())282        LocalPHIsToRemove.insert(PN);283 284    Changed = true;285  }286 287  // Remove PHI nodes that did not have any uses rewritten or add them to288  // PHIsToRemove, so the caller can remove them after some additional cleanup.289  // We need to redo the use_empty() check here, because even if the PHI node290  // wasn't used when added to LocalPHIsToRemove, later added PHI nodes can be291  // using it.  This cleanup is not guaranteed to handle trees/cycles of PHI292  // nodes that only are used by each other. Such situations has only been293  // noticed when the input IR contains unreachable code, and leaving some extra294  // redundant PHI nodes in such situations is considered a minor problem.295  if (PHIsToRemove) {296    PHIsToRemove->append(LocalPHIsToRemove.begin(), LocalPHIsToRemove.end());297  } else {298    for (PHINode *PN : LocalPHIsToRemove)299      if (PN->use_empty())300        PN->eraseFromParent();301  }302  return Changed;303}304 305/// For every instruction from the worklist, check to see if it has any uses306/// that are outside the current loop.  If so, insert LCSSA PHI nodes and307/// rewrite the uses.308bool llvm::formLCSSAForInstructions(SmallVectorImpl<Instruction *> &Worklist,309                                    const DominatorTree &DT, const LoopInfo &LI,310                                    ScalarEvolution *SE,311                                    SmallVectorImpl<PHINode *> *PHIsToRemove,312                                    SmallVectorImpl<PHINode *> *InsertedPHIs) {313  LoopExitBlocksTy LoopExitBlocks;314 315  return formLCSSAForInstructionsImpl(Worklist, DT, LI, SE, PHIsToRemove,316                                      InsertedPHIs, LoopExitBlocks);317}318 319// Compute the set of BasicBlocks in the loop `L` dominating at least one exit.320static void computeBlocksDominatingExits(321    Loop &L, const DominatorTree &DT, ArrayRef<BasicBlock *> ExitBlocks,322    SmallSetVector<BasicBlock *, 8> &BlocksDominatingExits) {323  // We start from the exit blocks, as every block trivially dominates itself324  // (not strictly).325  SmallVector<BasicBlock *, 8> BBWorklist(ExitBlocks);326 327  while (!BBWorklist.empty()) {328    BasicBlock *BB = BBWorklist.pop_back_val();329 330    // Check if this is a loop header. If this is the case, we're done.331    if (L.getHeader() == BB)332      continue;333 334    // Otherwise, add its immediate predecessor in the dominator tree to the335    // worklist, unless we visited it already.336    BasicBlock *IDomBB = DT.getNode(BB)->getIDom()->getBlock();337 338    // 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.354    if (!L.contains(IDomBB))355      continue;356 357    if (BlocksDominatingExits.insert(IDomBB))358      BBWorklist.push_back(IDomBB);359  }360}361 362static bool formLCSSAImpl(Loop &L, const DominatorTree &DT, const LoopInfo *LI,363                          ScalarEvolution *SE,364                          LoopExitBlocksTy &LoopExitBlocks) {365  bool Changed = false;366 367#ifdef EXPENSIVE_CHECKS368  // Verify all sub-loops are in LCSSA form already.369  for (Loop *SubLoop: L) {370    (void)SubLoop; // Silence unused variable warning.371    assert(SubLoop->isRecursivelyLCSSAForm(DT, *LI) && "Subloop not in LCSSA!");372  }373#endif374 375  auto [It, Inserted] = LoopExitBlocks.try_emplace(&L);376  if (Inserted)377    L.getExitBlocks(It->second);378  const SmallVectorImpl<BasicBlock *> &ExitBlocks = It->second;379  if (ExitBlocks.empty())380    return false;381 382  SmallSetVector<BasicBlock *, 8> BlocksDominatingExits;383 384  // We want to avoid use-scanning leveraging dominance informations.385  // If a block doesn't dominate any of the loop exits, the none of the values386  // defined in the loop can be used outside.387  // We compute the set of blocks fullfilling the conditions in advance388  // walking the dominator tree upwards until we hit a loop header.389  computeBlocksDominatingExits(L, DT, ExitBlocks, BlocksDominatingExits);390 391  SmallVector<Instruction *, 8> Worklist;392 393  // Look at all the instructions in the loop, checking to see if they have uses394  // outside the loop.  If so, put them into the worklist to rewrite those uses.395  for (BasicBlock *BB : BlocksDominatingExits) {396    // Skip blocks that are part of any sub-loops, they must be in LCSSA397    // already.398    if (LI->getLoopFor(BB) != &L)399      continue;400    for (Instruction &I : *BB) {401      // Reject two common cases fast: instructions with no uses (like stores)402      // and instructions with one use that is in the same block as this.403      if (I.use_empty() ||404          (I.hasOneUse() && I.user_back()->getParent() == BB &&405           !isa<PHINode>(I.user_back())))406        continue;407 408      // Tokens cannot be used in PHI nodes, so we skip over them.409      // We can run into tokens which are live out of a loop with catchswitch410      // instructions in Windows EH if the catchswitch has one catchpad which411      // is inside the loop and another which is not.412      if (I.getType()->isTokenTy())413        continue;414 415      Worklist.push_back(&I);416    }417  }418 419  Changed = formLCSSAForInstructionsImpl(Worklist, DT, *LI, SE, nullptr,420                                         nullptr, LoopExitBlocks);421 422  assert(L.isLCSSAForm(DT));423 424  return Changed;425}426 427bool llvm::formLCSSA(Loop &L, const DominatorTree &DT, const LoopInfo *LI,428                     ScalarEvolution *SE) {429  LoopExitBlocksTy LoopExitBlocks;430 431  return formLCSSAImpl(L, DT, LI, SE, LoopExitBlocks);432}433 434/// Process a loop nest depth first.435static bool formLCSSARecursivelyImpl(Loop &L, const DominatorTree &DT,436                                     const LoopInfo *LI, ScalarEvolution *SE,437                                     LoopExitBlocksTy &LoopExitBlocks) {438  bool Changed = false;439 440  // Recurse depth-first through inner loops.441  for (Loop *SubLoop : L.getSubLoops())442    Changed |= formLCSSARecursivelyImpl(*SubLoop, DT, LI, SE, LoopExitBlocks);443 444  Changed |= formLCSSAImpl(L, DT, LI, SE, LoopExitBlocks);445  return Changed;446}447 448/// Process a loop nest depth first.449bool llvm::formLCSSARecursively(Loop &L, const DominatorTree &DT,450                                const LoopInfo *LI, ScalarEvolution *SE) {451  LoopExitBlocksTy LoopExitBlocks;452 453  return formLCSSARecursivelyImpl(L, DT, LI, SE, LoopExitBlocks);454}455 456/// Process all loops in the function, inner-most out.457static bool formLCSSAOnAllLoops(const LoopInfo *LI, const DominatorTree &DT,458                                ScalarEvolution *SE) {459  bool Changed = false;460  for (const auto &L : *LI)461    Changed |= formLCSSARecursively(*L, DT, LI, SE);462  return Changed;463}464 465namespace {466struct LCSSAWrapperPass : public FunctionPass {467  static char ID; // Pass identification, replacement for typeid468  LCSSAWrapperPass() : FunctionPass(ID) {469    initializeLCSSAWrapperPassPass(*PassRegistry::getPassRegistry());470  }471 472  // Cached analysis information for the current function.473  DominatorTree *DT;474  LoopInfo *LI;475  ScalarEvolution *SE;476 477  bool runOnFunction(Function &F) override;478  void verifyAnalysis() const override {479    // This check is very expensive. On the loop intensive compiles it may cause480    // up to 10x slowdown. Currently it's disabled by default. LPPassManager481    // always does limited form of the LCSSA verification. Similar reasoning482    // was used for the LoopInfo verifier.483    if (VerifyLoopLCSSA) {484      assert(all_of(*LI,485                    [&](Loop *L) {486                      return L->isRecursivelyLCSSAForm(*DT, *LI);487                    }) &&488             "LCSSA form is broken!");489    }490  };491 492  /// This transformation requires natural loop information & requires that493  /// loop preheaders be inserted into the CFG.  It maintains both of these,494  /// as well as the CFG.  It also requires dominator information.495  void getAnalysisUsage(AnalysisUsage &AU) const override {496    AU.setPreservesCFG();497 498    AU.addRequired<DominatorTreeWrapperPass>();499    AU.addRequired<LoopInfoWrapperPass>();500    AU.addPreservedID(LoopSimplifyID);501    AU.addPreserved<AAResultsWrapperPass>();502    AU.addPreserved<BasicAAWrapperPass>();503    AU.addPreserved<GlobalsAAWrapperPass>();504    AU.addPreserved<ScalarEvolutionWrapperPass>();505    AU.addPreserved<SCEVAAWrapperPass>();506    AU.addPreserved<BranchProbabilityInfoWrapperPass>();507    AU.addPreserved<MemorySSAWrapperPass>();508 509    // This is needed to perform LCSSA verification inside LPPassManager510    AU.addRequired<LCSSAVerificationPass>();511    AU.addPreserved<LCSSAVerificationPass>();512  }513};514}515 516char LCSSAWrapperPass::ID = 0;517INITIALIZE_PASS_BEGIN(LCSSAWrapperPass, "lcssa", "Loop-Closed SSA Form Pass",518                      false, false)519INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)520INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)521INITIALIZE_PASS_DEPENDENCY(LCSSAVerificationPass)522INITIALIZE_PASS_END(LCSSAWrapperPass, "lcssa", "Loop-Closed SSA Form Pass",523                    false, false)524 525Pass *llvm::createLCSSAPass() { return new LCSSAWrapperPass(); }526char &llvm::LCSSAID = LCSSAWrapperPass::ID;527 528/// Transform \p F into loop-closed SSA form.529bool LCSSAWrapperPass::runOnFunction(Function &F) {530  LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();531  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();532  auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();533  SE = SEWP ? &SEWP->getSE() : nullptr;534 535  return formLCSSAOnAllLoops(LI, *DT, SE);536}537 538PreservedAnalyses LCSSAPass::run(Function &F, FunctionAnalysisManager &AM) {539  auto &LI = AM.getResult<LoopAnalysis>(F);540  auto &DT = AM.getResult<DominatorTreeAnalysis>(F);541  auto *SE = AM.getCachedResult<ScalarEvolutionAnalysis>(F);542  if (!formLCSSAOnAllLoops(&LI, DT, SE))543    return PreservedAnalyses::all();544 545  PreservedAnalyses PA;546  PA.preserveSet<CFGAnalyses>();547  PA.preserve<ScalarEvolutionAnalysis>();548  // BPI maps terminators to probabilities, since we don't modify the CFG, no549  // updates are needed to preserve it.550  PA.preserve<BranchProbabilityAnalysis>();551  PA.preserve<MemorySSAAnalysis>();552  return PA;553}554