17 #include "llvm/Config/llvm-config.h" 59 unsigned LastGlobalConstantID = 0;
60 unsigned LastGlobalValueID = 0;
64 bool isGlobalConstant(
unsigned ID)
const {
65 return ID <= LastGlobalConstantID;
68 bool isGlobalValue(
unsigned ID)
const {
69 return ID <= LastGlobalValueID && !isGlobalConstant(ID);
72 unsigned size()
const {
return IDs.
size(); }
73 std::pair<unsigned, bool> &operator[](
const Value *V) {
return IDs[V]; }
75 std::pair<unsigned, bool>
lookup(
const Value *V)
const {
79 void index(
const Value *V) {
81 unsigned ID = IDs.
size() + 1;
89 if (OM.lookup(V).first)
92 if (
const Constant *
C = dyn_cast<Constant>(V))
95 if (!isa<BasicBlock>(
Op) && !isa<GlobalValue>(
Op))
114 if (
G.hasInitializer())
115 if (!isa<GlobalValue>(
G.getInitializer()))
118 if (!isa<GlobalValue>(A.getAliasee()))
121 if (!isa<GlobalValue>(
I.getResolver()))
124 for (
const Use &U :
F.operands())
125 if (!isa<GlobalValue>(U.get()))
128 OM.LastGlobalConstantID = OM.size();
146 OM.LastGlobalValueID = OM.size();
149 if (
F.isDeclaration())
160 for (
const Value *
Op :
I.operands())
161 if ((isa<Constant>(*
Op) && !isa<GlobalValue>(*
Op)) ||
172 unsigned ID,
const OrderMap &OM,
175 using Entry = std::pair<const Use *, unsigned>;
179 if (OM.lookup(U.getUser()).
first)
186 bool IsGlobalValue = OM.isGlobalValue(ID);
187 llvm::sort(List, [&](
const Entry &L,
const Entry &R) {
188 const Use *LU = L.first;
189 const Use *RU = R.first;
193 auto LID = OM.lookup(LU->getUser()).
first;
194 auto RID = OM.lookup(RU->getUser()).
first;
202 if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID))
223 return LU->getOperandNo() < RU->getOperandNo();
224 return LU->getOperandNo() > RU->getOperandNo();
229 [](
const Entry &L,
const Entry &R) {
return L.second < R.second; }))
234 Stack.emplace_back(V, F, List.
size());
235 assert(List.
size() == Stack.back().Shuffle.size() &&
"Wrong size");
236 for (
size_t I = 0,
E = List.
size();
I !=
E; ++
I)
237 Stack.back().Shuffle[
I] = List[
I].second;
242 auto &IDPair = OM[V];
243 assert(IDPair.first &&
"Unmapped value");
249 IDPair.second =
true;
254 if (
const Constant *
C = dyn_cast<Constant>(V))
257 if (isa<Constant>(
Op))
284 for (
const Value *
Op :
I.operands())
285 if (isa<Constant>(*
Op) || isa<InlineAsm>(*Op))
303 if (
G.hasInitializer())
310 for (
const Use &U :
F.operands())
318 return V.first->getType()->isIntOrIntVectorTy();
322 bool ShouldPreserveUseListOrder)
323 : ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
324 if (ShouldPreserveUseListOrder)
334 EnumerateAttributes(
F.getAttributes());
343 EnumerateValue(&GIF);
346 unsigned FirstConstant = Values.size();
350 if (GV.hasInitializer())
351 EnumerateValue(GV.getInitializer());
352 if (GV.hasAttributes())
358 EnumerateValue(GA.getAliasee());
362 EnumerateValue(GIF.getResolver());
366 for (
const Use &U :
F.operands())
367 EnumerateValue(U.get());
377 EnumerateValueSymbolTable(M.getValueSymbolTable());
378 EnumerateNamedMetadata(M);
383 GV.getAllMetadata(MDs);
384 for (
const auto &
I : MDs)
388 EnumerateMetadata(
nullptr,
I.second);
394 EnumerateType(A.getType());
398 F.getAllMetadata(MDs);
399 for (
const auto &
I : MDs)
400 EnumerateMetadata(
F.isDeclaration() ? nullptr : &
F,
I.second);
404 for (
const Use &
Op :
I.operands()) {
407 EnumerateOperandType(
Op);
412 if (isa<LocalAsMetadata>(MD->getMetadata()))
415 EnumerateMetadata(&F, MD->getMetadata());
417 EnumerateType(
I.getType());
418 if (
const CallInst *CI = dyn_cast<CallInst>(&
I))
419 EnumerateAttributes(CI->getAttributes());
420 else if (
const InvokeInst *II = dyn_cast<InvokeInst>(&
I))
421 EnumerateAttributes(II->getAttributes());
425 I.getAllMetadataOtherThanDebugLoc(MDs);
426 for (
unsigned i = 0, e = MDs.size(); i != e; ++i)
427 EnumerateMetadata(&F, MDs[i].
second);
433 EnumerateMetadata(&F,
Op);
438 OptimizeConstants(FirstConstant, Values.size());
446 assert(I != InstructionMap.
end() &&
"Instruction is not mapped!");
451 unsigned ComdatID = Comdats.
idFor(C);
452 assert(ComdatID &&
"Comdat not found!");
457 InstructionMap[
I] = InstructionCount++;
461 if (
auto *MD = dyn_cast<MetadataAsValue>(V))
469 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 479 const char *
Name)
const {
480 OS <<
"Map Name: " << Name <<
"\n";
481 OS <<
"Size: " << Map.
size() <<
"\n";
484 const Value *V =
I->first;
486 OS <<
"Value: " << V->
getName();
488 OS <<
"Value: [null]\n";
493 for (
const Use &U : V->
uses()) {
497 OS <<
" " << U->getName();
507 const char *
Name)
const {
508 OS <<
"Map Name: " << Name <<
"\n";
509 OS <<
"Size: " << Map.
size() <<
"\n";
512 OS <<
"Metadata: slot = " <<
I->second.ID <<
"\n";
513 OS <<
"Metadata: function = " <<
I->second.F <<
"\n";
520 void ValueEnumerator::OptimizeConstants(
unsigned CstStart,
unsigned CstEnd) {
521 if (CstStart == CstEnd || CstStart+1 == CstEnd)
return;
523 if (ShouldPreserveUseListOrder)
528 std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
529 [
this](
const std::pair<const Value *, unsigned> &LHS,
530 const std::pair<const Value *, unsigned> &RHS) {
532 if (LHS.first->getType() != RHS.first->getType())
535 return LHS.second > RHS.second;
541 std::stable_partition(Values.begin() + CstStart, Values.begin() + CstEnd,
545 for (; CstStart != CstEnd; ++CstStart)
551 void ValueEnumerator::EnumerateValueSymbolTable(
const ValueSymbolTable &VST) {
554 EnumerateValue(
VI->getValue());
559 void ValueEnumerator::EnumerateNamedMetadata(
const Module &M) {
561 EnumerateNamedMDNode(&
I);
564 void ValueEnumerator::EnumerateNamedMDNode(
const NamedMDNode *MD) {
566 EnumerateMetadata(
nullptr, MD->
getOperand(i));
569 unsigned ValueEnumerator::getMetadataFunctionID(
const Function *
F)
const {
573 void ValueEnumerator::EnumerateMetadata(
const Function *F,
const Metadata *MD) {
574 EnumerateMetadata(getMetadataFunctionID(F), MD);
577 void ValueEnumerator::EnumerateFunctionLocalMetadata(
579 EnumerateFunctionLocalMetadata(getMetadataFunctionID(&F), Local);
582 void ValueEnumerator::dropFunctionFromMetadata(
586 auto &Entry = MD.second;
598 if (
auto *
N = dyn_cast<MDNode>(MD.first))
602 while (!Worklist.
empty())
606 auto MD = MetadataMap.
find(
Op);
607 if (MD != MetadataMap.
end())
612 void ValueEnumerator::EnumerateMetadata(
unsigned F,
const Metadata *MD) {
622 if (
const MDNode *
N = enumerateMetadataImpl(F, MD))
623 Worklist.
push_back(std::make_pair(
N,
N->op_begin()));
625 while (!Worklist.
empty()) {
632 [&](
const Metadata *MD) {
return enumerateMetadataImpl(F, MD); });
634 auto *
Op = cast<MDNode>(*I);
635 Worklist.
back().second = ++
I;
648 MetadataMap[
N].ID = MDs.size();
652 if (Worklist.
empty() || Worklist.
back().first->isDistinct()) {
653 for (
const MDNode *N : DelayedDistinctNodes)
655 DelayedDistinctNodes.clear();
660 const MDNode *ValueEnumerator::enumerateMetadataImpl(
unsigned F,
const Metadata *MD) {
665 (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
666 "Invalid metadata kind");
668 auto Insertion = MetadataMap.
insert(std::make_pair(MD, MDIndex(F)));
669 MDIndex &Entry = Insertion.first->second;
670 if (!Insertion.second) {
672 if (Entry.hasDifferentFunction(F))
673 dropFunctionFromMetadata(*Insertion.first);
678 if (
auto *
N = dyn_cast<MDNode>(MD))
683 Entry.ID = MDs.size();
686 if (
auto *
C = dyn_cast<ConstantAsMetadata>(MD))
687 EnumerateValue(
C->getValue());
694 void ValueEnumerator::EnumerateFunctionLocalMetadata(
696 assert(F &&
"Expected a function");
699 MDIndex &
Index = MetadataMap[Local];
701 assert(Index.F == F &&
"Expected the same function");
705 MDs.push_back(Local);
707 Index.ID = MDs.size();
714 if (isa<MDString>(MD))
725 return N->isDistinct() ? 2 : 3;
728 void ValueEnumerator::organizeMetadata() {
730 "Metadata map and vector out of sync");
748 llvm::sort(Order, [
this](MDIndex LHS, MDIndex RHS) {
755 std::vector<const Metadata *> OldMDs = std::move(MDs);
756 MDs.reserve(OldMDs.size());
757 for (
unsigned I = 0,
E = Order.
size();
I !=
E && !Order[
I].F; ++
I) {
758 auto *MD = Order[
I].get(OldMDs);
760 MetadataMap[MD].ID =
I + 1;
761 if (isa<MDString>(MD))
766 if (MDs.size() == Order.
size())
771 FunctionMDs.reserve(OldMDs.size());
773 for (
unsigned I = MDs.size(),
E = Order.
size(),
ID = MDs.size();
I !=
E;
775 unsigned F = Order[
I].F;
778 }
else if (PrevF != F) {
779 R.Last = FunctionMDs.size();
781 R.First = FunctionMDs.size();
787 auto *MD = Order[
I].get(OldMDs);
788 FunctionMDs.push_back(MD);
789 MetadataMap[MD].ID = ++
ID;
790 if (isa<MDString>(MD))
793 R.Last = FunctionMDs.size();
794 FunctionMDInfo[PrevF] = R;
797 void ValueEnumerator::incorporateFunctionMetadata(
const Function &F) {
798 NumModuleMDs = MDs.size();
801 NumMDStrings = R.NumStrings;
802 MDs.insert(MDs.end(), FunctionMDs.begin() + R.First,
803 FunctionMDs.begin() + R.Last);
806 void ValueEnumerator::EnumerateValue(
const Value *V) {
808 assert(!isa<MetadataAsValue>(V) &&
"EnumerateValue doesn't handle Metadata!");
814 Values[ValueID-1].second++;
818 if (
auto *GO = dyn_cast<GlobalObject>(V))
819 if (
const Comdat *
C = GO->getComdat())
825 if (
const Constant *
C = dyn_cast<Constant>(V)) {
826 if (isa<GlobalValue>(
C)) {
839 if (!isa<BasicBlock>(*
I))
844 Values.push_back(std::make_pair(V, 1U));
851 Values.push_back(std::make_pair(V, 1U));
852 ValueID = Values.size();
856 void ValueEnumerator::EnumerateType(
Type *Ty) {
857 unsigned *
TypeID = &TypeMap[Ty];
866 if (
StructType *STy = dyn_cast<StructType>(Ty))
867 if (!STy->isLiteral())
873 EnumerateType(SubTy);
876 TypeID = &TypeMap[Ty];
883 if (*TypeID && *TypeID != ~0U)
889 *TypeID = Types.size();
894 void ValueEnumerator::EnumerateOperandType(
const Value *V) {
897 assert(!isa<MetadataAsValue>(V) &&
"Unexpected metadata operand");
913 if (isa<BasicBlock>(
Op))
916 EnumerateOperandType(
Op);
920 void ValueEnumerator::EnumerateAttributes(
AttributeList PAL) {
924 unsigned &Entry = AttributeListMap[PAL];
927 AttributeLists.push_back(PAL);
928 Entry = AttributeLists.size();
937 unsigned &Entry = AttributeGroupMap[Pair];
939 AttributeGroups.push_back(Pair);
940 Entry = AttributeGroups.size();
946 InstructionCount = 0;
947 NumModuleValues = Values.size();
951 incorporateFunctionMetadata(F);
954 for (
const auto &
I : F.
args())
957 FirstFuncConstantID = Values.size();
962 for (
const Use &OI :
I.operands()) {
963 if ((isa<Constant>(OI) && !isa<GlobalValue>(OI)) || isa<InlineAsm>(OI))
966 BasicBlocks.push_back(&BB);
971 OptimizeConstants(FirstFuncConstantID, Values.size());
975 EnumerateAttributes(F.getAttributes());
977 FirstInstID = Values.size();
983 for (
const Use &OI :
I.operands()) {
984 if (
auto *MD = dyn_cast<MetadataAsValue>(&OI))
985 if (
auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata()))
990 if (!
I.getType()->isVoidTy())
996 for (
unsigned i = 0, e = FnLocalMDVector.
size(); i != e; ++i) {
1000 "Missing value for metadata operand");
1001 EnumerateFunctionLocalMetadata(F, FnLocalMDVector[i]);
1007 for (
unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
1009 for (
unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
1010 MetadataMap.
erase(MDs[i]);
1011 for (
unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
1014 Values.resize(NumModuleValues);
1015 MDs.resize(NumModuleMDs);
1016 BasicBlocks.clear();
1022 unsigned Counter = 0;
1024 IDMap[&BB] = ++Counter;
1031 unsigned &Idx = GlobalBasicBlockIDs[BB];
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Tracking metadata reference owned by Metadata.
This class provides a symbol table of name/value pairs.
ArrayRef< Type * > subtypes() const
iterator_range< use_iterator > uses()
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
static unsigned getMetadataTypeOrder(const Metadata *MD)
This class represents an incoming formal argument to a Function.
iterator begin()
Get an iterator that from the beginning of the symbol table.
unsigned getValueID(const Value *V) const
MDNode * getOperand(unsigned i) const
This class represents lattice values for constants.
static void predictValueUseListOrder(const Value *V, const Function *F, OrderMap &OM, UseListOrderStack &Stack)
A Module instance is used to store all the information related to an LLVM module. ...
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
void push_back(const T &Elt)
This class represents a function call, abstracting a target machine's calling convention.
void setInstructionID(const Instruction *I)
static Type * getMetadataTy(LLVMContext &C)
unsigned index_end() const
This defines the Use class.
void reserve(size_type N)
static void predictValueUseListOrderImpl(const Value *V, const Function *F, unsigned ID, const OrderMap &OM, UseListOrderStack &Stack)
op_iterator op_end() const
unsigned getMetadataID(const Metadata *MD) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
static bool isIntOrIntVectorValue(const std::pair< const Value *, unsigned > &V)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
amdgpu Simplify well known AMD library false Value Value const Twine & Name
Class to represent struct types.
A Use represents the edge between a Value definition and its users.
const TypeList & getTypes() const
This file contains the simple types necessary to represent the attributes associated with functions a...
TypeID
Definitions of all of the base types for the Type system.
uint64_t computeBitsRequiredForTypeIndicies() const
unsigned getNumOperands() const
static const uint16_t * lookup(unsigned opcode, unsigned domain, ArrayRef< uint16_t[3]> Table)
op_iterator op_begin() const
unsigned idFor(const T &Entry) const
idFor - return the ID for an existing entry.
Type * getType() const
All values are typed, get the type of this value.
op_range operands() const
llvm::detail::DenseMapPair< const Metadata *, MDIndex > value_type
iterator find(const KeyT &Val)
iterator end()
Get an iterator to the end of the symbol table.
iterator find(const_arg_type_t< KeyT > Val)
AttributeSet getAttributes(unsigned Index) const
The attributes for the specified index are returned.
bool isVoidTy() const
Return true if this is 'void'.
bool erase(const KeyT &Val)
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
void print(raw_ostream &OS, const ValueMapType &Map, const char *Name) const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
unsigned getInstructionID(const Instruction *I) const
std::vector< UseListOrder > UseListOrderStack
ValueEnumerator(const Module &M, bool ShouldPreserveUseListOrder)
iterator_range< named_metadata_iterator > named_metadata()
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block...
void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
static OrderMap orderModule(const Module &M)
static UseListOrderStack predictUseListOrder(const Module &M)
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
void sort(IteratorTy Start, IteratorTy End)
reverse_iterator rbegin()
unsigned getNumOperands() const
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
LLVM_NODISCARD T pop_back_val()
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
unsigned getTypeID(Type *T) const
UseListOrderStack UseListOrders
unsigned getNumUses() const
This method computes the number of uses of this Value.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
static void orderValue(const Value *V, OrderMap &OM)
unsigned insert(const T &Entry)
insert - Append entry to the vector if it doesn't already exist.
LLVM_NODISCARD bool empty() const
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
iterator_range< ifunc_iterator > ifuncs()
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
static void IncorporateFunctionInfoGlobalBBIDs(const Function *F, DenseMap< const BasicBlock *, unsigned > &IDMap)
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool hasAttributes() const
Return true if attributes exists in this set.
LLVM Value Representation.
This class implements an extremely fast bulk output stream that can only output to a stream...
iterator_range< global_iterator > globals()
unsigned getComdatID(const Comdat *C) const
bool isEmpty() const
Return true if there are no attributes.
iterator_range< arg_iterator > args()
unsigned index_begin() const
Use these to iterate over the valid attribute indices.
bool erase(const KeyT &Val)
iterator_range< alias_iterator > aliases()