1 //===- DirectX/DXILWriter/ValueEnumerator.h - Number values -----*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This class gives values and types Unique ID's. 10 // Forked from lib/Bitcode/Writer 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_DXILWRITER_VALUEENUMERATOR_H 15 #define LLVM_DXILWRITER_VALUEENUMERATOR_H 16 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/UniqueVector.h" 20 #include "llvm/IR/Attributes.h" 21 #include "llvm/IR/UseListOrder.h" 22 #include <cassert> 23 #include <cstdint> 24 #include <utility> 25 #include <vector> 26 27 namespace llvm { 28 29 class BasicBlock; 30 class Comdat; 31 class DIArgList; 32 class Function; 33 class Instruction; 34 class LocalAsMetadata; 35 class MDNode; 36 class Metadata; 37 class Module; 38 class NamedMDNode; 39 class raw_ostream; 40 class Type; 41 class Value; 42 class ValueSymbolTable; 43 44 namespace dxil { 45 46 class ValueEnumerator { 47 public: 48 using TypeList = std::vector<Type *>; 49 50 // For each value, we remember its Value* and occurrence frequency. 51 using ValueList = std::vector<std::pair<const Value *, unsigned>>; 52 53 /// Attribute groups as encoded in bitcode are almost AttributeSets, but they 54 /// include the AttributeList index, so we have to track that in our map. 55 using IndexAndAttrSet = std::pair<unsigned, AttributeSet>; 56 57 UseListOrderStack UseListOrders; 58 59 private: 60 using TypeMapType = DenseMap<Type *, unsigned>; 61 TypeMapType TypeMap; 62 TypeList Types; 63 64 using ValueMapType = DenseMap<const Value *, unsigned>; 65 ValueMapType ValueMap; 66 ValueList Values; 67 68 using ComdatSetType = UniqueVector<const Comdat *>; 69 ComdatSetType Comdats; 70 71 std::vector<const Metadata *> MDs; 72 std::vector<const Metadata *> FunctionMDs; 73 74 /// Index of information about a piece of metadata. 75 struct MDIndex { 76 unsigned F = 0; ///< The ID of the function for this metadata, if any. 77 unsigned ID = 0; ///< The implicit ID of this metadata in bitcode. 78 79 MDIndex() = default; 80 explicit MDIndex(unsigned F) : F(F) {} 81 82 /// Check if this has a function tag, and it's different from NewF. 83 bool hasDifferentFunction(unsigned NewF) const { return F && F != NewF; } 84 85 /// Fetch the MD this references out of the given metadata array. 86 const Metadata *get(ArrayRef<const Metadata *> MDs) const { 87 assert(ID && "Expected non-zero ID"); 88 assert(ID <= MDs.size() && "Expected valid ID"); 89 return MDs[ID - 1]; 90 } 91 }; 92 93 using MetadataMapType = DenseMap<const Metadata *, MDIndex>; 94 MetadataMapType MetadataMap; 95 96 /// Range of metadata IDs, as a half-open range. 97 struct MDRange { 98 unsigned First = 0; 99 unsigned Last = 0; 100 101 /// Number of strings in the prefix of the metadata range. 102 unsigned NumStrings = 0; 103 104 MDRange() = default; 105 explicit MDRange(unsigned First) : First(First) {} 106 }; 107 SmallDenseMap<unsigned, MDRange, 1> FunctionMDInfo; 108 109 bool ShouldPreserveUseListOrder; 110 111 using AttributeGroupMapType = DenseMap<IndexAndAttrSet, unsigned>; 112 AttributeGroupMapType AttributeGroupMap; 113 std::vector<IndexAndAttrSet> AttributeGroups; 114 115 using AttributeListMapType = DenseMap<AttributeList, unsigned>; 116 AttributeListMapType AttributeListMap; 117 std::vector<AttributeList> AttributeLists; 118 119 /// GlobalBasicBlockIDs - This map memoizes the basic block ID's referenced by 120 /// the "getGlobalBasicBlockID" method. 121 mutable DenseMap<const BasicBlock *, unsigned> GlobalBasicBlockIDs; 122 123 using InstructionMapType = DenseMap<const Instruction *, unsigned>; 124 InstructionMapType InstructionMap; 125 unsigned InstructionCount; 126 127 /// BasicBlocks - This contains all the basic blocks for the currently 128 /// incorporated function. Their reverse mapping is stored in ValueMap. 129 std::vector<const BasicBlock *> BasicBlocks; 130 131 /// When a function is incorporated, this is the size of the Values list 132 /// before incorporation. 133 unsigned NumModuleValues; 134 135 /// When a function is incorporated, this is the size of the Metadatas list 136 /// before incorporation. 137 unsigned NumModuleMDs = 0; 138 unsigned NumMDStrings = 0; 139 140 unsigned FirstFuncConstantID; 141 unsigned FirstInstID; 142 143 public: 144 ValueEnumerator(const Module &M, bool ShouldPreserveUseListOrder); 145 ValueEnumerator(const ValueEnumerator &) = delete; 146 ValueEnumerator &operator=(const ValueEnumerator &) = delete; 147 148 void dump() const; 149 void print(raw_ostream &OS, const ValueMapType &Map, const char *Name) const; 150 void print(raw_ostream &OS, const MetadataMapType &Map, 151 const char *Name) const; 152 153 unsigned getValueID(const Value *V) const; 154 155 unsigned getMetadataID(const Metadata *MD) const { 156 auto ID = getMetadataOrNullID(MD); 157 assert(ID != 0 && "Metadata not in slotcalculator!"); 158 return ID - 1; 159 } 160 161 unsigned getMetadataOrNullID(const Metadata *MD) const { 162 return MetadataMap.lookup(MD).ID; 163 } 164 165 unsigned numMDs() const { return MDs.size(); } 166 167 bool shouldPreserveUseListOrder() const { return ShouldPreserveUseListOrder; } 168 169 unsigned getTypeID(Type *T) const { 170 TypeMapType::const_iterator I = TypeMap.find(T); 171 assert(I != TypeMap.end() && "Type not in ValueEnumerator!"); 172 return I->second - 1; 173 } 174 175 unsigned getInstructionID(const Instruction *I) const; 176 void setInstructionID(const Instruction *I); 177 178 unsigned getAttributeListID(AttributeList PAL) const { 179 if (PAL.isEmpty()) 180 return 0; // Null maps to zero. 181 AttributeListMapType::const_iterator I = AttributeListMap.find(PAL); 182 assert(I != AttributeListMap.end() && "Attribute not in ValueEnumerator!"); 183 return I->second; 184 } 185 186 unsigned getAttributeGroupID(IndexAndAttrSet Group) const { 187 if (!Group.second.hasAttributes()) 188 return 0; // Null maps to zero. 189 AttributeGroupMapType::const_iterator I = AttributeGroupMap.find(Group); 190 assert(I != AttributeGroupMap.end() && "Attribute not in ValueEnumerator!"); 191 return I->second; 192 } 193 194 /// getFunctionConstantRange - Return the range of values that corresponds to 195 /// function-local constants. 196 void getFunctionConstantRange(unsigned &Start, unsigned &End) const { 197 Start = FirstFuncConstantID; 198 End = FirstInstID; 199 } 200 201 const ValueList &getValues() const { return Values; } 202 203 /// Check whether the current block has any metadata to emit. 204 bool hasMDs() const { return NumModuleMDs < MDs.size(); } 205 206 /// Get the MDString metadata for this block. 207 ArrayRef<const Metadata *> getMDStrings() const { 208 return makeArrayRef(MDs).slice(NumModuleMDs, NumMDStrings); 209 } 210 211 /// Get the non-MDString metadata for this block. 212 ArrayRef<const Metadata *> getNonMDStrings() const { 213 return makeArrayRef(MDs).slice(NumModuleMDs).slice(NumMDStrings); 214 } 215 216 const TypeList &getTypes() const { return Types; } 217 218 const std::vector<const BasicBlock *> &getBasicBlocks() const { 219 return BasicBlocks; 220 } 221 222 const std::vector<AttributeList> &getAttributeLists() const { 223 return AttributeLists; 224 } 225 226 const std::vector<IndexAndAttrSet> &getAttributeGroups() const { 227 return AttributeGroups; 228 } 229 230 const ComdatSetType &getComdats() const { return Comdats; } 231 unsigned getComdatID(const Comdat *C) const; 232 233 /// getGlobalBasicBlockID - This returns the function-specific ID for the 234 /// specified basic block. This is relatively expensive information, so it 235 /// should only be used by rare constructs such as address-of-label. 236 unsigned getGlobalBasicBlockID(const BasicBlock *BB) const; 237 238 /// incorporateFunction/purgeFunction - If you'd like to deal with a function, 239 /// use these two methods to get its data into the ValueEnumerator! 240 void incorporateFunction(const Function &F); 241 242 void purgeFunction(); 243 uint64_t computeBitsRequiredForTypeIndicies() const; 244 245 private: 246 void OptimizeConstants(unsigned CstStart, unsigned CstEnd); 247 248 /// Reorder the reachable metadata. 249 /// 250 /// This is not just an optimization, but is mandatory for emitting MDString 251 /// correctly. 252 void organizeMetadata(); 253 254 /// Drop the function tag from the transitive operands of the given node. 255 void dropFunctionFromMetadata(MetadataMapType::value_type &FirstMD); 256 257 /// Incorporate the function metadata. 258 /// 259 /// This should be called before enumerating LocalAsMetadata for the 260 /// function. 261 void incorporateFunctionMetadata(const Function &F); 262 263 /// Enumerate a single instance of metadata with the given function tag. 264 /// 265 /// If \c MD has already been enumerated, check that \c F matches its 266 /// function tag. If not, call \a dropFunctionFromMetadata(). 267 /// 268 /// Otherwise, mark \c MD as visited. Assign it an ID, or just return it if 269 /// it's an \a MDNode. 270 const MDNode *enumerateMetadataImpl(unsigned F, const Metadata *MD); 271 272 unsigned getMetadataFunctionID(const Function *F) const; 273 274 /// Enumerate reachable metadata in (almost) post-order. 275 /// 276 /// Enumerate all the metadata reachable from MD. We want to minimize the 277 /// cost of reading bitcode records, and so the primary consideration is that 278 /// operands of uniqued nodes are resolved before the nodes are read. This 279 /// avoids re-uniquing them on the context and factors away RAUW support. 280 /// 281 /// This algorithm guarantees that subgraphs of uniqued nodes are in 282 /// post-order. Distinct subgraphs reachable only from a single uniqued node 283 /// will be in post-order. 284 /// 285 /// \note The relative order of a distinct and uniqued node is irrelevant. 286 /// \a organizeMetadata() will later partition distinct nodes ahead of 287 /// uniqued ones. 288 ///{ 289 void EnumerateMetadata(const Function *F, const Metadata *MD); 290 void EnumerateMetadata(unsigned F, const Metadata *MD); 291 ///} 292 293 void EnumerateFunctionLocalMetadata(const Function &F, 294 const LocalAsMetadata *Local); 295 void EnumerateFunctionLocalMetadata(unsigned F, const LocalAsMetadata *Local); 296 void EnumerateFunctionLocalListMetadata(const Function &F, 297 const DIArgList *ArgList); 298 void EnumerateFunctionLocalListMetadata(unsigned F, const DIArgList *Arglist); 299 void EnumerateNamedMDNode(const NamedMDNode *NMD); 300 void EnumerateValue(const Value *V); 301 void EnumerateType(Type *T); 302 void EnumerateOperandType(const Value *V); 303 void EnumerateAttributes(AttributeList PAL); 304 305 void EnumerateValueSymbolTable(const ValueSymbolTable &ST); 306 void EnumerateNamedMetadata(const Module &M); 307 }; 308 309 } // end namespace dxil 310 } // end namespace llvm 311 312 #endif // LLVM_DXILWRITER_VALUEENUMERATOR_H 313