Path: blob/main/contrib/llvm-project/llvm/lib/Bitcode/Writer/ValueEnumerator.h
35291 views
//===- Bitcode/Writer/ValueEnumerator.h - Number values ---------*- C++ -*-===//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 class gives values and types Unique ID's.9//10//===----------------------------------------------------------------------===//1112#ifndef LLVM_LIB_BITCODE_WRITER_VALUEENUMERATOR_H13#define LLVM_LIB_BITCODE_WRITER_VALUEENUMERATOR_H1415#include "llvm/ADT/ArrayRef.h"16#include "llvm/ADT/DenseMap.h"17#include "llvm/ADT/UniqueVector.h"18#include "llvm/IR/Attributes.h"19#include "llvm/IR/UseListOrder.h"20#include <cassert>21#include <cstdint>22#include <utility>23#include <vector>2425namespace llvm {2627class BasicBlock;28class Comdat;29class DIArgList;30class Function;31class Instruction;32class LocalAsMetadata;33class MDNode;34class Metadata;35class Module;36class NamedMDNode;37class raw_ostream;38class Type;39class Value;40class ValueSymbolTable;4142class ValueEnumerator {43public:44using TypeList = std::vector<Type *>;4546// For each value, we remember its Value* and occurrence frequency.47using ValueList = std::vector<std::pair<const Value *, unsigned>>;4849/// Attribute groups as encoded in bitcode are almost AttributeSets, but they50/// include the AttributeList index, so we have to track that in our map.51using IndexAndAttrSet = std::pair<unsigned, AttributeSet>;5253UseListOrderStack UseListOrders;5455private:56using TypeMapType = DenseMap<Type *, unsigned>;57TypeMapType TypeMap;58TypeList Types;5960using ValueMapType = DenseMap<const Value *, unsigned>;61ValueMapType ValueMap;62ValueList Values;6364using ComdatSetType = UniqueVector<const Comdat *>;65ComdatSetType Comdats;6667std::vector<const Metadata *> MDs;68std::vector<const Metadata *> FunctionMDs;6970/// Index of information about a piece of metadata.71struct MDIndex {72unsigned F = 0; ///< The ID of the function for this metadata, if any.73unsigned ID = 0; ///< The implicit ID of this metadata in bitcode.7475MDIndex() = default;76explicit MDIndex(unsigned F) : F(F) {}7778/// Check if this has a function tag, and it's different from NewF.79bool hasDifferentFunction(unsigned NewF) const { return F && F != NewF; }8081/// Fetch the MD this references out of the given metadata array.82const Metadata *get(ArrayRef<const Metadata *> MDs) const {83assert(ID && "Expected non-zero ID");84assert(ID <= MDs.size() && "Expected valid ID");85return MDs[ID - 1];86}87};8889using MetadataMapType = DenseMap<const Metadata *, MDIndex>;90MetadataMapType MetadataMap;9192/// Range of metadata IDs, as a half-open range.93struct MDRange {94unsigned First = 0;95unsigned Last = 0;9697/// Number of strings in the prefix of the metadata range.98unsigned NumStrings = 0;99100MDRange() = default;101explicit MDRange(unsigned First) : First(First) {}102};103SmallDenseMap<unsigned, MDRange, 1> FunctionMDInfo;104105bool ShouldPreserveUseListOrder;106107using AttributeGroupMapType = DenseMap<IndexAndAttrSet, unsigned>;108AttributeGroupMapType AttributeGroupMap;109std::vector<IndexAndAttrSet> AttributeGroups;110111using AttributeListMapType = DenseMap<AttributeList, unsigned>;112AttributeListMapType AttributeListMap;113std::vector<AttributeList> AttributeLists;114115/// GlobalBasicBlockIDs - This map memoizes the basic block ID's referenced by116/// the "getGlobalBasicBlockID" method.117mutable DenseMap<const BasicBlock*, unsigned> GlobalBasicBlockIDs;118119using InstructionMapType = DenseMap<const Instruction *, unsigned>;120InstructionMapType InstructionMap;121unsigned InstructionCount;122123/// BasicBlocks - This contains all the basic blocks for the currently124/// incorporated function. Their reverse mapping is stored in ValueMap.125std::vector<const BasicBlock*> BasicBlocks;126127/// When a function is incorporated, this is the size of the Values list128/// before incorporation.129unsigned NumModuleValues;130131/// When a function is incorporated, this is the size of the Metadatas list132/// before incorporation.133unsigned NumModuleMDs = 0;134unsigned NumMDStrings = 0;135136unsigned FirstFuncConstantID;137unsigned FirstInstID;138139public:140ValueEnumerator(const Module &M, bool ShouldPreserveUseListOrder);141ValueEnumerator(const ValueEnumerator &) = delete;142ValueEnumerator &operator=(const ValueEnumerator &) = delete;143144void dump() const;145void print(raw_ostream &OS, const ValueMapType &Map, const char *Name) const;146void print(raw_ostream &OS, const MetadataMapType &Map,147const char *Name) const;148149unsigned getValueID(const Value *V) const;150151unsigned getMetadataID(const Metadata *MD) const {152auto ID = getMetadataOrNullID(MD);153assert(ID != 0 && "Metadata not in slotcalculator!");154return ID - 1;155}156157unsigned getMetadataOrNullID(const Metadata *MD) const {158return MetadataMap.lookup(MD).ID;159}160161unsigned numMDs() const { return MDs.size(); }162163bool shouldPreserveUseListOrder() const { return ShouldPreserveUseListOrder; }164165unsigned getTypeID(Type *T) const {166TypeMapType::const_iterator I = TypeMap.find(T);167assert(I != TypeMap.end() && "Type not in ValueEnumerator!");168return I->second-1;169}170171unsigned getInstructionID(const Instruction *I) const;172void setInstructionID(const Instruction *I);173174unsigned getAttributeListID(AttributeList PAL) const {175if (PAL.isEmpty()) return 0; // Null maps to zero.176AttributeListMapType::const_iterator I = AttributeListMap.find(PAL);177assert(I != AttributeListMap.end() && "Attribute not in ValueEnumerator!");178return I->second;179}180181unsigned getAttributeGroupID(IndexAndAttrSet Group) const {182if (!Group.second.hasAttributes())183return 0; // Null maps to zero.184AttributeGroupMapType::const_iterator I = AttributeGroupMap.find(Group);185assert(I != AttributeGroupMap.end() && "Attribute not in ValueEnumerator!");186return I->second;187}188189/// getFunctionConstantRange - Return the range of values that corresponds to190/// function-local constants.191void getFunctionConstantRange(unsigned &Start, unsigned &End) const {192Start = FirstFuncConstantID;193End = FirstInstID;194}195196const ValueList &getValues() const { return Values; }197198/// Check whether the current block has any metadata to emit.199bool hasMDs() const { return NumModuleMDs < MDs.size(); }200201/// Get the MDString metadata for this block.202ArrayRef<const Metadata *> getMDStrings() const {203return ArrayRef(MDs).slice(NumModuleMDs, NumMDStrings);204}205206/// Get the non-MDString metadata for this block.207ArrayRef<const Metadata *> getNonMDStrings() const {208return ArrayRef(MDs).slice(NumModuleMDs).slice(NumMDStrings);209}210211const TypeList &getTypes() const { return Types; }212213const std::vector<const BasicBlock*> &getBasicBlocks() const {214return BasicBlocks;215}216217const std::vector<AttributeList> &getAttributeLists() const { return AttributeLists; }218219const std::vector<IndexAndAttrSet> &getAttributeGroups() const {220return AttributeGroups;221}222223const ComdatSetType &getComdats() const { return Comdats; }224unsigned getComdatID(const Comdat *C) const;225226/// getGlobalBasicBlockID - This returns the function-specific ID for the227/// specified basic block. This is relatively expensive information, so it228/// should only be used by rare constructs such as address-of-label.229unsigned getGlobalBasicBlockID(const BasicBlock *BB) const;230231/// incorporateFunction/purgeFunction - If you'd like to deal with a function,232/// use these two methods to get its data into the ValueEnumerator!233void incorporateFunction(const Function &F);234235void purgeFunction();236uint64_t computeBitsRequiredForTypeIndices() const;237238private:239void OptimizeConstants(unsigned CstStart, unsigned CstEnd);240241/// Reorder the reachable metadata.242///243/// This is not just an optimization, but is mandatory for emitting MDString244/// correctly.245void organizeMetadata();246247/// Drop the function tag from the transitive operands of the given node.248void dropFunctionFromMetadata(MetadataMapType::value_type &FirstMD);249250/// Incorporate the function metadata.251///252/// This should be called before enumerating LocalAsMetadata for the253/// function.254void incorporateFunctionMetadata(const Function &F);255256/// Enumerate a single instance of metadata with the given function tag.257///258/// If \c MD has already been enumerated, check that \c F matches its259/// function tag. If not, call \a dropFunctionFromMetadata().260///261/// Otherwise, mark \c MD as visited. Assign it an ID, or just return it if262/// it's an \a MDNode.263const MDNode *enumerateMetadataImpl(unsigned F, const Metadata *MD);264265unsigned getMetadataFunctionID(const Function *F) const;266267/// Enumerate reachable metadata in (almost) post-order.268///269/// Enumerate all the metadata reachable from MD. We want to minimize the270/// cost of reading bitcode records, and so the primary consideration is that271/// operands of uniqued nodes are resolved before the nodes are read. This272/// avoids re-uniquing them on the context and factors away RAUW support.273///274/// This algorithm guarantees that subgraphs of uniqued nodes are in275/// post-order. Distinct subgraphs reachable only from a single uniqued node276/// will be in post-order.277///278/// \note The relative order of a distinct and uniqued node is irrelevant.279/// \a organizeMetadata() will later partition distinct nodes ahead of280/// uniqued ones.281///{282void EnumerateMetadata(const Function *F, const Metadata *MD);283void EnumerateMetadata(unsigned F, const Metadata *MD);284///}285286void EnumerateFunctionLocalMetadata(const Function &F,287const LocalAsMetadata *Local);288void EnumerateFunctionLocalMetadata(unsigned F, const LocalAsMetadata *Local);289void EnumerateFunctionLocalListMetadata(const Function &F,290const DIArgList *ArgList);291void EnumerateFunctionLocalListMetadata(unsigned F, const DIArgList *Arglist);292void EnumerateNamedMDNode(const NamedMDNode *NMD);293void EnumerateValue(const Value *V);294void EnumerateType(Type *T);295void EnumerateOperandType(const Value *V);296void EnumerateAttributes(AttributeList PAL);297298void EnumerateValueSymbolTable(const ValueSymbolTable &ST);299void EnumerateNamedMetadata(const Module &M);300};301302} // end namespace llvm303304#endif // LLVM_LIB_BITCODE_WRITER_VALUEENUMERATOR_H305306307