Path: blob/main/contrib/llvm-project/llvm/lib/Target/Hexagon/HexagonCommonGEP.cpp
35266 views
//===- HexagonCommonGEP.cpp -----------------------------------------------===//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//===----------------------------------------------------------------------===//78#include "llvm/ADT/ArrayRef.h"9#include "llvm/ADT/FoldingSet.h"10#include "llvm/ADT/GraphTraits.h"11#include "llvm/ADT/STLExtras.h"12#include "llvm/ADT/SetVector.h"13#include "llvm/ADT/SmallVector.h"14#include "llvm/ADT/StringRef.h"15#include "llvm/Analysis/LoopInfo.h"16#include "llvm/Analysis/PostDominators.h"17#include "llvm/IR/BasicBlock.h"18#include "llvm/IR/Constant.h"19#include "llvm/IR/Constants.h"20#include "llvm/IR/DerivedTypes.h"21#include "llvm/IR/Dominators.h"22#include "llvm/IR/Function.h"23#include "llvm/IR/Instruction.h"24#include "llvm/IR/Instructions.h"25#include "llvm/IR/Type.h"26#include "llvm/IR/Use.h"27#include "llvm/IR/User.h"28#include "llvm/IR/Value.h"29#include "llvm/IR/Verifier.h"30#include "llvm/InitializePasses.h"31#include "llvm/Pass.h"32#include "llvm/Support/Allocator.h"33#include "llvm/Support/Casting.h"34#include "llvm/Support/CommandLine.h"35#include "llvm/Support/Compiler.h"36#include "llvm/Support/Debug.h"37#include "llvm/Support/raw_ostream.h"38#include "llvm/Transforms/Utils/Local.h"39#include <algorithm>40#include <cassert>41#include <cstddef>42#include <cstdint>43#include <iterator>44#include <map>45#include <set>46#include <utility>47#include <vector>4849#define DEBUG_TYPE "commgep"5051using namespace llvm;5253static cl::opt<bool> OptSpeculate("commgep-speculate", cl::init(true),54cl::Hidden);5556static cl::opt<bool> OptEnableInv("commgep-inv", cl::init(true), cl::Hidden);5758static cl::opt<bool> OptEnableConst("commgep-const", cl::init(true),59cl::Hidden);6061namespace llvm {6263void initializeHexagonCommonGEPPass(PassRegistry&);6465} // end namespace llvm6667namespace {6869struct GepNode;70using NodeSet = std::set<GepNode *>;71using NodeToValueMap = std::map<GepNode *, Value *>;72using NodeVect = std::vector<GepNode *>;73using NodeChildrenMap = std::map<GepNode *, NodeVect>;74using UseSet = SetVector<Use *>;75using NodeToUsesMap = std::map<GepNode *, UseSet>;7677// Numbering map for gep nodes. Used to keep track of ordering for78// gep nodes.79struct NodeOrdering {80NodeOrdering() = default;8182void insert(const GepNode *N) { Map.insert(std::make_pair(N, ++LastNum)); }83void clear() { Map.clear(); }8485bool operator()(const GepNode *N1, const GepNode *N2) const {86auto F1 = Map.find(N1), F2 = Map.find(N2);87assert(F1 != Map.end() && F2 != Map.end());88return F1->second < F2->second;89}9091private:92std::map<const GepNode *, unsigned> Map;93unsigned LastNum = 0;94};9596class HexagonCommonGEP : public FunctionPass {97public:98static char ID;99100HexagonCommonGEP() : FunctionPass(ID) {101initializeHexagonCommonGEPPass(*PassRegistry::getPassRegistry());102}103104bool runOnFunction(Function &F) override;105StringRef getPassName() const override { return "Hexagon Common GEP"; }106107void getAnalysisUsage(AnalysisUsage &AU) const override {108AU.addRequired<DominatorTreeWrapperPass>();109AU.addPreserved<DominatorTreeWrapperPass>();110AU.addRequired<PostDominatorTreeWrapperPass>();111AU.addPreserved<PostDominatorTreeWrapperPass>();112AU.addRequired<LoopInfoWrapperPass>();113AU.addPreserved<LoopInfoWrapperPass>();114FunctionPass::getAnalysisUsage(AU);115}116117private:118using ValueToNodeMap = std::map<Value *, GepNode *>;119using ValueVect = std::vector<Value *>;120using NodeToValuesMap = std::map<GepNode *, ValueVect>;121122void getBlockTraversalOrder(BasicBlock *Root, ValueVect &Order);123bool isHandledGepForm(GetElementPtrInst *GepI);124void processGepInst(GetElementPtrInst *GepI, ValueToNodeMap &NM);125void collect();126void common();127128BasicBlock *recalculatePlacement(GepNode *Node, NodeChildrenMap &NCM,129NodeToValueMap &Loc);130BasicBlock *recalculatePlacementRec(GepNode *Node, NodeChildrenMap &NCM,131NodeToValueMap &Loc);132bool isInvariantIn(Value *Val, Loop *L);133bool isInvariantIn(GepNode *Node, Loop *L);134bool isInMainPath(BasicBlock *B, Loop *L);135BasicBlock *adjustForInvariance(GepNode *Node, NodeChildrenMap &NCM,136NodeToValueMap &Loc);137void separateChainForNode(GepNode *Node, Use *U, NodeToValueMap &Loc);138void separateConstantChains(GepNode *Node, NodeChildrenMap &NCM,139NodeToValueMap &Loc);140void computeNodePlacement(NodeToValueMap &Loc);141142Value *fabricateGEP(NodeVect &NA, BasicBlock::iterator At,143BasicBlock *LocB);144void getAllUsersForNode(GepNode *Node, ValueVect &Values,145NodeChildrenMap &NCM);146void materialize(NodeToValueMap &Loc);147148void removeDeadCode();149150NodeVect Nodes;151NodeToUsesMap Uses;152NodeOrdering NodeOrder; // Node ordering, for deterministic behavior.153SpecificBumpPtrAllocator<GepNode> *Mem;154LLVMContext *Ctx;155LoopInfo *LI;156DominatorTree *DT;157PostDominatorTree *PDT;158Function *Fn;159};160161} // end anonymous namespace162163char HexagonCommonGEP::ID = 0;164165INITIALIZE_PASS_BEGIN(HexagonCommonGEP, "hcommgep", "Hexagon Common GEP",166false, false)167INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)168INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)169INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)170INITIALIZE_PASS_END(HexagonCommonGEP, "hcommgep", "Hexagon Common GEP",171false, false)172173namespace {174175struct GepNode {176enum {177None = 0,178Root = 0x01,179Internal = 0x02,180Used = 0x04,181InBounds = 0x08,182Pointer = 0x10, // See note below.183};184// Note: GEP indices generally traverse nested types, and so a GepNode185// (representing a single index) can be associated with some composite186// type. The exception is the GEP input, which is a pointer, and not187// a composite type (at least not in the sense of having sub-types).188// Also, the corresponding index plays a different role as well: it is189// simply added to the input pointer. Since pointer types are becoming190// opaque (i.e. are no longer going to include the pointee type), the191// two pieces of information (1) the fact that it's a pointer, and192// (2) the pointee type, need to be stored separately. The pointee type193// will be stored in the PTy member, while the fact that the node194// operates on a pointer will be reflected by the flag "Pointer".195196uint32_t Flags = 0;197union {198GepNode *Parent;199Value *BaseVal;200};201Value *Idx = nullptr;202Type *PTy = nullptr; // Type indexed by this node. For pointer nodes203// this is the "pointee" type, and indexing a204// pointer does not change the type.205206GepNode() : Parent(nullptr) {}207GepNode(const GepNode *N) : Flags(N->Flags), Idx(N->Idx), PTy(N->PTy) {208if (Flags & Root)209BaseVal = N->BaseVal;210else211Parent = N->Parent;212}213214friend raw_ostream &operator<< (raw_ostream &OS, const GepNode &GN);215};216217raw_ostream &operator<< (raw_ostream &OS, const GepNode &GN) {218OS << "{ {";219bool Comma = false;220if (GN.Flags & GepNode::Root) {221OS << "root";222Comma = true;223}224if (GN.Flags & GepNode::Internal) {225if (Comma)226OS << ',';227OS << "internal";228Comma = true;229}230if (GN.Flags & GepNode::Used) {231if (Comma)232OS << ',';233OS << "used";234}235if (GN.Flags & GepNode::InBounds) {236if (Comma)237OS << ',';238OS << "inbounds";239}240if (GN.Flags & GepNode::Pointer) {241if (Comma)242OS << ',';243OS << "pointer";244}245OS << "} ";246if (GN.Flags & GepNode::Root)247OS << "BaseVal:" << GN.BaseVal->getName() << '(' << GN.BaseVal << ')';248else249OS << "Parent:" << GN.Parent;250251OS << " Idx:";252if (ConstantInt *CI = dyn_cast<ConstantInt>(GN.Idx))253OS << CI->getValue().getSExtValue();254else if (GN.Idx->hasName())255OS << GN.Idx->getName();256else257OS << "<anon> =" << *GN.Idx;258259OS << " PTy:";260if (GN.PTy->isStructTy()) {261StructType *STy = cast<StructType>(GN.PTy);262if (!STy->isLiteral())263OS << GN.PTy->getStructName();264else265OS << "<anon-struct>:" << *STy;266}267else268OS << *GN.PTy;269OS << " }";270return OS;271}272273template <typename NodeContainer>274void dump_node_container(raw_ostream &OS, const NodeContainer &S) {275using const_iterator = typename NodeContainer::const_iterator;276277for (const_iterator I = S.begin(), E = S.end(); I != E; ++I)278OS << *I << ' ' << **I << '\n';279}280281raw_ostream &operator<< (raw_ostream &OS,282const NodeVect &S) LLVM_ATTRIBUTE_UNUSED;283raw_ostream &operator<< (raw_ostream &OS, const NodeVect &S) {284dump_node_container(OS, S);285return OS;286}287288raw_ostream &operator<< (raw_ostream &OS,289const NodeToUsesMap &M) LLVM_ATTRIBUTE_UNUSED;290raw_ostream &operator<< (raw_ostream &OS, const NodeToUsesMap &M){291for (const auto &I : M) {292const UseSet &Us = I.second;293OS << I.first << " -> #" << Us.size() << '{';294for (const Use *U : Us) {295User *R = U->getUser();296if (R->hasName())297OS << ' ' << R->getName();298else299OS << " <?>(" << *R << ')';300}301OS << " }\n";302}303return OS;304}305306struct in_set {307in_set(const NodeSet &S) : NS(S) {}308309bool operator() (GepNode *N) const {310return NS.find(N) != NS.end();311}312313private:314const NodeSet &NS;315};316317} // end anonymous namespace318319inline void *operator new(size_t, SpecificBumpPtrAllocator<GepNode> &A) {320return A.Allocate();321}322323void HexagonCommonGEP::getBlockTraversalOrder(BasicBlock *Root,324ValueVect &Order) {325// Compute block ordering for a typical DT-based traversal of the flow326// graph: "before visiting a block, all of its dominators must have been327// visited".328329Order.push_back(Root);330for (auto *DTN : children<DomTreeNode*>(DT->getNode(Root)))331getBlockTraversalOrder(DTN->getBlock(), Order);332}333334bool HexagonCommonGEP::isHandledGepForm(GetElementPtrInst *GepI) {335// No vector GEPs.336if (!GepI->getType()->isPointerTy())337return false;338// No GEPs without any indices. (Is this possible?)339if (GepI->idx_begin() == GepI->idx_end())340return false;341return true;342}343344void HexagonCommonGEP::processGepInst(GetElementPtrInst *GepI,345ValueToNodeMap &NM) {346LLVM_DEBUG(dbgs() << "Visiting GEP: " << *GepI << '\n');347GepNode *N = new (*Mem) GepNode;348Value *PtrOp = GepI->getPointerOperand();349uint32_t InBounds = GepI->isInBounds() ? GepNode::InBounds : 0;350ValueToNodeMap::iterator F = NM.find(PtrOp);351if (F == NM.end()) {352N->BaseVal = PtrOp;353N->Flags |= GepNode::Root | InBounds;354} else {355// If PtrOp was a GEP instruction, it must have already been processed.356// The ValueToNodeMap entry for it is the last gep node in the generated357// chain. Link to it here.358N->Parent = F->second;359}360N->PTy = GepI->getSourceElementType();361N->Flags |= GepNode::Pointer;362N->Idx = *GepI->idx_begin();363364// Collect the list of users of this GEP instruction. Will add it to the365// last node created for it.366UseSet Us;367for (Value::user_iterator UI = GepI->user_begin(), UE = GepI->user_end();368UI != UE; ++UI) {369// Check if this gep is used by anything other than other geps that370// we will process.371if (isa<GetElementPtrInst>(*UI)) {372GetElementPtrInst *UserG = cast<GetElementPtrInst>(*UI);373if (isHandledGepForm(UserG))374continue;375}376Us.insert(&UI.getUse());377}378Nodes.push_back(N);379NodeOrder.insert(N);380381// Skip the first index operand, since it was already handled above. This382// dereferences the pointer operand.383GepNode *PN = N;384Type *PtrTy = GepI->getSourceElementType();385for (Use &U : llvm::drop_begin(GepI->indices())) {386Value *Op = U;387GepNode *Nx = new (*Mem) GepNode;388Nx->Parent = PN; // Link Nx to the previous node.389Nx->Flags |= GepNode::Internal | InBounds;390Nx->PTy = PtrTy;391Nx->Idx = Op;392Nodes.push_back(Nx);393NodeOrder.insert(Nx);394PN = Nx;395396PtrTy = GetElementPtrInst::getTypeAtIndex(PtrTy, Op);397}398399// After last node has been created, update the use information.400if (!Us.empty()) {401PN->Flags |= GepNode::Used;402Uses[PN].insert(Us.begin(), Us.end());403}404405// Link the last node with the originating GEP instruction. This is to406// help with linking chained GEP instructions.407NM.insert(std::make_pair(GepI, PN));408}409410void HexagonCommonGEP::collect() {411// Establish depth-first traversal order of the dominator tree.412ValueVect BO;413getBlockTraversalOrder(&Fn->front(), BO);414415// The creation of gep nodes requires DT-traversal. When processing a GEP416// instruction that uses another GEP instruction as the base pointer, the417// gep node for the base pointer should already exist.418ValueToNodeMap NM;419for (Value *I : BO) {420BasicBlock *B = cast<BasicBlock>(I);421for (Instruction &J : *B)422if (auto *GepI = dyn_cast<GetElementPtrInst>(&J))423if (isHandledGepForm(GepI))424processGepInst(GepI, NM);425}426427LLVM_DEBUG(dbgs() << "Gep nodes after initial collection:\n" << Nodes);428}429430static void invert_find_roots(const NodeVect &Nodes, NodeChildrenMap &NCM,431NodeVect &Roots) {432for (GepNode *N : Nodes) {433if (N->Flags & GepNode::Root) {434Roots.push_back(N);435continue;436}437GepNode *PN = N->Parent;438NCM[PN].push_back(N);439}440}441442static void nodes_for_root(GepNode *Root, NodeChildrenMap &NCM,443NodeSet &Nodes) {444NodeVect Work;445Work.push_back(Root);446Nodes.insert(Root);447448while (!Work.empty()) {449NodeVect::iterator First = Work.begin();450GepNode *N = *First;451Work.erase(First);452NodeChildrenMap::iterator CF = NCM.find(N);453if (CF != NCM.end()) {454llvm::append_range(Work, CF->second);455Nodes.insert(CF->second.begin(), CF->second.end());456}457}458}459460namespace {461462using NodeSymRel = std::set<NodeSet>;463using NodePair = std::pair<GepNode *, GepNode *>;464using NodePairSet = std::set<NodePair>;465466} // end anonymous namespace467468static const NodeSet *node_class(GepNode *N, NodeSymRel &Rel) {469for (const NodeSet &S : Rel)470if (S.count(N))471return &S;472return nullptr;473}474475// Create an ordered pair of GepNode pointers. The pair will be used in476// determining equality. The only purpose of the ordering is to eliminate477// duplication due to the commutativity of equality/non-equality.478static NodePair node_pair(GepNode *N1, GepNode *N2) {479uintptr_t P1 = reinterpret_cast<uintptr_t>(N1);480uintptr_t P2 = reinterpret_cast<uintptr_t>(N2);481if (P1 <= P2)482return std::make_pair(N1, N2);483return std::make_pair(N2, N1);484}485486static unsigned node_hash(GepNode *N) {487// Include everything except flags and parent.488FoldingSetNodeID ID;489ID.AddPointer(N->Idx);490ID.AddPointer(N->PTy);491return ID.ComputeHash();492}493494static bool node_eq(GepNode *N1, GepNode *N2, NodePairSet &Eq,495NodePairSet &Ne) {496// Don't cache the result for nodes with different hashes. The hash497// comparison is fast enough.498if (node_hash(N1) != node_hash(N2))499return false;500501NodePair NP = node_pair(N1, N2);502NodePairSet::iterator FEq = Eq.find(NP);503if (FEq != Eq.end())504return true;505NodePairSet::iterator FNe = Ne.find(NP);506if (FNe != Ne.end())507return false;508// Not previously compared.509bool Root1 = N1->Flags & GepNode::Root;510uint32_t CmpFlags = GepNode::Root | GepNode::Pointer;511bool Different = (N1->Flags & CmpFlags) != (N2->Flags & CmpFlags);512NodePair P = node_pair(N1, N2);513// If the root/pointer flags have different values, the nodes are514// different.515// If both nodes are root nodes, but their base pointers differ,516// they are different.517if (Different || (Root1 && N1->BaseVal != N2->BaseVal)) {518Ne.insert(P);519return false;520}521// Here the root/pointer flags are identical, and for root nodes the522// base pointers are equal, so the root nodes are equal.523// For non-root nodes, compare their parent nodes.524if (Root1 || node_eq(N1->Parent, N2->Parent, Eq, Ne)) {525Eq.insert(P);526return true;527}528return false;529}530531void HexagonCommonGEP::common() {532// The essence of this commoning is finding gep nodes that are equal.533// To do this we need to compare all pairs of nodes. To save time,534// first, partition the set of all nodes into sets of potentially equal535// nodes, and then compare pairs from within each partition.536using NodeSetMap = std::map<unsigned, NodeSet>;537NodeSetMap MaybeEq;538539for (GepNode *N : Nodes) {540unsigned H = node_hash(N);541MaybeEq[H].insert(N);542}543544// Compute the equivalence relation for the gep nodes. Use two caches,545// one for equality and the other for non-equality.546NodeSymRel EqRel; // Equality relation (as set of equivalence classes).547NodePairSet Eq, Ne; // Caches.548for (auto &I : MaybeEq) {549NodeSet &S = I.second;550for (NodeSet::iterator NI = S.begin(), NE = S.end(); NI != NE; ++NI) {551GepNode *N = *NI;552// If node already has a class, then the class must have been created553// in a prior iteration of this loop. Since equality is transitive,554// nothing more will be added to that class, so skip it.555if (node_class(N, EqRel))556continue;557558// Create a new class candidate now.559NodeSet C;560for (NodeSet::iterator NJ = std::next(NI); NJ != NE; ++NJ)561if (node_eq(N, *NJ, Eq, Ne))562C.insert(*NJ);563// If Tmp is empty, N would be the only element in it. Don't bother564// creating a class for it then.565if (!C.empty()) {566C.insert(N); // Finalize the set before adding it to the relation.567std::pair<NodeSymRel::iterator, bool> Ins = EqRel.insert(C);568(void)Ins;569assert(Ins.second && "Cannot add a class");570}571}572}573574LLVM_DEBUG({575dbgs() << "Gep node equality:\n";576for (NodePairSet::iterator I = Eq.begin(), E = Eq.end(); I != E; ++I)577dbgs() << "{ " << I->first << ", " << I->second << " }\n";578579dbgs() << "Gep equivalence classes:\n";580for (const NodeSet &S : EqRel) {581dbgs() << '{';582for (NodeSet::const_iterator J = S.begin(), F = S.end(); J != F; ++J) {583if (J != S.begin())584dbgs() << ',';585dbgs() << ' ' << *J;586}587dbgs() << " }\n";588}589});590591// Create a projection from a NodeSet to the minimal element in it.592using ProjMap = std::map<const NodeSet *, GepNode *>;593ProjMap PM;594for (const NodeSet &S : EqRel) {595GepNode *Min = *llvm::min_element(S, NodeOrder);596std::pair<ProjMap::iterator,bool> Ins = PM.insert(std::make_pair(&S, Min));597(void)Ins;598assert(Ins.second && "Cannot add minimal element");599600// Update the min element's flags, and user list.601uint32_t Flags = 0;602UseSet &MinUs = Uses[Min];603for (GepNode *N : S) {604uint32_t NF = N->Flags;605// If N is used, append all original values of N to the list of606// original values of Min.607if (NF & GepNode::Used)608MinUs.insert(Uses[N].begin(), Uses[N].end());609Flags |= NF;610}611if (MinUs.empty())612Uses.erase(Min);613614// The collected flags should include all the flags from the min element.615assert((Min->Flags & Flags) == Min->Flags);616Min->Flags = Flags;617}618619// Commoning: for each non-root gep node, replace "Parent" with the620// selected (minimum) node from the corresponding equivalence class.621// If a given parent does not have an equivalence class, leave it622// unchanged (it means that it's the only element in its class).623for (GepNode *N : Nodes) {624if (N->Flags & GepNode::Root)625continue;626const NodeSet *PC = node_class(N->Parent, EqRel);627if (!PC)628continue;629ProjMap::iterator F = PM.find(PC);630if (F == PM.end())631continue;632// Found a replacement, use it.633GepNode *Rep = F->second;634N->Parent = Rep;635}636637LLVM_DEBUG(dbgs() << "Gep nodes after commoning:\n" << Nodes);638639// Finally, erase the nodes that are no longer used.640NodeSet Erase;641for (GepNode *N : Nodes) {642const NodeSet *PC = node_class(N, EqRel);643if (!PC)644continue;645ProjMap::iterator F = PM.find(PC);646if (F == PM.end())647continue;648if (N == F->second)649continue;650// Node for removal.651Erase.insert(N);652}653erase_if(Nodes, in_set(Erase));654655LLVM_DEBUG(dbgs() << "Gep nodes after post-commoning cleanup:\n" << Nodes);656}657658template <typename T>659static BasicBlock *nearest_common_dominator(DominatorTree *DT, T &Blocks) {660LLVM_DEBUG({661dbgs() << "NCD of {";662for (typename T::iterator I = Blocks.begin(), E = Blocks.end(); I != E;663++I) {664if (!*I)665continue;666BasicBlock *B = cast<BasicBlock>(*I);667dbgs() << ' ' << B->getName();668}669dbgs() << " }\n";670});671672// Allow null basic blocks in Blocks. In such cases, return nullptr.673typename T::iterator I = Blocks.begin(), E = Blocks.end();674if (I == E || !*I)675return nullptr;676BasicBlock *Dom = cast<BasicBlock>(*I);677while (++I != E) {678BasicBlock *B = cast_or_null<BasicBlock>(*I);679Dom = B ? DT->findNearestCommonDominator(Dom, B) : nullptr;680if (!Dom)681return nullptr;682}683LLVM_DEBUG(dbgs() << "computed:" << Dom->getName() << '\n');684return Dom;685}686687template <typename T>688static BasicBlock *nearest_common_dominatee(DominatorTree *DT, T &Blocks) {689// If two blocks, A and B, dominate a block C, then A dominates B,690// or B dominates A.691typename T::iterator I = Blocks.begin(), E = Blocks.end();692// Find the first non-null block.693while (I != E && !*I)694++I;695if (I == E)696return DT->getRoot();697BasicBlock *DomB = cast<BasicBlock>(*I);698while (++I != E) {699if (!*I)700continue;701BasicBlock *B = cast<BasicBlock>(*I);702if (DT->dominates(B, DomB))703continue;704if (!DT->dominates(DomB, B))705return nullptr;706DomB = B;707}708return DomB;709}710711// Find the first use in B of any value from Values. If no such use,712// return B->end().713template <typename T>714static BasicBlock::iterator first_use_of_in_block(T &Values, BasicBlock *B) {715BasicBlock::iterator FirstUse = B->end(), BEnd = B->end();716717using iterator = typename T::iterator;718719for (iterator I = Values.begin(), E = Values.end(); I != E; ++I) {720Value *V = *I;721// If V is used in a PHI node, the use belongs to the incoming block,722// not the block with the PHI node. In the incoming block, the use723// would be considered as being at the end of it, so it cannot724// influence the position of the first use (which is assumed to be725// at the end to start with).726if (isa<PHINode>(V))727continue;728if (!isa<Instruction>(V))729continue;730Instruction *In = cast<Instruction>(V);731if (In->getParent() != B)732continue;733BasicBlock::iterator It = In->getIterator();734if (std::distance(FirstUse, BEnd) < std::distance(It, BEnd))735FirstUse = It;736}737return FirstUse;738}739740static bool is_empty(const BasicBlock *B) {741return B->empty() || (&*B->begin() == B->getTerminator());742}743744BasicBlock *HexagonCommonGEP::recalculatePlacement(GepNode *Node,745NodeChildrenMap &NCM, NodeToValueMap &Loc) {746LLVM_DEBUG(dbgs() << "Loc for node:" << Node << '\n');747// Recalculate the placement for Node, assuming that the locations of748// its children in Loc are valid.749// Return nullptr if there is no valid placement for Node (for example, it750// uses an index value that is not available at the location required751// to dominate all children, etc.).752753// Find the nearest common dominator for:754// - all users, if the node is used, and755// - all children.756ValueVect Bs;757if (Node->Flags & GepNode::Used) {758// Append all blocks with uses of the original values to the759// block vector Bs.760NodeToUsesMap::iterator UF = Uses.find(Node);761assert(UF != Uses.end() && "Used node with no use information");762UseSet &Us = UF->second;763for (Use *U : Us) {764User *R = U->getUser();765if (!isa<Instruction>(R))766continue;767BasicBlock *PB = isa<PHINode>(R)768? cast<PHINode>(R)->getIncomingBlock(*U)769: cast<Instruction>(R)->getParent();770Bs.push_back(PB);771}772}773// Append the location of each child.774NodeChildrenMap::iterator CF = NCM.find(Node);775if (CF != NCM.end()) {776NodeVect &Cs = CF->second;777for (GepNode *CN : Cs) {778NodeToValueMap::iterator LF = Loc.find(CN);779// If the child is only used in GEP instructions (i.e. is not used in780// non-GEP instructions), the nearest dominator computed for it may781// have been null. In such case it won't have a location available.782if (LF == Loc.end())783continue;784Bs.push_back(LF->second);785}786}787788BasicBlock *DomB = nearest_common_dominator(DT, Bs);789if (!DomB)790return nullptr;791// Check if the index used by Node dominates the computed dominator.792Instruction *IdxI = dyn_cast<Instruction>(Node->Idx);793if (IdxI && !DT->dominates(IdxI->getParent(), DomB))794return nullptr;795796// Avoid putting nodes into empty blocks.797while (is_empty(DomB)) {798DomTreeNode *N = (*DT)[DomB]->getIDom();799if (!N)800break;801DomB = N->getBlock();802}803804// Otherwise, DomB is fine. Update the location map.805Loc[Node] = DomB;806return DomB;807}808809BasicBlock *HexagonCommonGEP::recalculatePlacementRec(GepNode *Node,810NodeChildrenMap &NCM, NodeToValueMap &Loc) {811LLVM_DEBUG(dbgs() << "LocRec begin for node:" << Node << '\n');812// Recalculate the placement of Node, after recursively recalculating the813// placements of all its children.814NodeChildrenMap::iterator CF = NCM.find(Node);815if (CF != NCM.end()) {816NodeVect &Cs = CF->second;817for (GepNode *C : Cs)818recalculatePlacementRec(C, NCM, Loc);819}820BasicBlock *LB = recalculatePlacement(Node, NCM, Loc);821LLVM_DEBUG(dbgs() << "LocRec end for node:" << Node << '\n');822return LB;823}824825bool HexagonCommonGEP::isInvariantIn(Value *Val, Loop *L) {826if (isa<Constant>(Val) || isa<Argument>(Val))827return true;828Instruction *In = dyn_cast<Instruction>(Val);829if (!In)830return false;831BasicBlock *HdrB = L->getHeader(), *DefB = In->getParent();832return DT->properlyDominates(DefB, HdrB);833}834835bool HexagonCommonGEP::isInvariantIn(GepNode *Node, Loop *L) {836if (Node->Flags & GepNode::Root)837if (!isInvariantIn(Node->BaseVal, L))838return false;839return isInvariantIn(Node->Idx, L);840}841842bool HexagonCommonGEP::isInMainPath(BasicBlock *B, Loop *L) {843BasicBlock *HB = L->getHeader();844BasicBlock *LB = L->getLoopLatch();845// B must post-dominate the loop header or dominate the loop latch.846if (PDT->dominates(B, HB))847return true;848if (LB && DT->dominates(B, LB))849return true;850return false;851}852853static BasicBlock *preheader(DominatorTree *DT, Loop *L) {854if (BasicBlock *PH = L->getLoopPreheader())855return PH;856if (!OptSpeculate)857return nullptr;858DomTreeNode *DN = DT->getNode(L->getHeader());859if (!DN)860return nullptr;861return DN->getIDom()->getBlock();862}863864BasicBlock *HexagonCommonGEP::adjustForInvariance(GepNode *Node,865NodeChildrenMap &NCM, NodeToValueMap &Loc) {866// Find the "topmost" location for Node: it must be dominated by both,867// its parent (or the BaseVal, if it's a root node), and by the index868// value.869ValueVect Bs;870if (Node->Flags & GepNode::Root) {871if (Instruction *PIn = dyn_cast<Instruction>(Node->BaseVal))872Bs.push_back(PIn->getParent());873} else {874Bs.push_back(Loc[Node->Parent]);875}876if (Instruction *IIn = dyn_cast<Instruction>(Node->Idx))877Bs.push_back(IIn->getParent());878BasicBlock *TopB = nearest_common_dominatee(DT, Bs);879880// Traverse the loop nest upwards until we find a loop in which Node881// is no longer invariant, or until we get to the upper limit of Node's882// placement. The traversal will also stop when a suitable "preheader"883// cannot be found for a given loop. The "preheader" may actually be884// a regular block outside of the loop (i.e. not guarded), in which case885// the Node will be speculated.886// For nodes that are not in the main path of the containing loop (i.e.887// are not executed in each iteration), do not move them out of the loop.888BasicBlock *LocB = cast_or_null<BasicBlock>(Loc[Node]);889if (LocB) {890Loop *Lp = LI->getLoopFor(LocB);891while (Lp) {892if (!isInvariantIn(Node, Lp) || !isInMainPath(LocB, Lp))893break;894BasicBlock *NewLoc = preheader(DT, Lp);895if (!NewLoc || !DT->dominates(TopB, NewLoc))896break;897Lp = Lp->getParentLoop();898LocB = NewLoc;899}900}901Loc[Node] = LocB;902903// Recursively compute the locations of all children nodes.904NodeChildrenMap::iterator CF = NCM.find(Node);905if (CF != NCM.end()) {906NodeVect &Cs = CF->second;907for (GepNode *C : Cs)908adjustForInvariance(C, NCM, Loc);909}910return LocB;911}912913namespace {914915struct LocationAsBlock {916LocationAsBlock(const NodeToValueMap &L) : Map(L) {}917918const NodeToValueMap ⤅919};920921raw_ostream &operator<< (raw_ostream &OS,922const LocationAsBlock &Loc) LLVM_ATTRIBUTE_UNUSED ;923raw_ostream &operator<< (raw_ostream &OS, const LocationAsBlock &Loc) {924for (const auto &I : Loc.Map) {925OS << I.first << " -> ";926if (BasicBlock *B = cast_or_null<BasicBlock>(I.second))927OS << B->getName() << '(' << B << ')';928else929OS << "<null-block>";930OS << '\n';931}932return OS;933}934935inline bool is_constant(GepNode *N) {936return isa<ConstantInt>(N->Idx);937}938939} // end anonymous namespace940941void HexagonCommonGEP::separateChainForNode(GepNode *Node, Use *U,942NodeToValueMap &Loc) {943User *R = U->getUser();944LLVM_DEBUG(dbgs() << "Separating chain for node (" << Node << ") user: " << *R945<< '\n');946BasicBlock *PB = cast<Instruction>(R)->getParent();947948GepNode *N = Node;949GepNode *C = nullptr, *NewNode = nullptr;950while (is_constant(N) && !(N->Flags & GepNode::Root)) {951// XXX if (single-use) dont-replicate;952GepNode *NewN = new (*Mem) GepNode(N);953Nodes.push_back(NewN);954Loc[NewN] = PB;955956if (N == Node)957NewNode = NewN;958NewN->Flags &= ~GepNode::Used;959if (C)960C->Parent = NewN;961C = NewN;962N = N->Parent;963}964if (!NewNode)965return;966967// Move over all uses that share the same user as U from Node to NewNode.968NodeToUsesMap::iterator UF = Uses.find(Node);969assert(UF != Uses.end());970UseSet &Us = UF->second;971UseSet NewUs;972for (Use *U : Us) {973if (U->getUser() == R)974NewUs.insert(U);975}976for (Use *U : NewUs)977Us.remove(U); // erase takes an iterator.978979if (Us.empty()) {980Node->Flags &= ~GepNode::Used;981Uses.erase(UF);982}983984// Should at least have U in NewUs.985NewNode->Flags |= GepNode::Used;986LLVM_DEBUG(dbgs() << "new node: " << NewNode << " " << *NewNode << '\n');987assert(!NewUs.empty());988Uses[NewNode] = NewUs;989}990991void HexagonCommonGEP::separateConstantChains(GepNode *Node,992NodeChildrenMap &NCM, NodeToValueMap &Loc) {993// First approximation: extract all chains.994NodeSet Ns;995nodes_for_root(Node, NCM, Ns);996997LLVM_DEBUG(dbgs() << "Separating constant chains for node: " << Node << '\n');998// Collect all used nodes together with the uses from loads and stores,999// where the GEP node could be folded into the load/store instruction.1000NodeToUsesMap FNs; // Foldable nodes.1001for (GepNode *N : Ns) {1002if (!(N->Flags & GepNode::Used))1003continue;1004NodeToUsesMap::iterator UF = Uses.find(N);1005assert(UF != Uses.end());1006UseSet &Us = UF->second;1007// Loads/stores that use the node N.1008UseSet LSs;1009for (Use *U : Us) {1010User *R = U->getUser();1011// We're interested in uses that provide the address. It can happen1012// that the value may also be provided via GEP, but we won't handle1013// those cases here for now.1014if (LoadInst *Ld = dyn_cast<LoadInst>(R)) {1015unsigned PtrX = LoadInst::getPointerOperandIndex();1016if (&Ld->getOperandUse(PtrX) == U)1017LSs.insert(U);1018} else if (StoreInst *St = dyn_cast<StoreInst>(R)) {1019unsigned PtrX = StoreInst::getPointerOperandIndex();1020if (&St->getOperandUse(PtrX) == U)1021LSs.insert(U);1022}1023}1024// Even if the total use count is 1, separating the chain may still be1025// beneficial, since the constant chain may be longer than the GEP alone1026// would be (e.g. if the parent node has a constant index and also has1027// other children).1028if (!LSs.empty())1029FNs.insert(std::make_pair(N, LSs));1030}10311032LLVM_DEBUG(dbgs() << "Nodes with foldable users:\n" << FNs);10331034for (auto &FN : FNs) {1035GepNode *N = FN.first;1036UseSet &Us = FN.second;1037for (Use *U : Us)1038separateChainForNode(N, U, Loc);1039}1040}10411042void HexagonCommonGEP::computeNodePlacement(NodeToValueMap &Loc) {1043// Compute the inverse of the Node.Parent links. Also, collect the set1044// of root nodes.1045NodeChildrenMap NCM;1046NodeVect Roots;1047invert_find_roots(Nodes, NCM, Roots);10481049// Compute the initial placement determined by the users' locations, and1050// the locations of the child nodes.1051for (GepNode *Root : Roots)1052recalculatePlacementRec(Root, NCM, Loc);10531054LLVM_DEBUG(dbgs() << "Initial node placement:\n" << LocationAsBlock(Loc));10551056if (OptEnableInv) {1057for (GepNode *Root : Roots)1058adjustForInvariance(Root, NCM, Loc);10591060LLVM_DEBUG(dbgs() << "Node placement after adjustment for invariance:\n"1061<< LocationAsBlock(Loc));1062}1063if (OptEnableConst) {1064for (GepNode *Root : Roots)1065separateConstantChains(Root, NCM, Loc);1066}1067LLVM_DEBUG(dbgs() << "Node use information:\n" << Uses);10681069// At the moment, there is no further refinement of the initial placement.1070// Such a refinement could include splitting the nodes if they are placed1071// too far from some of its users.10721073LLVM_DEBUG(dbgs() << "Final node placement:\n" << LocationAsBlock(Loc));1074}10751076Value *HexagonCommonGEP::fabricateGEP(NodeVect &NA, BasicBlock::iterator At,1077BasicBlock *LocB) {1078LLVM_DEBUG(dbgs() << "Fabricating GEP in " << LocB->getName()1079<< " for nodes:\n"1080<< NA);1081unsigned Num = NA.size();1082GepNode *RN = NA[0];1083assert((RN->Flags & GepNode::Root) && "Creating GEP for non-root");10841085GetElementPtrInst *NewInst = nullptr;1086Value *Input = RN->BaseVal;1087Type *InpTy = RN->PTy;10881089unsigned Idx = 0;1090do {1091SmallVector<Value*, 4> IdxList;1092// If the type of the input of the first node is not a pointer,1093// we need to add an artificial i32 0 to the indices (because the1094// actual input in the IR will be a pointer).1095if (!(NA[Idx]->Flags & GepNode::Pointer)) {1096Type *Int32Ty = Type::getInt32Ty(*Ctx);1097IdxList.push_back(ConstantInt::get(Int32Ty, 0));1098}10991100// Keep adding indices from NA until we have to stop and generate1101// an "intermediate" GEP.1102while (++Idx <= Num) {1103GepNode *N = NA[Idx-1];1104IdxList.push_back(N->Idx);1105if (Idx < Num) {1106// We have to stop if we reach a pointer.1107if (NA[Idx]->Flags & GepNode::Pointer)1108break;1109}1110}1111NewInst = GetElementPtrInst::Create(InpTy, Input, IdxList, "cgep", At);1112NewInst->setIsInBounds(RN->Flags & GepNode::InBounds);1113LLVM_DEBUG(dbgs() << "new GEP: " << *NewInst << '\n');1114if (Idx < Num) {1115Input = NewInst;1116InpTy = NA[Idx]->PTy;1117}1118} while (Idx <= Num);11191120return NewInst;1121}11221123void HexagonCommonGEP::getAllUsersForNode(GepNode *Node, ValueVect &Values,1124NodeChildrenMap &NCM) {1125NodeVect Work;1126Work.push_back(Node);11271128while (!Work.empty()) {1129NodeVect::iterator First = Work.begin();1130GepNode *N = *First;1131Work.erase(First);1132if (N->Flags & GepNode::Used) {1133NodeToUsesMap::iterator UF = Uses.find(N);1134assert(UF != Uses.end() && "No use information for used node");1135UseSet &Us = UF->second;1136for (const auto &U : Us)1137Values.push_back(U->getUser());1138}1139NodeChildrenMap::iterator CF = NCM.find(N);1140if (CF != NCM.end()) {1141NodeVect &Cs = CF->second;1142llvm::append_range(Work, Cs);1143}1144}1145}11461147void HexagonCommonGEP::materialize(NodeToValueMap &Loc) {1148LLVM_DEBUG(dbgs() << "Nodes before materialization:\n" << Nodes << '\n');1149NodeChildrenMap NCM;1150NodeVect Roots;1151// Compute the inversion again, since computing placement could alter1152// "parent" relation between nodes.1153invert_find_roots(Nodes, NCM, Roots);11541155while (!Roots.empty()) {1156NodeVect::iterator First = Roots.begin();1157GepNode *Root = *First, *Last = *First;1158Roots.erase(First);11591160NodeVect NA; // Nodes to assemble.1161// Append to NA all child nodes up to (and including) the first child1162// that:1163// (1) has more than 1 child, or1164// (2) is used, or1165// (3) has a child located in a different block.1166bool LastUsed = false;1167unsigned LastCN = 0;1168// The location may be null if the computation failed (it can legitimately1169// happen for nodes created from dead GEPs).1170Value *LocV = Loc[Last];1171if (!LocV)1172continue;1173BasicBlock *LastB = cast<BasicBlock>(LocV);1174do {1175NA.push_back(Last);1176LastUsed = (Last->Flags & GepNode::Used);1177if (LastUsed)1178break;1179NodeChildrenMap::iterator CF = NCM.find(Last);1180LastCN = (CF != NCM.end()) ? CF->second.size() : 0;1181if (LastCN != 1)1182break;1183GepNode *Child = CF->second.front();1184BasicBlock *ChildB = cast_or_null<BasicBlock>(Loc[Child]);1185if (ChildB != nullptr && LastB != ChildB)1186break;1187Last = Child;1188} while (true);11891190BasicBlock::iterator InsertAt = LastB->getTerminator()->getIterator();1191if (LastUsed || LastCN > 0) {1192ValueVect Urs;1193getAllUsersForNode(Root, Urs, NCM);1194BasicBlock::iterator FirstUse = first_use_of_in_block(Urs, LastB);1195if (FirstUse != LastB->end())1196InsertAt = FirstUse;1197}11981199// Generate a new instruction for NA.1200Value *NewInst = fabricateGEP(NA, InsertAt, LastB);12011202// Convert all the children of Last node into roots, and append them1203// to the Roots list.1204if (LastCN > 0) {1205NodeVect &Cs = NCM[Last];1206for (GepNode *CN : Cs) {1207CN->Flags &= ~GepNode::Internal;1208CN->Flags |= GepNode::Root;1209CN->BaseVal = NewInst;1210Roots.push_back(CN);1211}1212}12131214// Lastly, if the Last node was used, replace all uses with the new GEP.1215// The uses reference the original GEP values.1216if (LastUsed) {1217NodeToUsesMap::iterator UF = Uses.find(Last);1218assert(UF != Uses.end() && "No use information found");1219UseSet &Us = UF->second;1220for (Use *U : Us)1221U->set(NewInst);1222}1223}1224}12251226void HexagonCommonGEP::removeDeadCode() {1227ValueVect BO;1228BO.push_back(&Fn->front());12291230for (unsigned i = 0; i < BO.size(); ++i) {1231BasicBlock *B = cast<BasicBlock>(BO[i]);1232for (auto *DTN : children<DomTreeNode *>(DT->getNode(B)))1233BO.push_back(DTN->getBlock());1234}12351236for (Value *V : llvm::reverse(BO)) {1237BasicBlock *B = cast<BasicBlock>(V);1238ValueVect Ins;1239for (Instruction &I : llvm::reverse(*B))1240Ins.push_back(&I);1241for (Value *I : Ins) {1242Instruction *In = cast<Instruction>(I);1243if (isInstructionTriviallyDead(In))1244In->eraseFromParent();1245}1246}1247}12481249bool HexagonCommonGEP::runOnFunction(Function &F) {1250if (skipFunction(F))1251return false;12521253// For now bail out on C++ exception handling.1254for (const BasicBlock &BB : F)1255for (const Instruction &I : BB)1256if (isa<InvokeInst>(I) || isa<LandingPadInst>(I))1257return false;12581259Fn = &F;1260DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();1261PDT = &getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();1262LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();1263Ctx = &F.getContext();12641265Nodes.clear();1266Uses.clear();1267NodeOrder.clear();12681269SpecificBumpPtrAllocator<GepNode> Allocator;1270Mem = &Allocator;12711272collect();1273common();12741275NodeToValueMap Loc;1276computeNodePlacement(Loc);1277materialize(Loc);1278removeDeadCode();12791280#ifdef EXPENSIVE_CHECKS1281// Run this only when expensive checks are enabled.1282if (verifyFunction(F, &dbgs()))1283report_fatal_error("Broken function");1284#endif1285return true;1286}12871288namespace llvm {12891290FunctionPass *createHexagonCommonGEP() {1291return new HexagonCommonGEP();1292}12931294} // end namespace llvm129512961297