Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Scalar/GVNHoist.cpp
35269 views
//===- GVNHoist.cpp - Hoist scalar and load expressions -------------------===//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 hoists expressions from branches to a common dominator. It uses9// GVN (global value numbering) to discover expressions computing the same10// values. The primary goals of code-hoisting are:11// 1. To reduce the code size.12// 2. In some cases reduce critical path (by exposing more ILP).13//14// The algorithm factors out the reachability of values such that multiple15// queries to find reachability of values are fast. This is based on finding the16// ANTIC points in the CFG which do not change during hoisting. The ANTIC points17// are basically the dominance-frontiers in the inverse graph. So we introduce a18// data structure (CHI nodes) to keep track of values flowing out of a basic19// block. We only do this for values with multiple occurrences in the function20// as they are the potential hoistable candidates. This approach allows us to21// hoist instructions to a basic block with more than two successors, as well as22// deal with infinite loops in a trivial way.23//24// Limitations: This pass does not hoist fully redundant expressions because25// they are already handled by GVN-PRE. It is advisable to run gvn-hoist before26// and after gvn-pre because gvn-pre creates opportunities for more instructions27// to be hoisted.28//29// Hoisting may affect the performance in some cases. To mitigate that, hoisting30// is disabled in the following cases.31// 1. Scalars across calls.32// 2. geps when corresponding load/store cannot be hoisted.33//===----------------------------------------------------------------------===//3435#include "llvm/ADT/DenseMap.h"36#include "llvm/ADT/DenseSet.h"37#include "llvm/ADT/STLExtras.h"38#include "llvm/ADT/SmallPtrSet.h"39#include "llvm/ADT/SmallVector.h"40#include "llvm/ADT/Statistic.h"41#include "llvm/ADT/iterator_range.h"42#include "llvm/Analysis/AliasAnalysis.h"43#include "llvm/Analysis/GlobalsModRef.h"44#include "llvm/Analysis/IteratedDominanceFrontier.h"45#include "llvm/Analysis/MemoryDependenceAnalysis.h"46#include "llvm/Analysis/MemorySSA.h"47#include "llvm/Analysis/MemorySSAUpdater.h"48#include "llvm/Analysis/PostDominators.h"49#include "llvm/Analysis/ValueTracking.h"50#include "llvm/IR/Argument.h"51#include "llvm/IR/BasicBlock.h"52#include "llvm/IR/CFG.h"53#include "llvm/IR/Constants.h"54#include "llvm/IR/Dominators.h"55#include "llvm/IR/Function.h"56#include "llvm/IR/Instruction.h"57#include "llvm/IR/Instructions.h"58#include "llvm/IR/IntrinsicInst.h"59#include "llvm/IR/LLVMContext.h"60#include "llvm/IR/PassManager.h"61#include "llvm/IR/Use.h"62#include "llvm/IR/User.h"63#include "llvm/IR/Value.h"64#include "llvm/Support/Casting.h"65#include "llvm/Support/CommandLine.h"66#include "llvm/Support/Debug.h"67#include "llvm/Support/raw_ostream.h"68#include "llvm/Transforms/Scalar/GVN.h"69#include "llvm/Transforms/Utils/Local.h"70#include <algorithm>71#include <cassert>72#include <iterator>73#include <memory>74#include <utility>75#include <vector>7677using namespace llvm;7879#define DEBUG_TYPE "gvn-hoist"8081STATISTIC(NumHoisted, "Number of instructions hoisted");82STATISTIC(NumRemoved, "Number of instructions removed");83STATISTIC(NumLoadsHoisted, "Number of loads hoisted");84STATISTIC(NumLoadsRemoved, "Number of loads removed");85STATISTIC(NumStoresHoisted, "Number of stores hoisted");86STATISTIC(NumStoresRemoved, "Number of stores removed");87STATISTIC(NumCallsHoisted, "Number of calls hoisted");88STATISTIC(NumCallsRemoved, "Number of calls removed");8990static cl::opt<int>91MaxHoistedThreshold("gvn-max-hoisted", cl::Hidden, cl::init(-1),92cl::desc("Max number of instructions to hoist "93"(default unlimited = -1)"));9495static cl::opt<int> MaxNumberOfBBSInPath(96"gvn-hoist-max-bbs", cl::Hidden, cl::init(4),97cl::desc("Max number of basic blocks on the path between "98"hoisting locations (default = 4, unlimited = -1)"));99100static cl::opt<int> MaxDepthInBB(101"gvn-hoist-max-depth", cl::Hidden, cl::init(100),102cl::desc("Hoist instructions from the beginning of the BB up to the "103"maximum specified depth (default = 100, unlimited = -1)"));104105static cl::opt<int>106MaxChainLength("gvn-hoist-max-chain-length", cl::Hidden, cl::init(10),107cl::desc("Maximum length of dependent chains to hoist "108"(default = 10, unlimited = -1)"));109110namespace llvm {111112using BBSideEffectsSet = DenseMap<const BasicBlock *, bool>;113using SmallVecInsn = SmallVector<Instruction *, 4>;114using SmallVecImplInsn = SmallVectorImpl<Instruction *>;115116// Each element of a hoisting list contains the basic block where to hoist and117// a list of instructions to be hoisted.118using HoistingPointInfo = std::pair<BasicBlock *, SmallVecInsn>;119120using HoistingPointList = SmallVector<HoistingPointInfo, 4>;121122// A map from a pair of VNs to all the instructions with those VNs.123using VNType = std::pair<unsigned, uintptr_t>;124125using VNtoInsns = DenseMap<VNType, SmallVector<Instruction *, 4>>;126127// CHI keeps information about values flowing out of a basic block. It is128// similar to PHI but in the inverse graph, and used for outgoing values on each129// edge. For conciseness, it is computed only for instructions with multiple130// occurrences in the CFG because they are the only hoistable candidates.131// A (CHI[{V, B, I1}, {V, C, I2}]132// / \133// / \134// B(I1) C (I2)135// The Value number for both I1 and I2 is V, the CHI node will save the136// instruction as well as the edge where the value is flowing to.137struct CHIArg {138VNType VN;139140// Edge destination (shows the direction of flow), may not be where the I is.141BasicBlock *Dest;142143// The instruction (VN) which uses the values flowing out of CHI.144Instruction *I;145146bool operator==(const CHIArg &A) const { return VN == A.VN; }147bool operator!=(const CHIArg &A) const { return !(*this == A); }148};149150using CHIIt = SmallVectorImpl<CHIArg>::iterator;151using CHIArgs = iterator_range<CHIIt>;152using OutValuesType = DenseMap<BasicBlock *, SmallVector<CHIArg, 2>>;153using InValuesType =154DenseMap<BasicBlock *, SmallVector<std::pair<VNType, Instruction *>, 2>>;155156// An invalid value number Used when inserting a single value number into157// VNtoInsns.158enum : uintptr_t { InvalidVN = ~(uintptr_t)2 };159160// Records all scalar instructions candidate for code hoisting.161class InsnInfo {162VNtoInsns VNtoScalars;163164public:165// Inserts I and its value number in VNtoScalars.166void insert(Instruction *I, GVNPass::ValueTable &VN) {167// Scalar instruction.168unsigned V = VN.lookupOrAdd(I);169VNtoScalars[{V, InvalidVN}].push_back(I);170}171172const VNtoInsns &getVNTable() const { return VNtoScalars; }173};174175// Records all load instructions candidate for code hoisting.176class LoadInfo {177VNtoInsns VNtoLoads;178179public:180// Insert Load and the value number of its memory address in VNtoLoads.181void insert(LoadInst *Load, GVNPass::ValueTable &VN) {182if (Load->isSimple()) {183unsigned V = VN.lookupOrAdd(Load->getPointerOperand());184// With opaque pointers we may have loads from the same pointer with185// different result types, which should be disambiguated.186VNtoLoads[{V, (uintptr_t)Load->getType()}].push_back(Load);187}188}189190const VNtoInsns &getVNTable() const { return VNtoLoads; }191};192193// Records all store instructions candidate for code hoisting.194class StoreInfo {195VNtoInsns VNtoStores;196197public:198// Insert the Store and a hash number of the store address and the stored199// value in VNtoStores.200void insert(StoreInst *Store, GVNPass::ValueTable &VN) {201if (!Store->isSimple())202return;203// Hash the store address and the stored value.204Value *Ptr = Store->getPointerOperand();205Value *Val = Store->getValueOperand();206VNtoStores[{VN.lookupOrAdd(Ptr), VN.lookupOrAdd(Val)}].push_back(Store);207}208209const VNtoInsns &getVNTable() const { return VNtoStores; }210};211212// Records all call instructions candidate for code hoisting.213class CallInfo {214VNtoInsns VNtoCallsScalars;215VNtoInsns VNtoCallsLoads;216VNtoInsns VNtoCallsStores;217218public:219// Insert Call and its value numbering in one of the VNtoCalls* containers.220void insert(CallInst *Call, GVNPass::ValueTable &VN) {221// A call that doesNotAccessMemory is handled as a Scalar,222// onlyReadsMemory will be handled as a Load instruction,223// all other calls will be handled as stores.224unsigned V = VN.lookupOrAdd(Call);225auto Entry = std::make_pair(V, InvalidVN);226227if (Call->doesNotAccessMemory())228VNtoCallsScalars[Entry].push_back(Call);229else if (Call->onlyReadsMemory())230VNtoCallsLoads[Entry].push_back(Call);231else232VNtoCallsStores[Entry].push_back(Call);233}234235const VNtoInsns &getScalarVNTable() const { return VNtoCallsScalars; }236const VNtoInsns &getLoadVNTable() const { return VNtoCallsLoads; }237const VNtoInsns &getStoreVNTable() const { return VNtoCallsStores; }238};239240// This pass hoists common computations across branches sharing common241// dominator. The primary goal is to reduce the code size, and in some242// cases reduce critical path (by exposing more ILP).243class GVNHoist {244public:245GVNHoist(DominatorTree *DT, PostDominatorTree *PDT, AliasAnalysis *AA,246MemoryDependenceResults *MD, MemorySSA *MSSA)247: DT(DT), PDT(PDT), AA(AA), MD(MD), MSSA(MSSA),248MSSAUpdater(std::make_unique<MemorySSAUpdater>(MSSA)) {249MSSA->ensureOptimizedUses();250}251252bool run(Function &F);253254// Copied from NewGVN.cpp255// This function provides global ranking of operations so that we can place256// them in a canonical order. Note that rank alone is not necessarily enough257// for a complete ordering, as constants all have the same rank. However,258// generally, we will simplify an operation with all constants so that it259// doesn't matter what order they appear in.260unsigned int rank(const Value *V) const;261262private:263GVNPass::ValueTable VN;264DominatorTree *DT;265PostDominatorTree *PDT;266AliasAnalysis *AA;267MemoryDependenceResults *MD;268MemorySSA *MSSA;269std::unique_ptr<MemorySSAUpdater> MSSAUpdater;270DenseMap<const Value *, unsigned> DFSNumber;271BBSideEffectsSet BBSideEffects;272DenseSet<const BasicBlock *> HoistBarrier;273SmallVector<BasicBlock *, 32> IDFBlocks;274unsigned NumFuncArgs;275const bool HoistingGeps = false;276277enum InsKind { Unknown, Scalar, Load, Store };278279// Return true when there are exception handling in BB.280bool hasEH(const BasicBlock *BB);281282// Return true when I1 appears before I2 in the instructions of BB.283bool firstInBB(const Instruction *I1, const Instruction *I2) {284assert(I1->getParent() == I2->getParent());285unsigned I1DFS = DFSNumber.lookup(I1);286unsigned I2DFS = DFSNumber.lookup(I2);287assert(I1DFS && I2DFS);288return I1DFS < I2DFS;289}290291// Return true when there are memory uses of Def in BB.292bool hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,293const BasicBlock *BB);294295bool hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,296int &NBBsOnAllPaths);297298// Return true when there are exception handling or loads of memory Def299// between Def and NewPt. This function is only called for stores: Def is300// the MemoryDef of the store to be hoisted.301302// Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and303// return true when the counter NBBsOnAllPaths reaces 0, except when it is304// initialized to -1 which is unlimited.305bool hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,306int &NBBsOnAllPaths);307308// Return true when there are exception handling between HoistPt and BB.309// Decrement by 1 NBBsOnAllPaths for each block between HoistPt and BB, and310// return true when the counter NBBsOnAllPaths reaches 0, except when it is311// initialized to -1 which is unlimited.312bool hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,313int &NBBsOnAllPaths);314315// Return true when it is safe to hoist a memory load or store U from OldPt316// to NewPt.317bool safeToHoistLdSt(const Instruction *NewPt, const Instruction *OldPt,318MemoryUseOrDef *U, InsKind K, int &NBBsOnAllPaths);319320// Return true when it is safe to hoist scalar instructions from all blocks in321// WL to HoistBB.322bool safeToHoistScalar(const BasicBlock *HoistBB, const BasicBlock *BB,323int &NBBsOnAllPaths) {324return !hasEHOnPath(HoistBB, BB, NBBsOnAllPaths);325}326327// In the inverse CFG, the dominance frontier of basic block (BB) is the328// point where ANTIC needs to be computed for instructions which are going329// to be hoisted. Since this point does not change during gvn-hoist,330// we compute it only once (on demand).331// The ides is inspired from:332// "Partial Redundancy Elimination in SSA Form"333// ROBERT KENNEDY, SUN CHAN, SHIN-MING LIU, RAYMOND LO, PENG TU and FRED CHOW334// They use similar idea in the forward graph to find fully redundant and335// partially redundant expressions, here it is used in the inverse graph to336// find fully anticipable instructions at merge point (post-dominator in337// the inverse CFG).338// Returns the edge via which an instruction in BB will get the values from.339340// Returns true when the values are flowing out to each edge.341bool valueAnticipable(CHIArgs C, Instruction *TI) const;342343// Check if it is safe to hoist values tracked by CHI in the range344// [Begin, End) and accumulate them in Safe.345void checkSafety(CHIArgs C, BasicBlock *BB, InsKind K,346SmallVectorImpl<CHIArg> &Safe);347348using RenameStackType = DenseMap<VNType, SmallVector<Instruction *, 2>>;349350// Push all the VNs corresponding to BB into RenameStack.351void fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs,352RenameStackType &RenameStack);353354void fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs,355RenameStackType &RenameStack);356357// Walk the post-dominator tree top-down and use a stack for each value to358// store the last value you see. When you hit a CHI from a given edge, the359// value to use as the argument is at the top of the stack, add the value to360// CHI and pop.361void insertCHI(InValuesType &ValueBBs, OutValuesType &CHIBBs) {362auto Root = PDT->getNode(nullptr);363if (!Root)364return;365// Depth first walk on PDom tree to fill the CHIargs at each PDF.366for (auto *Node : depth_first(Root)) {367BasicBlock *BB = Node->getBlock();368if (!BB)369continue;370371RenameStackType RenameStack;372// Collect all values in BB and push to stack.373fillRenameStack(BB, ValueBBs, RenameStack);374375// Fill outgoing values in each CHI corresponding to BB.376fillChiArgs(BB, CHIBBs, RenameStack);377}378}379380// Walk all the CHI-nodes to find ones which have a empty-entry and remove381// them Then collect all the instructions which are safe to hoist and see if382// they form a list of anticipable values. OutValues contains CHIs383// corresponding to each basic block.384void findHoistableCandidates(OutValuesType &CHIBBs, InsKind K,385HoistingPointList &HPL);386387// Compute insertion points for each values which can be fully anticipated at388// a dominator. HPL contains all such values.389void computeInsertionPoints(const VNtoInsns &Map, HoistingPointList &HPL,390InsKind K) {391// Sort VNs based on their rankings392std::vector<VNType> Ranks;393for (const auto &Entry : Map) {394Ranks.push_back(Entry.first);395}396397// TODO: Remove fully-redundant expressions.398// Get instruction from the Map, assume that all the Instructions399// with same VNs have same rank (this is an approximation).400llvm::sort(Ranks, [this, &Map](const VNType &r1, const VNType &r2) {401return (rank(*Map.lookup(r1).begin()) < rank(*Map.lookup(r2).begin()));402});403404// - Sort VNs according to their rank, and start with lowest ranked VN405// - Take a VN and for each instruction with same VN406// - Find the dominance frontier in the inverse graph (PDF)407// - Insert the chi-node at PDF408// - Remove the chi-nodes with missing entries409// - Remove values from CHI-nodes which do not truly flow out, e.g.,410// modified along the path.411// - Collect the remaining values that are still anticipable412SmallVector<BasicBlock *, 2> IDFBlocks;413ReverseIDFCalculator IDFs(*PDT);414OutValuesType OutValue;415InValuesType InValue;416for (const auto &R : Ranks) {417const SmallVecInsn &V = Map.lookup(R);418if (V.size() < 2)419continue;420const VNType &VN = R;421SmallPtrSet<BasicBlock *, 2> VNBlocks;422for (const auto &I : V) {423BasicBlock *BBI = I->getParent();424if (!hasEH(BBI))425VNBlocks.insert(BBI);426}427// Compute the Post Dominance Frontiers of each basic block428// The dominance frontier of a live block X in the reverse429// control graph is the set of blocks upon which X is control430// dependent. The following sequence computes the set of blocks431// which currently have dead terminators that are control432// dependence sources of a block which is in NewLiveBlocks.433IDFs.setDefiningBlocks(VNBlocks);434IDFBlocks.clear();435IDFs.calculate(IDFBlocks);436437// Make a map of BB vs instructions to be hoisted.438for (unsigned i = 0; i < V.size(); ++i) {439InValue[V[i]->getParent()].push_back(std::make_pair(VN, V[i]));440}441// Insert empty CHI node for this VN. This is used to factor out442// basic blocks where the ANTIC can potentially change.443CHIArg EmptyChi = {VN, nullptr, nullptr};444for (auto *IDFBB : IDFBlocks) {445for (unsigned i = 0; i < V.size(); ++i) {446// Ignore spurious PDFs.447if (DT->properlyDominates(IDFBB, V[i]->getParent())) {448OutValue[IDFBB].push_back(EmptyChi);449LLVM_DEBUG(dbgs() << "\nInserting a CHI for BB: "450<< IDFBB->getName() << ", for Insn: " << *V[i]);451}452}453}454}455456// Insert CHI args at each PDF to iterate on factored graph of457// control dependence.458insertCHI(InValue, OutValue);459// Using the CHI args inserted at each PDF, find fully anticipable values.460findHoistableCandidates(OutValue, K, HPL);461}462463// Return true when all operands of Instr are available at insertion point464// HoistPt. When limiting the number of hoisted expressions, one could hoist465// a load without hoisting its access function. So before hoisting any466// expression, make sure that all its operands are available at insert point.467bool allOperandsAvailable(const Instruction *I,468const BasicBlock *HoistPt) const;469470// Same as allOperandsAvailable with recursive check for GEP operands.471bool allGepOperandsAvailable(const Instruction *I,472const BasicBlock *HoistPt) const;473474// Make all operands of the GEP available.475void makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,476const SmallVecInsn &InstructionsToHoist,477Instruction *Gep) const;478479void updateAlignment(Instruction *I, Instruction *Repl);480481// Remove all the instructions in Candidates and replace their usage with482// Repl. Returns the number of instructions removed.483unsigned rauw(const SmallVecInsn &Candidates, Instruction *Repl,484MemoryUseOrDef *NewMemAcc);485486// Replace all Memory PHI usage with NewMemAcc.487void raMPHIuw(MemoryUseOrDef *NewMemAcc);488489// Remove all other instructions and replace them with Repl.490unsigned removeAndReplace(const SmallVecInsn &Candidates, Instruction *Repl,491BasicBlock *DestBB, bool MoveAccess);492493// In the case Repl is a load or a store, we make all their GEPs494// available: GEPs are not hoisted by default to avoid the address495// computations to be hoisted without the associated load or store.496bool makeGepOperandsAvailable(Instruction *Repl, BasicBlock *HoistPt,497const SmallVecInsn &InstructionsToHoist) const;498499std::pair<unsigned, unsigned> hoist(HoistingPointList &HPL);500501// Hoist all expressions. Returns Number of scalars hoisted502// and number of non-scalars hoisted.503std::pair<unsigned, unsigned> hoistExpressions(Function &F);504};505506bool GVNHoist::run(Function &F) {507NumFuncArgs = F.arg_size();508VN.setDomTree(DT);509VN.setAliasAnalysis(AA);510VN.setMemDep(MD);511bool Res = false;512// Perform DFS Numbering of instructions.513unsigned BBI = 0;514for (const BasicBlock *BB : depth_first(&F.getEntryBlock())) {515DFSNumber[BB] = ++BBI;516unsigned I = 0;517for (const auto &Inst : *BB)518DFSNumber[&Inst] = ++I;519}520521int ChainLength = 0;522523// FIXME: use lazy evaluation of VN to avoid the fix-point computation.524while (true) {525if (MaxChainLength != -1 && ++ChainLength >= MaxChainLength)526return Res;527528auto HoistStat = hoistExpressions(F);529if (HoistStat.first + HoistStat.second == 0)530return Res;531532if (HoistStat.second > 0)533// To address a limitation of the current GVN, we need to rerun the534// hoisting after we hoisted loads or stores in order to be able to535// hoist all scalars dependent on the hoisted ld/st.536VN.clear();537538Res = true;539}540541return Res;542}543544unsigned int GVNHoist::rank(const Value *V) const {545// Prefer constants to undef to anything else546// Undef is a constant, have to check it first.547// Prefer smaller constants to constantexprs548if (isa<ConstantExpr>(V))549return 2;550if (isa<UndefValue>(V))551return 1;552if (isa<Constant>(V))553return 0;554else if (auto *A = dyn_cast<Argument>(V))555return 3 + A->getArgNo();556557// Need to shift the instruction DFS by number of arguments + 3 to account558// for the constant and argument ranking above.559auto Result = DFSNumber.lookup(V);560if (Result > 0)561return 4 + NumFuncArgs + Result;562// Unreachable or something else, just return a really large number.563return ~0;564}565566bool GVNHoist::hasEH(const BasicBlock *BB) {567auto It = BBSideEffects.find(BB);568if (It != BBSideEffects.end())569return It->second;570571if (BB->isEHPad() || BB->hasAddressTaken()) {572BBSideEffects[BB] = true;573return true;574}575576if (BB->getTerminator()->mayThrow()) {577BBSideEffects[BB] = true;578return true;579}580581BBSideEffects[BB] = false;582return false;583}584585bool GVNHoist::hasMemoryUse(const Instruction *NewPt, MemoryDef *Def,586const BasicBlock *BB) {587const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);588if (!Acc)589return false;590591Instruction *OldPt = Def->getMemoryInst();592const BasicBlock *OldBB = OldPt->getParent();593const BasicBlock *NewBB = NewPt->getParent();594bool ReachedNewPt = false;595596for (const MemoryAccess &MA : *Acc)597if (const MemoryUse *MU = dyn_cast<MemoryUse>(&MA)) {598Instruction *Insn = MU->getMemoryInst();599600// Do not check whether MU aliases Def when MU occurs after OldPt.601if (BB == OldBB && firstInBB(OldPt, Insn))602break;603604// Do not check whether MU aliases Def when MU occurs before NewPt.605if (BB == NewBB) {606if (!ReachedNewPt) {607if (firstInBB(Insn, NewPt))608continue;609ReachedNewPt = true;610}611}612if (MemorySSAUtil::defClobbersUseOrDef(Def, MU, *AA))613return true;614}615616return false;617}618619bool GVNHoist::hasEHhelper(const BasicBlock *BB, const BasicBlock *SrcBB,620int &NBBsOnAllPaths) {621// Stop walk once the limit is reached.622if (NBBsOnAllPaths == 0)623return true;624625// Impossible to hoist with exceptions on the path.626if (hasEH(BB))627return true;628629// No such instruction after HoistBarrier in a basic block was630// selected for hoisting so instructions selected within basic block with631// a hoist barrier can be hoisted.632if ((BB != SrcBB) && HoistBarrier.count(BB))633return true;634635return false;636}637638bool GVNHoist::hasEHOrLoadsOnPath(const Instruction *NewPt, MemoryDef *Def,639int &NBBsOnAllPaths) {640const BasicBlock *NewBB = NewPt->getParent();641const BasicBlock *OldBB = Def->getBlock();642assert(DT->dominates(NewBB, OldBB) && "invalid path");643assert(DT->dominates(Def->getDefiningAccess()->getBlock(), NewBB) &&644"def does not dominate new hoisting point");645646// Walk all basic blocks reachable in depth-first iteration on the inverse647// CFG from OldBB to NewBB. These blocks are all the blocks that may be648// executed between the execution of NewBB and OldBB. Hoisting an expression649// from OldBB into NewBB has to be safe on all execution paths.650for (auto I = idf_begin(OldBB), E = idf_end(OldBB); I != E;) {651const BasicBlock *BB = *I;652if (BB == NewBB) {653// Stop traversal when reaching HoistPt.654I.skipChildren();655continue;656}657658if (hasEHhelper(BB, OldBB, NBBsOnAllPaths))659return true;660661// Check that we do not move a store past loads.662if (hasMemoryUse(NewPt, Def, BB))663return true;664665// -1 is unlimited number of blocks on all paths.666if (NBBsOnAllPaths != -1)667--NBBsOnAllPaths;668669++I;670}671672return false;673}674675bool GVNHoist::hasEHOnPath(const BasicBlock *HoistPt, const BasicBlock *SrcBB,676int &NBBsOnAllPaths) {677assert(DT->dominates(HoistPt, SrcBB) && "Invalid path");678679// Walk all basic blocks reachable in depth-first iteration on680// the inverse CFG from BBInsn to NewHoistPt. These blocks are all the681// blocks that may be executed between the execution of NewHoistPt and682// BBInsn. Hoisting an expression from BBInsn into NewHoistPt has to be safe683// on all execution paths.684for (auto I = idf_begin(SrcBB), E = idf_end(SrcBB); I != E;) {685const BasicBlock *BB = *I;686if (BB == HoistPt) {687// Stop traversal when reaching NewHoistPt.688I.skipChildren();689continue;690}691692if (hasEHhelper(BB, SrcBB, NBBsOnAllPaths))693return true;694695// -1 is unlimited number of blocks on all paths.696if (NBBsOnAllPaths != -1)697--NBBsOnAllPaths;698699++I;700}701702return false;703}704705bool GVNHoist::safeToHoistLdSt(const Instruction *NewPt,706const Instruction *OldPt, MemoryUseOrDef *U,707GVNHoist::InsKind K, int &NBBsOnAllPaths) {708// In place hoisting is safe.709if (NewPt == OldPt)710return true;711712const BasicBlock *NewBB = NewPt->getParent();713const BasicBlock *OldBB = OldPt->getParent();714const BasicBlock *UBB = U->getBlock();715716// Check for dependences on the Memory SSA.717MemoryAccess *D = U->getDefiningAccess();718BasicBlock *DBB = D->getBlock();719if (DT->properlyDominates(NewBB, DBB))720// Cannot move the load or store to NewBB above its definition in DBB.721return false;722723if (NewBB == DBB && !MSSA->isLiveOnEntryDef(D))724if (auto *UD = dyn_cast<MemoryUseOrDef>(D))725if (!firstInBB(UD->getMemoryInst(), NewPt))726// Cannot move the load or store to NewPt above its definition in D.727return false;728729// Check for unsafe hoistings due to side effects.730if (K == InsKind::Store) {731if (hasEHOrLoadsOnPath(NewPt, cast<MemoryDef>(U), NBBsOnAllPaths))732return false;733} else if (hasEHOnPath(NewBB, OldBB, NBBsOnAllPaths))734return false;735736if (UBB == NewBB) {737if (DT->properlyDominates(DBB, NewBB))738return true;739assert(UBB == DBB);740assert(MSSA->locallyDominates(D, U));741}742743// No side effects: it is safe to hoist.744return true;745}746747bool GVNHoist::valueAnticipable(CHIArgs C, Instruction *TI) const {748if (TI->getNumSuccessors() > (unsigned)size(C))749return false; // Not enough args in this CHI.750751for (auto CHI : C) {752// Find if all the edges have values flowing out of BB.753if (!llvm::is_contained(successors(TI), CHI.Dest))754return false;755}756return true;757}758759void GVNHoist::checkSafety(CHIArgs C, BasicBlock *BB, GVNHoist::InsKind K,760SmallVectorImpl<CHIArg> &Safe) {761int NumBBsOnAllPaths = MaxNumberOfBBSInPath;762const Instruction *T = BB->getTerminator();763for (auto CHI : C) {764Instruction *Insn = CHI.I;765if (!Insn) // No instruction was inserted in this CHI.766continue;767// If the Terminator is some kind of "exotic terminator" that produces a768// value (such as InvokeInst, CallBrInst, or CatchSwitchInst) which the CHI769// uses, it is not safe to hoist the use above the def.770if (!T->use_empty() && is_contained(Insn->operands(), cast<const Value>(T)))771continue;772if (K == InsKind::Scalar) {773if (safeToHoistScalar(BB, Insn->getParent(), NumBBsOnAllPaths))774Safe.push_back(CHI);775} else {776if (MemoryUseOrDef *UD = MSSA->getMemoryAccess(Insn))777if (safeToHoistLdSt(T, Insn, UD, K, NumBBsOnAllPaths))778Safe.push_back(CHI);779}780}781}782783void GVNHoist::fillRenameStack(BasicBlock *BB, InValuesType &ValueBBs,784GVNHoist::RenameStackType &RenameStack) {785auto it1 = ValueBBs.find(BB);786if (it1 != ValueBBs.end()) {787// Iterate in reverse order to keep lower ranked values on the top.788LLVM_DEBUG(dbgs() << "\nVisiting: " << BB->getName()789<< " for pushing instructions on stack";);790for (std::pair<VNType, Instruction *> &VI : reverse(it1->second)) {791// Get the value of instruction I792LLVM_DEBUG(dbgs() << "\nPushing on stack: " << *VI.second);793RenameStack[VI.first].push_back(VI.second);794}795}796}797798void GVNHoist::fillChiArgs(BasicBlock *BB, OutValuesType &CHIBBs,799GVNHoist::RenameStackType &RenameStack) {800// For each *predecessor* (because Post-DOM) of BB check if it has a CHI801for (auto *Pred : predecessors(BB)) {802auto P = CHIBBs.find(Pred);803if (P == CHIBBs.end()) {804continue;805}806LLVM_DEBUG(dbgs() << "\nLooking at CHIs in: " << Pred->getName(););807// A CHI is found (BB -> Pred is an edge in the CFG)808// Pop the stack until Top(V) = Ve.809auto &VCHI = P->second;810for (auto It = VCHI.begin(), E = VCHI.end(); It != E;) {811CHIArg &C = *It;812if (!C.Dest) {813auto si = RenameStack.find(C.VN);814// The Basic Block where CHI is must dominate the value we want to815// track in a CHI. In the PDom walk, there can be values in the816// stack which are not control dependent e.g., nested loop.817if (si != RenameStack.end() && si->second.size() &&818DT->properlyDominates(Pred, si->second.back()->getParent())) {819C.Dest = BB; // Assign the edge820C.I = si->second.pop_back_val(); // Assign the argument821LLVM_DEBUG(dbgs()822<< "\nCHI Inserted in BB: " << C.Dest->getName() << *C.I823<< ", VN: " << C.VN.first << ", " << C.VN.second);824}825// Move to next CHI of a different value826It = std::find_if(It, VCHI.end(), [It](CHIArg &A) { return A != *It; });827} else828++It;829}830}831}832833void GVNHoist::findHoistableCandidates(OutValuesType &CHIBBs,834GVNHoist::InsKind K,835HoistingPointList &HPL) {836auto cmpVN = [](const CHIArg &A, const CHIArg &B) { return A.VN < B.VN; };837838// CHIArgs now have the outgoing values, so check for anticipability and839// accumulate hoistable candidates in HPL.840for (std::pair<BasicBlock *, SmallVector<CHIArg, 2>> &A : CHIBBs) {841BasicBlock *BB = A.first;842SmallVectorImpl<CHIArg> &CHIs = A.second;843// Vector of PHIs contains PHIs for different instructions.844// Sort the args according to their VNs, such that identical845// instructions are together.846llvm::stable_sort(CHIs, cmpVN);847auto TI = BB->getTerminator();848auto B = CHIs.begin();849// [PreIt, PHIIt) form a range of CHIs which have identical VNs.850auto PHIIt = llvm::find_if(CHIs, [B](CHIArg &A) { return A != *B; });851auto PrevIt = CHIs.begin();852while (PrevIt != PHIIt) {853// Collect values which satisfy safety checks.854SmallVector<CHIArg, 2> Safe;855// We check for safety first because there might be multiple values in856// the same path, some of which are not safe to be hoisted, but overall857// each edge has at least one value which can be hoisted, making the858// value anticipable along that path.859checkSafety(make_range(PrevIt, PHIIt), BB, K, Safe);860861// List of safe values should be anticipable at TI.862if (valueAnticipable(make_range(Safe.begin(), Safe.end()), TI)) {863HPL.push_back({BB, SmallVecInsn()});864SmallVecInsn &V = HPL.back().second;865for (auto B : Safe)866V.push_back(B.I);867}868869// Check other VNs870PrevIt = PHIIt;871PHIIt = std::find_if(PrevIt, CHIs.end(),872[PrevIt](CHIArg &A) { return A != *PrevIt; });873}874}875}876877bool GVNHoist::allOperandsAvailable(const Instruction *I,878const BasicBlock *HoistPt) const {879for (const Use &Op : I->operands())880if (const auto *Inst = dyn_cast<Instruction>(&Op))881if (!DT->dominates(Inst->getParent(), HoistPt))882return false;883884return true;885}886887bool GVNHoist::allGepOperandsAvailable(const Instruction *I,888const BasicBlock *HoistPt) const {889for (const Use &Op : I->operands())890if (const auto *Inst = dyn_cast<Instruction>(&Op))891if (!DT->dominates(Inst->getParent(), HoistPt)) {892if (const GetElementPtrInst *GepOp =893dyn_cast<GetElementPtrInst>(Inst)) {894if (!allGepOperandsAvailable(GepOp, HoistPt))895return false;896// Gep is available if all operands of GepOp are available.897} else {898// Gep is not available if it has operands other than GEPs that are899// defined in blocks not dominating HoistPt.900return false;901}902}903return true;904}905906void GVNHoist::makeGepsAvailable(Instruction *Repl, BasicBlock *HoistPt,907const SmallVecInsn &InstructionsToHoist,908Instruction *Gep) const {909assert(allGepOperandsAvailable(Gep, HoistPt) && "GEP operands not available");910911Instruction *ClonedGep = Gep->clone();912for (unsigned i = 0, e = Gep->getNumOperands(); i != e; ++i)913if (Instruction *Op = dyn_cast<Instruction>(Gep->getOperand(i))) {914// Check whether the operand is already available.915if (DT->dominates(Op->getParent(), HoistPt))916continue;917918// As a GEP can refer to other GEPs, recursively make all the operands919// of this GEP available at HoistPt.920if (GetElementPtrInst *GepOp = dyn_cast<GetElementPtrInst>(Op))921makeGepsAvailable(ClonedGep, HoistPt, InstructionsToHoist, GepOp);922}923924// Copy Gep and replace its uses in Repl with ClonedGep.925ClonedGep->insertBefore(HoistPt->getTerminator());926927// Conservatively discard any optimization hints, they may differ on the928// other paths.929ClonedGep->dropUnknownNonDebugMetadata();930931// If we have optimization hints which agree with each other along different932// paths, preserve them.933for (const Instruction *OtherInst : InstructionsToHoist) {934const GetElementPtrInst *OtherGep;935if (auto *OtherLd = dyn_cast<LoadInst>(OtherInst))936OtherGep = cast<GetElementPtrInst>(OtherLd->getPointerOperand());937else938OtherGep = cast<GetElementPtrInst>(939cast<StoreInst>(OtherInst)->getPointerOperand());940ClonedGep->andIRFlags(OtherGep);941942// Merge debug locations of GEPs, because the hoisted GEP replaces those943// in branches. When cloning, ClonedGep preserves the debug location of944// Gepd, so Gep is skipped to avoid merging it twice.945if (OtherGep != Gep) {946ClonedGep->applyMergedLocation(ClonedGep->getDebugLoc(),947OtherGep->getDebugLoc());948}949}950951// Replace uses of Gep with ClonedGep in Repl.952Repl->replaceUsesOfWith(Gep, ClonedGep);953}954955void GVNHoist::updateAlignment(Instruction *I, Instruction *Repl) {956if (auto *ReplacementLoad = dyn_cast<LoadInst>(Repl)) {957ReplacementLoad->setAlignment(958std::min(ReplacementLoad->getAlign(), cast<LoadInst>(I)->getAlign()));959++NumLoadsRemoved;960} else if (auto *ReplacementStore = dyn_cast<StoreInst>(Repl)) {961ReplacementStore->setAlignment(962std::min(ReplacementStore->getAlign(), cast<StoreInst>(I)->getAlign()));963++NumStoresRemoved;964} else if (auto *ReplacementAlloca = dyn_cast<AllocaInst>(Repl)) {965ReplacementAlloca->setAlignment(std::max(ReplacementAlloca->getAlign(),966cast<AllocaInst>(I)->getAlign()));967} else if (isa<CallInst>(Repl)) {968++NumCallsRemoved;969}970}971972unsigned GVNHoist::rauw(const SmallVecInsn &Candidates, Instruction *Repl,973MemoryUseOrDef *NewMemAcc) {974unsigned NR = 0;975for (Instruction *I : Candidates) {976if (I != Repl) {977++NR;978updateAlignment(I, Repl);979if (NewMemAcc) {980// Update the uses of the old MSSA access with NewMemAcc.981MemoryAccess *OldMA = MSSA->getMemoryAccess(I);982OldMA->replaceAllUsesWith(NewMemAcc);983MSSAUpdater->removeMemoryAccess(OldMA);984}985986combineMetadataForCSE(Repl, I, true);987Repl->andIRFlags(I);988I->replaceAllUsesWith(Repl);989// Also invalidate the Alias Analysis cache.990MD->removeInstruction(I);991I->eraseFromParent();992}993}994return NR;995}996997void GVNHoist::raMPHIuw(MemoryUseOrDef *NewMemAcc) {998SmallPtrSet<MemoryPhi *, 4> UsePhis;999for (User *U : NewMemAcc->users())1000if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(U))1001UsePhis.insert(Phi);10021003for (MemoryPhi *Phi : UsePhis) {1004auto In = Phi->incoming_values();1005if (llvm::all_of(In, [&](Use &U) { return U == NewMemAcc; })) {1006Phi->replaceAllUsesWith(NewMemAcc);1007MSSAUpdater->removeMemoryAccess(Phi);1008}1009}1010}10111012unsigned GVNHoist::removeAndReplace(const SmallVecInsn &Candidates,1013Instruction *Repl, BasicBlock *DestBB,1014bool MoveAccess) {1015MemoryUseOrDef *NewMemAcc = MSSA->getMemoryAccess(Repl);1016if (MoveAccess && NewMemAcc) {1017// The definition of this ld/st will not change: ld/st hoisting is1018// legal when the ld/st is not moved past its current definition.1019MSSAUpdater->moveToPlace(NewMemAcc, DestBB, MemorySSA::BeforeTerminator);1020}10211022// Replace all other instructions with Repl with memory access NewMemAcc.1023unsigned NR = rauw(Candidates, Repl, NewMemAcc);10241025// Remove MemorySSA phi nodes with the same arguments.1026if (NewMemAcc)1027raMPHIuw(NewMemAcc);1028return NR;1029}10301031bool GVNHoist::makeGepOperandsAvailable(1032Instruction *Repl, BasicBlock *HoistPt,1033const SmallVecInsn &InstructionsToHoist) const {1034// Check whether the GEP of a ld/st can be synthesized at HoistPt.1035GetElementPtrInst *Gep = nullptr;1036Instruction *Val = nullptr;1037if (auto *Ld = dyn_cast<LoadInst>(Repl)) {1038Gep = dyn_cast<GetElementPtrInst>(Ld->getPointerOperand());1039} else if (auto *St = dyn_cast<StoreInst>(Repl)) {1040Gep = dyn_cast<GetElementPtrInst>(St->getPointerOperand());1041Val = dyn_cast<Instruction>(St->getValueOperand());1042// Check that the stored value is available.1043if (Val) {1044if (isa<GetElementPtrInst>(Val)) {1045// Check whether we can compute the GEP at HoistPt.1046if (!allGepOperandsAvailable(Val, HoistPt))1047return false;1048} else if (!DT->dominates(Val->getParent(), HoistPt))1049return false;1050}1051}10521053// Check whether we can compute the Gep at HoistPt.1054if (!Gep || !allGepOperandsAvailable(Gep, HoistPt))1055return false;10561057makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Gep);10581059if (Val && isa<GetElementPtrInst>(Val))1060makeGepsAvailable(Repl, HoistPt, InstructionsToHoist, Val);10611062return true;1063}10641065std::pair<unsigned, unsigned> GVNHoist::hoist(HoistingPointList &HPL) {1066unsigned NI = 0, NL = 0, NS = 0, NC = 0, NR = 0;1067for (const HoistingPointInfo &HP : HPL) {1068// Find out whether we already have one of the instructions in HoistPt,1069// in which case we do not have to move it.1070BasicBlock *DestBB = HP.first;1071const SmallVecInsn &InstructionsToHoist = HP.second;1072Instruction *Repl = nullptr;1073for (Instruction *I : InstructionsToHoist)1074if (I->getParent() == DestBB)1075// If there are two instructions in HoistPt to be hoisted in place:1076// update Repl to be the first one, such that we can rename the uses1077// of the second based on the first.1078if (!Repl || firstInBB(I, Repl))1079Repl = I;10801081// Keep track of whether we moved the instruction so we know whether we1082// should move the MemoryAccess.1083bool MoveAccess = true;1084if (Repl) {1085// Repl is already in HoistPt: it remains in place.1086assert(allOperandsAvailable(Repl, DestBB) &&1087"instruction depends on operands that are not available");1088MoveAccess = false;1089} else {1090// When we do not find Repl in HoistPt, select the first in the list1091// and move it to HoistPt.1092Repl = InstructionsToHoist.front();10931094// We can move Repl in HoistPt only when all operands are available.1095// The order in which hoistings are done may influence the availability1096// of operands.1097if (!allOperandsAvailable(Repl, DestBB)) {1098// When HoistingGeps there is nothing more we can do to make the1099// operands available: just continue.1100if (HoistingGeps)1101continue;11021103// When not HoistingGeps we need to copy the GEPs.1104if (!makeGepOperandsAvailable(Repl, DestBB, InstructionsToHoist))1105continue;1106}11071108// Move the instruction at the end of HoistPt.1109Instruction *Last = DestBB->getTerminator();1110MD->removeInstruction(Repl);1111Repl->moveBefore(Last);11121113DFSNumber[Repl] = DFSNumber[Last]++;1114}11151116// Drop debug location as per debug info update guide.1117Repl->dropLocation();1118NR += removeAndReplace(InstructionsToHoist, Repl, DestBB, MoveAccess);11191120if (isa<LoadInst>(Repl))1121++NL;1122else if (isa<StoreInst>(Repl))1123++NS;1124else if (isa<CallInst>(Repl))1125++NC;1126else // Scalar1127++NI;1128}11291130if (MSSA && VerifyMemorySSA)1131MSSA->verifyMemorySSA();11321133NumHoisted += NL + NS + NC + NI;1134NumRemoved += NR;1135NumLoadsHoisted += NL;1136NumStoresHoisted += NS;1137NumCallsHoisted += NC;1138return {NI, NL + NC + NS};1139}11401141std::pair<unsigned, unsigned> GVNHoist::hoistExpressions(Function &F) {1142InsnInfo II;1143LoadInfo LI;1144StoreInfo SI;1145CallInfo CI;1146for (BasicBlock *BB : depth_first(&F.getEntryBlock())) {1147int InstructionNb = 0;1148for (Instruction &I1 : *BB) {1149// If I1 cannot guarantee progress, subsequent instructions1150// in BB cannot be hoisted anyways.1151if (!isGuaranteedToTransferExecutionToSuccessor(&I1)) {1152HoistBarrier.insert(BB);1153break;1154}1155// Only hoist the first instructions in BB up to MaxDepthInBB. Hoisting1156// deeper may increase the register pressure and compilation time.1157if (MaxDepthInBB != -1 && InstructionNb++ >= MaxDepthInBB)1158break;11591160// Do not value number terminator instructions.1161if (I1.isTerminator())1162break;11631164if (auto *Load = dyn_cast<LoadInst>(&I1))1165LI.insert(Load, VN);1166else if (auto *Store = dyn_cast<StoreInst>(&I1))1167SI.insert(Store, VN);1168else if (auto *Call = dyn_cast<CallInst>(&I1)) {1169if (auto *Intr = dyn_cast<IntrinsicInst>(Call)) {1170if (isa<DbgInfoIntrinsic>(Intr) ||1171Intr->getIntrinsicID() == Intrinsic::assume ||1172Intr->getIntrinsicID() == Intrinsic::sideeffect)1173continue;1174}1175if (Call->mayHaveSideEffects())1176break;11771178if (Call->isConvergent())1179break;11801181CI.insert(Call, VN);1182} else if (HoistingGeps || !isa<GetElementPtrInst>(&I1))1183// Do not hoist scalars past calls that may write to memory because1184// that could result in spills later. geps are handled separately.1185// TODO: We can relax this for targets like AArch64 as they have more1186// registers than X86.1187II.insert(&I1, VN);1188}1189}11901191HoistingPointList HPL;1192computeInsertionPoints(II.getVNTable(), HPL, InsKind::Scalar);1193computeInsertionPoints(LI.getVNTable(), HPL, InsKind::Load);1194computeInsertionPoints(SI.getVNTable(), HPL, InsKind::Store);1195computeInsertionPoints(CI.getScalarVNTable(), HPL, InsKind::Scalar);1196computeInsertionPoints(CI.getLoadVNTable(), HPL, InsKind::Load);1197computeInsertionPoints(CI.getStoreVNTable(), HPL, InsKind::Store);1198return hoist(HPL);1199}12001201} // end namespace llvm12021203PreservedAnalyses GVNHoistPass::run(Function &F, FunctionAnalysisManager &AM) {1204DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(F);1205PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(F);1206AliasAnalysis &AA = AM.getResult<AAManager>(F);1207MemoryDependenceResults &MD = AM.getResult<MemoryDependenceAnalysis>(F);1208MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(F).getMSSA();1209GVNHoist G(&DT, &PDT, &AA, &MD, &MSSA);1210if (!G.run(F))1211return PreservedAnalyses::all();12121213PreservedAnalyses PA;1214PA.preserve<DominatorTreeAnalysis>();1215PA.preserve<MemorySSAAnalysis>();1216return PA;1217}121812191220