15#include "llvm/Config/llvm-config.h"
52 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
53 unsigned LastGlobalValueID = 0;
57 bool isGlobalValue(
unsigned ID)
const {
58 return ID <= LastGlobalValueID;
61 unsigned size()
const {
return IDs.
size(); }
64 std::pair<unsigned, bool>
lookup(
const Value *V)
const {
68 void index(
const Value *V) {
70 unsigned ID = IDs.
size() + 1;
78 if (OM.lookup(V).first)
82 if (
C->getNumOperands()) {
83 for (
const Value *
Op :
C->operands())
87 if (CE->getOpcode() == Instruction::ShuffleVector)
88 orderValue(CE->getShuffleMaskForBitcode(), OM);
118 OM.LastGlobalValueID = OM.size();
120 auto orderConstantValue = [&OM](
const Value *V) {
126 if (
F.isDeclaration())
138 auto OrderConstantFromMetadata = [&](
Metadata *MD) {
140 orderConstantValue(VAM->getValue());
142 for (
const auto *VAM : AL->getArgs())
143 orderConstantValue(VAM->getValue());
148 OrderConstantFromMetadata(DVR.getRawLocation());
149 if (DVR.isDbgAssign())
150 OrderConstantFromMetadata(DVR.getRawAddress());
153 for (
const Value *V :
I.operands()) {
155 OrderConstantFromMetadata(MAV->getMetadata());
163 for (
const Value *
Op :
I.operands())
164 orderConstantValue(
Op);
166 orderValue(SVI->getShuffleMaskForBitcode(), OM);
168 for (
const auto &Case :
SI->cases())
178 unsigned ID,
const OrderMap &OM,
181 using Entry = std::pair<const Use *, unsigned>;
185 if (OM.lookup(U.getUser()).first)
186 List.
push_back(std::make_pair(&U, List.size()));
192 bool IsGlobalValue = OM.isGlobalValue(
ID);
193 llvm::sort(List, [&](
const Entry &L,
const Entry &R) {
194 const Use *LU = L.first;
195 const Use *RU = R.first;
199 auto LID = OM.lookup(LU->getUser()).first;
200 auto RID = OM.lookup(RU->getUser()).first;
220 return LU->getOperandNo() < RU->getOperandNo();
221 return LU->getOperandNo() > RU->getOperandNo();
229 Stack.emplace_back(V,
F, List.size());
230 assert(List.size() == Stack.back().Shuffle.size() &&
"Wrong size");
231 for (
size_t I = 0,
E = List.size();
I !=
E; ++
I)
232 Stack.back().Shuffle[
I] = List[
I].second;
237 if (!V->hasUseList())
240 auto &IDPair = OM[V];
241 assert(IDPair.first &&
"Unmapped value");
247 IDPair.second =
true;
248 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
253 if (
C->getNumOperands()) {
254 for (
const Value *
Op :
C->operands())
258 if (CE->getOpcode() == Instruction::ShuffleVector)
279 auto PredictValueOrderFromMetadata = [&](
Metadata *MD) {
283 for (
const auto *VAM : AL->getArgs())
287 if (
F.isDeclaration())
296 PredictValueOrderFromMetadata(DVR.getRawLocation());
297 if (DVR.isDbgAssign())
298 PredictValueOrderFromMetadata(DVR.getRawAddress());
300 for (
const Value *
Op :
I.operands()) {
304 PredictValueOrderFromMetadata(MAV->getMetadata());
325 if (
G.hasInitializer())
332 for (
const Use &U :
F.operands())
340 return V.first->getType()->isIntOrIntVectorTy();
344 bool ShouldPreserveUseListOrder)
345 : ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
346 if (ShouldPreserveUseListOrder)
352 EnumerateType(GV.getValueType());
358 EnumerateType(
F.getValueType());
359 EnumerateAttributes(
F.getAttributes());
365 EnumerateType(GA.getValueType());
370 EnumerateValue(&GIF);
371 EnumerateType(GIF.getValueType());
375 unsigned FirstConstant = Values.size();
379 if (GV.hasInitializer())
380 EnumerateValue(GV.getInitializer());
381 if (GV.hasAttributes())
382 EnumerateAttributes(GV.getAttributesAsList(AttributeList::FunctionIndex));
387 EnumerateValue(GA.getAliasee());
391 EnumerateValue(GIF.getResolver());
395 for (
const Use &U :
F.operands())
396 EnumerateValue(U.get());
406 EnumerateValueSymbolTable(M.getValueSymbolTable());
407 EnumerateNamedMetadata(M);
412 GV.getAllMetadata(MDs);
413 for (const auto &I : MDs)
417 EnumerateMetadata(nullptr, I.second);
423 EnumerateType(
A.getType());
427 F.getAllMetadata(MDs);
428 for (
const auto &
I : MDs)
429 EnumerateMetadata(
F.isDeclaration() ?
nullptr : &
F,
I.second);
436 auto EnumerateNonLocalValuesFromMetadata = [&](
Metadata *MD) {
437 assert(MD &&
"Metadata unexpectedly null");
439 for (
const auto *VAM : AL->getArgs()) {
441 EnumerateMetadata(&
F, VAM);
447 EnumerateMetadata(&
F, MD);
452 EnumerateMetadata(&
F, DLR->getLabel());
453 EnumerateMetadata(&
F, &*DLR->getDebugLoc());
468 for (
const Use &
Op :
I.operands()) {
471 EnumerateOperandType(
Op);
475 EnumerateNonLocalValuesFromMetadata(MD->getMetadata());
478 EnumerateType(SVI->getShuffleMaskForBitcode()->getType());
480 EnumerateType(
GEP->getSourceElementType());
482 EnumerateType(AI->getAllocatedType());
483 EnumerateType(
I.getType());
485 EnumerateAttributes(
Call->getAttributes());
486 EnumerateType(
Call->getFunctionType());
491 I.getAllMetadataOtherThanDebugLoc(MDs);
492 for (
const auto &MD : MDs)
493 EnumerateMetadata(&
F, MD.second);
499 EnumerateMetadata(&
F,
Op);
504 GIF.getAllMetadata(MDs);
505 for (const auto &I : MDs)
506 EnumerateMetadata(nullptr, I.second);
510 OptimizeConstants(FirstConstant, Values.size());
518 assert(
I != InstructionMap.end() &&
"Instruction is not mapped!");
523 unsigned ComdatID = Comdats.idFor(
C);
524 assert(ComdatID &&
"Comdat not found!");
529 InstructionMap[
I] = InstructionCount++;
537 assert(
I != ValueMap.end() &&
"Value not in slotcalculator!");
541#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
551 const char *Name)
const {
552 OS <<
"Map Name: " << Name <<
"\n";
553 OS <<
"Size: " << Map.size() <<
"\n";
554 for (
const auto &
I : Map) {
557 OS <<
"Value: " << V->getName();
559 OS <<
"Value: [null]\n";
563 OS <<
" Uses(" << V->getNumUses() <<
"):";
564 for (
const Use &U : V->
uses()) {
565 if (&U != &*V->use_begin())
568 OS <<
" " << U->getName();
578 const char *Name)
const {
579 OS <<
"Map Name: " << Name <<
"\n";
580 OS <<
"Size: " << Map.size() <<
"\n";
581 for (
const auto &
I : Map) {
583 OS <<
"Metadata: slot = " <<
I.second.ID <<
"\n";
584 OS <<
"Metadata: function = " <<
I.second.F <<
"\n";
591void ValueEnumerator::OptimizeConstants(
unsigned CstStart,
unsigned CstEnd) {
592 if (CstStart == CstEnd || CstStart+1 == CstEnd)
return;
594 if (ShouldPreserveUseListOrder)
599 std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
600 [
this](
const std::pair<const Value *, unsigned> &LHS,
601 const std::pair<const Value *, unsigned> &RHS) {
603 if (LHS.first->getType() != RHS.first->getType())
604 return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
606 return LHS.second > RHS.second;
612 std::stable_partition(Values.begin() + CstStart, Values.begin() + CstEnd,
616 for (; CstStart != CstEnd; ++CstStart)
617 ValueMap[Values[CstStart].first] = CstStart+1;
622void ValueEnumerator::EnumerateValueSymbolTable(
const ValueSymbolTable &VST) {
623 for (
const auto &VI : VST)
624 EnumerateValue(VI.getValue());
629void ValueEnumerator::EnumerateNamedMetadata(
const Module &M) {
630 for (
const auto &
I :
M.named_metadata())
631 EnumerateNamedMDNode(&
I);
634void ValueEnumerator::EnumerateNamedMDNode(
const NamedMDNode *MD) {
636 EnumerateMetadata(
nullptr,
N);
639unsigned ValueEnumerator::getMetadataFunctionID(
const Function *
F)
const {
644 EnumerateMetadata(getMetadataFunctionID(
F), MD);
647void ValueEnumerator::EnumerateFunctionLocalMetadata(
649 EnumerateFunctionLocalMetadata(getMetadataFunctionID(&
F),
Local);
652void ValueEnumerator::EnumerateFunctionLocalListMetadata(
654 EnumerateFunctionLocalListMetadata(getMetadataFunctionID(&
F), ArgList);
657void ValueEnumerator::dropFunctionFromMetadata(
658 MetadataMapType::value_type &FirstMD) {
661 auto &
Entry = MD.second;
677 while (!Worklist.
empty())
681 auto MD = MetadataMap.find(
Op);
682 if (MD != MetadataMap.end())
687void ValueEnumerator::EnumerateMetadata(
unsigned F,
const Metadata *MD) {
697 if (
const MDNode *
N = enumerateMetadataImpl(
F, MD))
698 Worklist.
push_back(std::make_pair(
N,
N->op_begin()));
700 while (!Worklist.
empty()) {
701 const MDNode *
N = Worklist.
back().first;
706 Worklist.
back().second,
N->op_end(),
707 [&](
const Metadata *MD) { return enumerateMetadataImpl(F, MD); });
708 if (
I !=
N->op_end()) {
710 Worklist.
back().second = ++
I;
713 if (
Op->isDistinct() && !
N->isDistinct())
723 MetadataMap[
N].ID = MDs.size();
727 if (Worklist.
empty() || Worklist.
back().first->isDistinct()) {
728 for (
const MDNode *
N : DelayedDistinctNodes)
729 Worklist.
push_back(std::make_pair(
N,
N->op_begin()));
730 DelayedDistinctNodes.clear();
735const MDNode *ValueEnumerator::enumerateMetadataImpl(
unsigned F,
const Metadata *MD) {
741 "Invalid metadata kind");
743 auto Insertion = MetadataMap.insert(std::make_pair(MD, MDIndex(
F)));
744 MDIndex &
Entry = Insertion.first->second;
745 if (!Insertion.second) {
747 if (
Entry.hasDifferentFunction(
F))
748 dropFunctionFromMetadata(*Insertion.first);
758 Entry.ID = MDs.size();
762 EnumerateValue(
C->getValue());
769void ValueEnumerator::EnumerateFunctionLocalMetadata(
771 assert(
F &&
"Expected a function");
780 MDs.push_back(
Local);
782 Index.ID = MDs.size();
784 EnumerateValue(
Local->getValue());
789void ValueEnumerator::EnumerateFunctionLocalListMetadata(
791 assert(
F &&
"Expected a function");
794 MDIndex &
Index = MetadataMap[ArgList];
800 for (ValueAsMetadata *VAM : ArgList->
getArgs()) {
802 assert(MetadataMap.count(VAM) &&
803 "LocalAsMetadata should be enumerated before DIArgList");
805 "Expected LocalAsMetadata in the same function");
808 "Expected LocalAsMetadata or ConstantAsMetadata");
809 assert(ValueMap.count(VAM->getValue()) &&
810 "Constant should be enumerated beforeDIArgList");
811 EnumerateMetadata(
F, VAM);
815 MDs.push_back(ArgList);
817 Index.ID = MDs.size();
833 return N->isDistinct() ? 2 : 3;
836void ValueEnumerator::organizeMetadata() {
837 assert(MetadataMap.size() == MDs.size() &&
838 "Metadata map and vector out of sync");
846 Order.
reserve(MetadataMap.size());
863 std::vector<const Metadata *> OldMDs;
865 MDs.reserve(OldMDs.size());
866 for (
unsigned I = 0,
E = Order.
size();
I !=
E && !Order[
I].F; ++
I) {
867 auto *MD = Order[
I].get(OldMDs);
869 MetadataMap[MD].ID =
I + 1;
875 if (MDs.size() == Order.
size())
880 FunctionMDs.reserve(OldMDs.size());
882 for (
unsigned I = MDs.size(),
E = Order.
size(),
ID = MDs.size();
I !=
E;
884 unsigned F = Order[
I].F;
887 }
else if (PrevF !=
F) {
888 R.Last = FunctionMDs.size();
890 R.First = FunctionMDs.size();
896 auto *MD = Order[
I].get(OldMDs);
898 MetadataMap[MD].ID = ++
ID;
902 R.Last = FunctionMDs.size();
903 FunctionMDInfo[PrevF] =
R;
906void ValueEnumerator::incorporateFunctionMetadata(
const Function &
F) {
907 NumModuleMDs = MDs.size();
910 NumMDStrings =
R.NumStrings;
911 MDs.insert(MDs.end(), FunctionMDs.begin() +
R.First,
912 FunctionMDs.begin() +
R.Last);
915void ValueEnumerator::EnumerateValue(
const Value *V) {
916 assert(!
V->getType()->isVoidTy() &&
"Can't insert void values!");
920 unsigned &ValueID = ValueMap[
V];
923 Values[ValueID-1].second++;
928 if (
const Comdat *
C = GO->getComdat())
932 EnumerateType(
V->getType());
937 }
else if (
C->getNumOperands()) {
946 for (
const Use &U :
C->operands())
950 if (
CE->getOpcode() == Instruction::ShuffleVector)
951 EnumerateValue(
CE->getShuffleMaskForBitcode());
953 EnumerateType(
GEP->getSourceElementType());
958 Values.push_back(std::make_pair(V, 1U));
959 ValueMap[
V] = Values.size();
965 Values.push_back(std::make_pair(V, 1U));
966 ValueID = Values.size();
970void ValueEnumerator::EnumerateType(
Type *Ty) {
971 unsigned *
TypeID = &TypeMap[Ty];
981 if (!STy->isLiteral())
987 EnumerateType(SubTy);
1001 Types.push_back(Ty);
1008void ValueEnumerator::EnumerateOperandType(
const Value *V) {
1009 EnumerateType(
V->getType());
1019 if (ValueMap.count(
C))
1024 for (
const Value *
Op :
C->operands()) {
1030 EnumerateOperandType(
Op);
1033 if (
CE->getOpcode() == Instruction::ShuffleVector)
1034 EnumerateOperandType(
CE->getShuffleMaskForBitcode());
1035 if (
CE->getOpcode() == Instruction::GetElementPtr)
1040void ValueEnumerator::EnumerateAttributes(AttributeList PAL) {
1041 if (PAL.isEmpty())
return;
1044 unsigned &
Entry = AttributeListMap[PAL];
1047 AttributeLists.push_back(PAL);
1048 Entry = AttributeLists.size();
1052 for (
unsigned i : PAL.indexes()) {
1053 AttributeSet AS = PAL.getAttributes(i);
1057 unsigned &
Entry = AttributeGroupMap[Pair];
1059 AttributeGroups.push_back(Pair);
1060 Entry = AttributeGroups.size();
1063 if (Attr.isTypeAttribute())
1064 EnumerateType(Attr.getValueAsType());
1071 InstructionCount = 0;
1072 NumModuleValues = Values.size();
1076 incorporateFunctionMetadata(
F);
1079 for (
const auto &
I :
F.args()) {
1081 if (
I.hasAttribute(Attribute::ByVal))
1082 EnumerateType(
I.getParamByValType());
1083 else if (
I.hasAttribute(Attribute::StructRet))
1084 EnumerateType(
I.getParamStructRetType());
1085 else if (
I.hasAttribute(Attribute::ByRef))
1086 EnumerateType(
I.getParamByRefType());
1088 FirstFuncConstantID = Values.size();
1093 for (
const Use &OI :
I.operands()) {
1098 EnumerateValue(SVI->getShuffleMaskForBitcode());
1100 for (
const auto &Case :
SI->cases())
1101 EnumerateValue(Case.getCaseValue());
1104 BasicBlocks.push_back(&BB);
1105 ValueMap[&BB] = BasicBlocks.size();
1109 OptimizeConstants(FirstFuncConstantID, Values.size());
1113 EnumerateAttributes(
F.getAttributes());
1115 FirstInstID = Values.size();
1120 auto AddFnLocalMetadata = [&](
Metadata *MD) {
1141 for (
const Use &OI :
I.operands()) {
1143 AddFnLocalMetadata(MD->getMetadata());
1147 assert(DVR.getRawLocation() &&
1148 "DbgVariableRecord location unexpectedly null");
1149 AddFnLocalMetadata(DVR.getRawLocation());
1150 if (DVR.isDbgAssign()) {
1151 assert(DVR.getRawAddress() &&
1152 "DbgVariableRecord location unexpectedly null");
1153 AddFnLocalMetadata(DVR.getRawAddress());
1156 if (!
I.getType()->isVoidTy())
1166 "Missing value for metadata operand");
1167 EnumerateFunctionLocalMetadata(
F,
Local);
1171 for (
const DIArgList *ArgList : ArgListMDVector)
1172 EnumerateFunctionLocalListMetadata(
F, ArgList);
1178 ValueMap.erase(V.first);
1180 MetadataMap.erase(MD);
1184 Values.resize(NumModuleValues);
1185 MDs.resize(NumModuleMDs);
1186 BasicBlocks.clear();
1192 unsigned Counter = 0;
1194 IDMap[&BB] = ++Counter;
1201 unsigned &Idx = GlobalBasicBlockIDs[BB];
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MapVector< const Value *, unsigned > OrderMap
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
This file contains the declaration of the GlobalIFunc class, which represents a single indirect funct...
Module.h This file contains the declarations for the Module class.
This defines the Use class.
static bool lookup(const GsymReader &GR, DataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
This file defines the SmallVector class.
static void predictValueUseListOrderImpl(const Value *V, const Function *F, unsigned ID, const OrderMap &OM, UseListOrderStack &Stack)
static unsigned getMetadataTypeOrder(const Metadata *MD)
static void orderValue(const Value *V, OrderMap &OM)
static void predictValueUseListOrder(const Value *V, const Function *F, OrderMap &OM, UseListOrderStack &Stack)
static UseListOrderStack predictUseListOrder(const Module &M)
static void IncorporateFunctionInfoGlobalBBIDs(const Function *F, DenseMap< const BasicBlock *, unsigned > &IDMap)
static bool isIntOrIntVectorValue(const std::pair< const Value *, unsigned > &V)
static OrderMap orderModule(const Module &M)
This class represents an incoming formal argument to a Function.
bool hasAttributes() const
Return true if attributes exists in this set.
LLVM Basic Block Representation.
const Function * getParent() const
Return the enclosing method, or null if none.
This is an important base class in LLVM.
List of ValueAsMetadata, to be used as an argument to a dbg.value intrinsic.
ArrayRef< ValueAsMetadata * > getArgs() const
Records a position in IR for a source label (DILabel).
Base class for non-instruction debug metadata records that have positions within IR.
DebugLoc getDebugLoc() const
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI DIAssignID * getAssignID() const
DIExpression * getExpression() const
DILocalVariable * getVariable() const
Metadata * getRawLocation() const
Returns the metadata operand for the first location description.
Metadata * getRawAddress() const
DIExpression * getAddressExpression() const
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...
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
const MDOperand * op_iterator
unsigned & operator[](const const Value *&Key)
A Module instance is used to store all the information related to an LLVM module.
iterator_range< op_iterator > operands()
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
static LLVM_ABI Type * getMetadataTy(LLVMContext &C)
ArrayRef< Type * > subtypes() const
A Use represents the edge between a Value definition and its users.
unsigned getMetadataID(const Metadata *MD) const
UseListOrderStack UseListOrders
void print(raw_ostream &OS, const ValueMapType &Map, const char *Name) const
unsigned getInstructionID(const Instruction *I) const
void incorporateFunction(const Function &F)
incorporateFunction/purgeFunction - If you'd like to deal with a function, use these two methods to g...
ValueEnumerator(const Module &M, bool ShouldPreserveUseListOrder)
unsigned getComdatID(const Comdat *C) const
uint64_t computeBitsRequiredForTypeIndices() const
unsigned getValueID(const Value *V) const
unsigned getGlobalBasicBlockID(const BasicBlock *BB) const
getGlobalBasicBlockID - This returns the function-specific ID for the specified basic block.
void setInstructionID(const Instruction *I)
std::pair< unsigned, AttributeSet > IndexAndAttrSet
Attribute groups as encoded in bitcode are almost AttributeSets, but they include the AttributeList i...
const TypeList & getTypes() const
This class provides a symbol table of name/value pairs.
LLVM Value Representation.
iterator_range< use_iterator > uses()
This class implements an extremely fast bulk output stream that can only output to a stream.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
@ C
The default llvm calling convention, compatible with C.
@ CE
Windows NT (Windows on ARM)
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
FunctionAddr VTableAddr Value
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
auto reverse(ContainerTy &&C)
void sort(IteratorTy Start, IteratorTy End)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
std::vector< UseListOrder > UseListOrderStack
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Function object to check whether the second component of a container supported by std::get (like std:...