57#define DEBUG_TYPE "memprof-context-disambiguation"
60 "Number of function clones created during whole program analysis");
62 "Number of function clones created during ThinLTO backend");
64 "Number of functions that had clones created during ThinLTO backend");
66 FunctionCloneDuplicatesThinBackend,
67 "Number of function clone duplicates detected during ThinLTO backend");
68STATISTIC(AllocTypeNotCold,
"Number of not cold static allocations (possibly "
69 "cloned) during whole program analysis");
70STATISTIC(AllocTypeCold,
"Number of cold static allocations (possibly cloned) "
71 "during whole program analysis");
73 "Number of ambiguous static allocations (possibly cloned) during "
74 "whole program analysis");
76 "Number of not cold static allocations (possibly cloned) during "
78STATISTIC(AllocTypeColdThinBackend,
"Number of cold static allocations "
79 "(possibly cloned) during ThinLTO backend");
81 "Number of ambiguous static allocations (possibly cloned) during "
84 "Number of original (not cloned) allocations with memprof profiles "
85 "during ThinLTO backend");
87 AllocVersionsThinBackend,
88 "Number of allocation versions (including clones) during ThinLTO backend");
90 "Maximum number of allocation versions created for an original "
91 "allocation during ThinLTO backend");
93 "Number of unclonable ambigous allocations during ThinLTO backend");
95 "Number of edges removed due to mismatched callees (profiled vs IR)");
97 "Number of profiled callees found via tail calls");
99 "Aggregate depth of profiled callees found via tail calls");
101 "Maximum depth of profiled callees found via tail calls");
103 "Number of profiled callees found via multiple tail call chains");
105 "Number of tail calls in chains to profiled callees that are "
106 "indirect (thin link)");
108 "Number of indirect tail calls recorded for ICP for cloning during "
110STATISTIC(DeferredBackedges,
"Number of backedges with deferred cloning");
111STATISTIC(NewMergedNodes,
"Number of new nodes created during merging");
112STATISTIC(NonNewMergedNodes,
"Number of non new nodes used during merging");
114 "Number of missing alloc nodes for context ids");
116 "Number of calls skipped during cloning due to unexpected operand");
118 "Number of callsites assigned to call multiple non-matching clones");
119STATISTIC(TotalMergeInvokes,
"Number of merge invocations for nodes");
120STATISTIC(TotalMergeIters,
"Number of merge iterations for nodes");
121STATISTIC(MaxMergeIters,
"Max merge iterations for nodes");
122STATISTIC(NumImportantContextIds,
"Number of important context ids");
123STATISTIC(NumFixupEdgeIdsInserted,
"Number of fixup edge ids inserted");
124STATISTIC(NumFixupEdgesAdded,
"Number of fixup edges added");
125STATISTIC(NumFixedContexts,
"Number of contexts with fixed edges");
127 "Number of callsite clones without an edge to a callee's clones "
128 "assigned the callee function clone of their original node");
130 "Number of calls in function clones whose callee was taken from a "
131 "callsite clone an implicit caller requires");
133 "Number of context ids with call stacks trimmed at a callsite");
135 "Number of callsite clones without an edge to a callee's clones "
136 "left in a function clone calling a conflicting callee clone");
138 "Number of aliasees prevailing in a different module than its alias");
140 "Number of summary callsites assigned to call a cloned callee (thin "
143 "Number of summary callsites assigned to call a cloned callee with "
144 "an indirect call edge (thin link)");
146 "Number of summary indirect call edges to cloned callees marked as "
147 "requiring a declaration import (thin link)");
149 "Number of calls assigned contexts trimmed within their inlined "
150 "stack id sequence");
152 "Number of (duplicated) context ids for contexts trimmed within a "
153 "call's inlined stack id sequence");
155 "Number of functions with memprof metadata or summaries not "
156 "considered for cloning because copying them is unsafe");
180template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
181class CallsiteContextGraph {
183 CallsiteContextGraph(
const IPOOptions &Opts) : Opts(Opts) {}
184 CallsiteContextGraph(
const CallsiteContextGraph &) =
default;
185 CallsiteContextGraph(CallsiteContextGraph &&) =
default;
189 EmitRemark =
nullptr,
190 bool AllowExtraAnalysis =
false);
194 void identifyClones();
201 bool assignFunctions();
207 EmitRemark =
nullptr)
const;
210 const CallsiteContextGraph &CCG) {
216 const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *>;
218 const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *>;
220 void exportToDot(std::string Label)
const;
223 struct FuncInfo final
224 :
public std::pair<FuncTy *, unsigned > {
225 using Base = std::pair<FuncTy *, unsigned>;
227 FuncInfo(FuncTy *
F =
nullptr,
unsigned CloneNo = 0) :
Base(
F, CloneNo) {}
228 explicit operator bool()
const {
return this->first !=
nullptr; }
229 FuncTy *func()
const {
return this->first; }
230 unsigned cloneNo()
const {
return this->second; }
234 struct CallInfo final :
public std::pair<CallTy, unsigned > {
235 using Base = std::pair<CallTy, unsigned>;
237 CallInfo(CallTy
Call =
nullptr,
unsigned CloneNo = 0)
239 explicit operator bool()
const {
return (
bool)this->first; }
240 CallTy call()
const {
return this->first; }
241 unsigned cloneNo()
const {
return this->second; }
242 void setCloneNo(
unsigned N) { this->second =
N; }
244 if (!
operator bool()) {
250 OS <<
"\t(clone " << cloneNo() <<
")";
276 bool Recursive =
false;
284 bool CloneRecursiveContexts : 1;
285 bool AllowRecursiveCallsitesAndContexts : 1;
308 std::vector<std::shared_ptr<ContextEdge>> CalleeEdges;
312 std::vector<std::shared_ptr<ContextEdge>> CallerEdges;
316 bool useCallerEdgesForContextInfo()
const {
321 assert(!CalleeEdges.empty() || CallerEdges.empty() || IsAllocation ||
322 AllowRecursiveCallsitesAndContexts);
328 return IsAllocation || CloneRecursiveContexts;
339 for (
auto &Edge : CalleeEdges.empty() ? CallerEdges : CalleeEdges)
340 Count += Edge->getContextIds().size();
344 CalleeEdges, useCallerEdgesForContextInfo()
346 : std::vector<std::shared_ptr<ContextEdge>>());
347 for (
const auto &Edge : Edges)
354 uint8_t computeAllocType()
const {
359 CalleeEdges, useCallerEdgesForContextInfo()
361 : std::vector<std::shared_ptr<ContextEdge>>());
362 for (
const auto &Edge : Edges) {
363 AllocType |= Edge->AllocTypes;
365 if (AllocType == BothTypes)
373 bool emptyContextIds()
const {
375 CalleeEdges, useCallerEdgesForContextInfo()
377 : std::vector<std::shared_ptr<ContextEdge>>());
378 for (
const auto &Edge : Edges) {
379 if (!Edge->getContextIds().empty())
386 bool hasContextId(
uint32_t Id)
const {
388 CalleeEdges, useCallerEdgesForContextInfo()
390 : std::vector<std::shared_ptr<ContextEdge>>());
391 for (
const auto &Edge : Edges) {
392 if (Edge->getContextIds().contains(Id))
404 CalleeEdges, useCallerEdgesForContextInfo()
406 : std::vector<std::shared_ptr<ContextEdge>>());
407 for (
const auto &Edge : Edges) {
408 const auto &EdgeIds = Edge->getContextIds();
410 if (EdgeIds.size() < NotFound.
size()) {
411 for (
auto Id : EdgeIds)
415 [&EdgeIds](
uint32_t Id) {
return EdgeIds.contains(Id); });
417 if (NotFound.
empty())
424 std::vector<ContextNode *> Clones;
427 ContextNode *CloneOf =
nullptr;
429 ContextNode(
const IPOOptions &Opts,
bool IsAllocation, CallInfo
C)
430 : IsAllocation(IsAllocation),
431 CloneRecursiveContexts(Opts.memprof_clone_recursive_contexts),
432 AllowRecursiveCallsitesAndContexts(
433 Opts.memprof_allow_recursive_callsites &&
434 Opts.memprof_allow_recursive_contexts),
437 void addClone(ContextNode *Clone) {
439 CloneOf->Clones.push_back(Clone);
440 Clone->CloneOf = CloneOf;
442 Clones.push_back(Clone);
444 Clone->CloneOf =
this;
448 ContextNode *getOrigNode() {
454 const ContextNode *getOrigNode()
const {
460 void addOrUpdateCallerEdge(ContextNode *Caller,
AllocationType AllocType,
461 unsigned int ContextId);
463 ContextEdge *findEdgeFromCallee(
const ContextNode *Callee);
464 ContextEdge *findEdgeFromCaller(
const ContextNode *Caller);
465 void eraseCalleeEdge(
const ContextEdge *Edge);
466 void eraseCallerEdge(
const ContextEdge *Edge);
468 void setCall(CallInfo
C) {
Call = std::move(
C); }
470 bool hasCall()
const {
return (
bool)
Call.call(); }
476 bool isRemoved()
const {
481 assert(AllowRecursiveCallsitesAndContexts ||
512 bool IsBackedge =
false;
517 ContextEdge(ContextNode *Callee, ContextNode *Caller,
uint8_t AllocType,
519 : Callee(Callee), Caller(Caller), AllocTypes(AllocType),
520 ContextIds(std::move(ContextIds)) {}
526 inline void clear() {
536 inline bool isRemoved()
const {
537 if (Callee || Caller)
558 void removeNoneTypeCalleeEdges(ContextNode *
Node);
559 void removeNoneTypeCallerEdges(ContextNode *
Node);
561 recursivelyRemoveNoneTypeCalleeEdges(ContextNode *
Node,
565 const IPOOptions &Opts;
569 template <
class NodeT,
class IteratorT>
570 std::vector<ContextNode *>
575 ContextNode *addAllocNode(CallInfo
Call,
const FuncTy *
F);
578 template <
class NodeT,
class IteratorT>
579 void addStackNodesForMIB(
583 std::map<uint64_t, uint32_t> &TotalSizeToContextIdTopNCold);
588 void updateStackNodes();
598 void fixupImportantContexts();
602 void handleCallsitesWithMultipleTargets();
605 void markBackedges();
615 bool partitionCallsByCallee(
617 std::vector<std::pair<CallInfo, ContextNode *>> &NewCallToNode);
624 std::map<const ContextNode *, const FuncTy *> NodeToCallingFunc;
626 const FuncTy *getCallingFunc(
const ContextNode *
N)
const {
627 auto It = NodeToCallingFunc.
find(
N);
628 return It != NodeToCallingFunc.end() ? It->second :
nullptr;
643 using EdgeIter =
typename std::vector<std::shared_ptr<ContextEdge>>
::iterator;
648 struct CallContextInfo {
656 std::vector<ContextNode *> StackNodes;
675 void removeEdgeFromGraph(ContextEdge *Edge, EdgeIter *EI =
nullptr,
676 bool CalleeIter =
true);
684 void assignStackNodesPostOrder(
700 void propagateDuplicateContextIds(
707 struct TrimmedAtNodeCache {
709 std::vector<DenseSet<uint32_t>> TrimmedAtNodeIds;
717 TrimmedAtNodeCache &Cache);
722 void connectNewNode(ContextNode *NewNode, ContextNode *OrigNode,
729 return static_cast<const DerivedCCG *
>(
this)->getStackId(IdOrIndex);
739 calleesMatch(CallTy
Call, EdgeIter &EI,
744 const FuncTy *getCalleeFunc(CallTy
Call) {
745 return static_cast<DerivedCCG *
>(
this)->getCalleeFunc(
Call);
751 bool calleeMatchesFunc(
752 CallTy
Call,
const FuncTy *Func,
const FuncTy *CallerFunc,
753 std::vector<std::pair<CallTy, FuncTy *>> &FoundCalleeChain) {
754 return static_cast<DerivedCCG *
>(
this)->calleeMatchesFunc(
755 Call, Func, CallerFunc, FoundCalleeChain);
759 bool sameCallee(CallTy Call1, CallTy Call2) {
760 return static_cast<DerivedCCG *
>(
this)->sameCallee(Call1, Call2);
765 std::vector<ContextNode *> getStackNodesForCall(CallTy
Call) {
766 return static_cast<DerivedCCG *
>(
this)->getStackNodesForCall(
Call);
771 return static_cast<DerivedCCG *
>(
this)->getLastStackId(
Call);
779 AllocTypeAmbiguous++;
782 static_cast<DerivedCCG *
>(
this)->updateAllocationCall(
Call, AllocType);
787 return static_cast<const DerivedCCG *
>(
this)->getAllocationCallType(
Call);
792 void updateCall(CallInfo &CallerCall, FuncInfo CalleeFunc) {
793 static_cast<DerivedCCG *
>(
this)->updateCall(CallerCall, CalleeFunc);
799 FuncInfo cloneFunctionForCallsite(
801 std::vector<CallInfo> &CallsWithMetadataInFunc,
unsigned CloneNo) {
802 return static_cast<DerivedCCG *
>(
this)->cloneFunctionForCallsite(
803 Func,
Call, CallMap, CallsWithMetadataInFunc, CloneNo);
808 std::string getLabel(
const FuncTy *Func,
const CallTy
Call,
809 unsigned CloneNo)
const {
810 return static_cast<const DerivedCCG *
>(
this)->getLabel(Func,
Call, CloneNo);
814 std::string getFuncName(
const FuncTy *Func,
unsigned CloneNo = 0)
const {
815 return static_cast<const DerivedCCG *
>(
this)->getFuncName(Func, CloneNo);
820 bool isFuncDead(
const FuncTy *Func)
const {
821 return static_cast<const DerivedCCG *
>(
this)->isFuncDead(Func);
825 void populateFunctionsWithCallers() {
826 static_cast<DerivedCCG *
>(
this)->populateFunctionsWithCallers();
831 void capturePreCloningContextInfo();
837 std::string formatContextReportSuffix(
const ContextNode *
Node,
841 ContextNode *createNewNode(
bool IsAllocation,
const FuncTy *
F =
nullptr,
842 CallInfo
C = CallInfo()) {
843 NodeOwner.push_back(std::make_unique<ContextNode>(Opts, IsAllocation,
C));
844 auto *NewNode = NodeOwner.back().get();
846 NodeToCallingFunc[NewNode] =
F;
847 NewNode->NodeId = NodeOwner.size();
852 ContextNode *getNodeForInst(
const CallInfo &
C);
853 ContextNode *getNodeForAlloc(
const CallInfo &
C);
854 ContextNode *getNodeForStackId(
uint64_t StackId);
876 moveEdgeToNewCalleeClone(
const std::shared_ptr<ContextEdge> &Edge,
883 void moveEdgeToExistingCalleeClone(
const std::shared_ptr<ContextEdge> &Edge,
884 ContextNode *NewCallee,
885 bool NewClone =
false,
893 void moveCalleeEdgeToNewCaller(
const std::shared_ptr<ContextEdge> &Edge,
894 ContextNode *NewCaller);
905 void mergeNodeCalleeClones(
910 void findOtherCallersToShareMerge(
911 ContextNode *
Node, std::vector<std::shared_ptr<ContextEdge>> &CalleeEdges,
925 struct ImplicitSource {
927 const ContextNode *Source;
935 using ImplicitSourceMap =
943 void assignImplicitCallers(
946 const std::map<FuncInfo, ContextNode *> &FuncCloneToCurNodeCloneMap,
947 ImplicitSourceMap &ImplicitSources);
953 static const ContextNode *resolveImplicitSource(
const ContextNode *
Node,
954 const ImplicitSource &Src);
973 struct ImportantContextInfo {
975 std::vector<uint64_t> StackIds;
978 unsigned MaxLength = 0;
982 std::map<std::vector<uint64_t>, ContextNode *> StackIdsToNode;
997 if (!Opts.memprof_top_n_important) {
1005 std::vector<uint64_t> StackIds;
1006 StackIds.reserve(StackNodes.
size());
1007 for (
const ContextNode *
N : StackNodes)
1008 StackIds.push_back(
N->OrigStackOrAllocId);
1009 auto Size = StackIds.size();
1010 for (
auto Id : Ids) {
1011 auto &Entry = ImportantContextIdInfo[Id];
1012 Entry.StackIdsToNode[StackIds] =
Node;
1014 if (
Size > Entry.MaxLength)
1015 Entry.MaxLength =
Size;
1024 std::vector<std::unique_ptr<ContextNode>> NodeOwner;
1030 unsigned int LastContextId = 0;
1038 struct PreCloningContextInfo {
1042 std::vector<const ContextNode *> Chain;
1052 unsigned MaxMatchedFrame = 0;
1055 bool OutermostMatchedNodeHasOtherCallers =
false;
1060 bool StoppedAtRecursive =
false;
1061 bool StoppedAtMismatchedCallee =
false;
1064 const FuncTy *UnmatchedCallingFunc =
nullptr;
1079 OrigNodeAndCloneToCalleeClone;
1084 OrigAllocAndCloneToNode;
1087template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1089 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode;
1090template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1092 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge;
1093template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1095 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::FuncInfo;
1096template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1098 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::CallInfo;
1101class ModuleCallsiteContextGraph
1102 :
public CallsiteContextGraph<ModuleCallsiteContextGraph, Function,
1105 ModuleCallsiteContextGraph(
1107 llvm::function_ref<OptimizationRemarkEmitter &(
Function *)> OREGetter);
1110 friend CallsiteContextGraph<ModuleCallsiteContextGraph,
Function,
1115 bool calleeMatchesFunc(
1117 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain);
1118 bool sameCallee(Instruction *Call1, Instruction *Call2);
1119 bool findProfiledCalleeThroughTailCalls(
1121 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain,
1122 bool &FoundMultipleCalleeChains);
1124 std::vector<ContextNode *> getStackNodesForCall(Instruction *
Call);
1127 void updateCall(CallInfo &CallerCall, FuncInfo CalleeFunc);
1128 CallsiteContextGraph<ModuleCallsiteContextGraph,
Function,
1130 cloneFunctionForCallsite(FuncInfo &Func, CallInfo &
Call,
1131 DenseMap<CallInfo, CallInfo> &CallMap,
1132 std::vector<CallInfo> &CallsWithMetadataInFunc,
1134 std::string getLabel(
const Function *Func,
const Instruction *
Call,
1135 unsigned CloneNo)
const;
1136 std::string getFuncName(
const Function *Func,
unsigned CloneNo = 0)
const;
1137 bool isFuncDead(
const Function *Func)
const {
return false; }
1138 void populateFunctionsWithCallers();
1141 llvm::function_ref<OptimizationRemarkEmitter &(
Function *)> OREGetter;
1147struct IndexCall :
public PointerUnion<CallsiteInfo *, AllocInfo *> {
1148 IndexCall() : PointerUnion() {}
1149 IndexCall(std::nullptr_t) : IndexCall() {}
1150 IndexCall(CallsiteInfo *StackNode) : PointerUnion(StackNode) {}
1151 IndexCall(AllocInfo *AllocNode) : PointerUnion(AllocNode) {}
1152 IndexCall(PointerUnion PT) : PointerUnion(PT) {}
1154 IndexCall *operator->() {
return this; }
1156 void print(raw_ostream &OS)
const {
1157 PointerUnion<CallsiteInfo *, AllocInfo *>
Base = *
this;
1182class IndexCallsiteContextGraph
1183 :
public CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
1186 IndexCallsiteContextGraph(
1187 const IPOOptions &Opts, ModuleSummaryIndex &Index,
1191 ~IndexCallsiteContextGraph() {
1196 for (
auto &
I : FunctionCalleesToSynthesizedCallsiteInfos) {
1198 for (
auto &Callsite :
I.second)
1199 FS->addCallsite(std::move(*Callsite.second));
1204 friend CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
1208 const FunctionSummary *getCalleeFunc(IndexCall &
Call);
1209 bool calleeMatchesFunc(
1210 IndexCall &
Call,
const FunctionSummary *Func,
1211 const FunctionSummary *CallerFunc,
1212 std::vector<std::pair<IndexCall, FunctionSummary *>> &FoundCalleeChain);
1213 bool sameCallee(IndexCall &Call1, IndexCall &Call2);
1214 bool findProfiledCalleeThroughTailCalls(
1215 ValueInfo ProfiledCallee, ValueInfo CurCallee,
unsigned Depth,
1216 std::vector<std::pair<ValueInfo, FunctionSummary *>> &FoundCalleeChain,
1217 bool &FoundMultipleCalleeChains);
1219 std::vector<ContextNode *> getStackNodesForCall(IndexCall &
Call);
1222 void updateCall(CallInfo &CallerCall, FuncInfo CalleeFunc);
1223 CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
1224 IndexCall>::FuncInfo
1225 cloneFunctionForCallsite(FuncInfo &Func, CallInfo &
Call,
1226 DenseMap<CallInfo, CallInfo> &CallMap,
1227 std::vector<CallInfo> &CallsWithMetadataInFunc,
1229 std::string getLabel(
const FunctionSummary *Func,
const IndexCall &
Call,
1230 unsigned CloneNo)
const;
1231 std::string getFuncName(
const FunctionSummary *Func,
1232 unsigned CloneNo = 0)
const;
1233 bool isFuncDead(
const FunctionSummary *Func)
const;
1234 void populateFunctionsWithCallers();
1235 DenseSet<GlobalValue::GUID> findAliaseeGUIDsPrevailingInDifferentModule();
1239 std::map<const FunctionSummary *, ValueInfo> FSToVIMap;
1241 const ModuleSummaryIndex &Index;
1249 DenseMap<FunctionSummary *,
1250 std::map<ValueInfo, std::unique_ptr<CallsiteInfo>>>
1251 FunctionCalleesToSynthesizedCallsiteInfos;
1262 :
public DenseMapInfo<std::pair<IndexCall, unsigned>> {};
1265 :
public DenseMapInfo<PointerUnion<CallsiteInfo *, AllocInfo *>> {};
1286template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1287bool allocTypesMatch(
1288 const std::vector<uint8_t> &InAllocTypes,
1289 const std::vector<std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>>>
1293 assert(InAllocTypes.size() == Edges.size());
1295 InAllocTypes.begin(), InAllocTypes.end(), Edges.begin(), Edges.end(),
1297 const std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>> &r) {
1301 if (l == (uint8_t)AllocationType::None ||
1302 r->AllocTypes == (uint8_t)AllocationType::None)
1304 return allocTypeToUse(l) == allocTypeToUse(r->AllocTypes);
1313template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1314bool allocTypesMatchClone(
1315 const std::vector<uint8_t> &InAllocTypes,
1316 const ContextNode<DerivedCCG, FuncTy, CallTy> *Clone) {
1317 const ContextNode<DerivedCCG, FuncTy, CallTy> *
Node = Clone->CloneOf;
1321 assert(InAllocTypes.size() ==
Node->CalleeEdges.size());
1325 for (
const auto &
E : Clone->CalleeEdges) {
1327 EdgeCalleeMap[
E->Callee] =
E->AllocTypes;
1331 for (
unsigned I = 0;
I <
Node->CalleeEdges.size();
I++) {
1332 auto Iter = EdgeCalleeMap.
find(
Node->CalleeEdges[
I]->Callee);
1334 if (Iter == EdgeCalleeMap.
end())
1342 if (allocTypeToUse(Iter->second) != allocTypeToUse(InAllocTypes[
I]))
1350template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1351typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1352CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getNodeForInst(
1353 const CallInfo &
C) {
1354 ContextNode *
Node = getNodeForAlloc(
C);
1358 return NonAllocationCallToContextNodeMap.lookup(
C);
1361template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1362typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1363CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getNodeForAlloc(
1364 const CallInfo &
C) {
1365 return AllocationCallToContextNodeMap.lookup(
C);
1368template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1369typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1370CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getNodeForStackId(
1372 auto StackEntryNode = StackEntryIdToContextNodeMap.find(StackId);
1373 if (StackEntryNode != StackEntryIdToContextNodeMap.end())
1374 return StackEntryNode->second;
1378template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1379void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1380 addOrUpdateCallerEdge(ContextNode *Caller,
AllocationType AllocType,
1381 unsigned int ContextId) {
1382 for (
auto &
Edge : CallerEdges) {
1383 if (
Edge->Caller == Caller) {
1384 Edge->AllocTypes |= (uint8_t)AllocType;
1385 Edge->getContextIds().insert(ContextId);
1389 std::shared_ptr<ContextEdge>
Edge = std::make_shared<ContextEdge>(
1390 this, Caller, (uint8_t)AllocType, DenseSet<uint32_t>({ContextId}));
1391 CallerEdges.push_back(
Edge);
1395template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1396void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::removeEdgeFromGraph(
1397 ContextEdge *
Edge, EdgeIter *EI,
bool CalleeIter) {
1413 auto CalleeCallerCount =
Callee->CallerEdges.size();
1414 auto CallerCalleeCount =
Caller->CalleeEdges.size();
1419 }
else if (CalleeIter) {
1421 *EI =
Caller->CalleeEdges.erase(*EI);
1424 *EI =
Callee->CallerEdges.erase(*EI);
1426 assert(
Callee->CallerEdges.size() < CalleeCallerCount);
1427 assert(
Caller->CalleeEdges.size() < CallerCalleeCount);
1430template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1431void CallsiteContextGraph<
1432 DerivedCCG, FuncTy, CallTy>::removeNoneTypeCalleeEdges(ContextNode *Node) {
1433 for (
auto EI =
Node->CalleeEdges.begin(); EI !=
Node->CalleeEdges.end();) {
1435 if (
Edge->AllocTypes == (uint8_t)AllocationType::None) {
1437 removeEdgeFromGraph(
Edge.get(), &EI,
true);
1443template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1444void CallsiteContextGraph<
1445 DerivedCCG, FuncTy, CallTy>::removeNoneTypeCallerEdges(ContextNode *Node) {
1446 for (
auto EI =
Node->CallerEdges.begin(); EI !=
Node->CallerEdges.end();) {
1448 if (
Edge->AllocTypes == (uint8_t)AllocationType::None) {
1450 Edge->Caller->eraseCalleeEdge(
Edge.get());
1451 EI =
Node->CallerEdges.erase(EI);
1457template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1458typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge *
1459CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1460 findEdgeFromCallee(
const ContextNode *Callee) {
1461 for (
const auto &
Edge : CalleeEdges)
1462 if (
Edge->Callee == Callee)
1467template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1468typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge *
1469CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1470 findEdgeFromCaller(
const ContextNode *Caller) {
1471 for (
const auto &
Edge : CallerEdges)
1472 if (
Edge->Caller == Caller)
1477template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1478void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1479 eraseCalleeEdge(
const ContextEdge *
Edge) {
1481 CalleeEdges, [
Edge](
const std::shared_ptr<ContextEdge> &CalleeEdge) {
1482 return CalleeEdge.get() ==
Edge;
1484 assert(EI != CalleeEdges.end());
1485 CalleeEdges.erase(EI);
1488template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1489void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1490 eraseCallerEdge(
const ContextEdge *
Edge) {
1492 CallerEdges, [
Edge](
const std::shared_ptr<ContextEdge> &CallerEdge) {
1493 return CallerEdge.get() ==
Edge;
1495 assert(EI != CallerEdges.end());
1496 CallerEdges.erase(EI);
1499template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1500uint8_t CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::computeAllocType(
1501 DenseSet<uint32_t> &ContextIds)
const {
1503 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
1504 uint8_t AllocType = (uint8_t)AllocationType::None;
1505 for (
auto Id : ContextIds) {
1506 AllocType |= (uint8_t)ContextIdToAllocationType.at(Id);
1508 if (AllocType == BothTypes)
1514template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1516CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::intersectAllocTypesImpl(
1517 const DenseSet<uint32_t> &Node1Ids,
1518 const DenseSet<uint32_t> &Node2Ids)
const {
1520 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
1521 uint8_t AllocType = (uint8_t)AllocationType::None;
1522 for (
auto Id : Node1Ids) {
1523 if (!Node2Ids.
count(Id))
1525 AllocType |= (uint8_t)ContextIdToAllocationType.at(Id);
1527 if (AllocType == BothTypes)
1533template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1534uint8_t CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::intersectAllocTypes(
1535 const DenseSet<uint32_t> &Node1Ids,
1536 const DenseSet<uint32_t> &Node2Ids)
const {
1537 if (Node1Ids.
size() < Node2Ids.
size())
1538 return intersectAllocTypesImpl(Node1Ids, Node2Ids);
1540 return intersectAllocTypesImpl(Node2Ids, Node1Ids);
1543template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1544typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1545CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::addAllocNode(
1546 CallInfo
Call,
const FuncTy *
F) {
1548 ContextNode *AllocNode = createNewNode(
true,
F,
Call);
1549 AllocationCallToContextNodeMap[
Call] = AllocNode;
1551 AllocNode->OrigStackOrAllocId = LastContextId;
1554 AllocNode->AllocTypes = (uint8_t)AllocationType::None;
1570template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1571template <
class NodeT,
class IteratorT>
1572void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::addStackNodesForMIB(
1573 ContextNode *AllocNode, CallStack<NodeT, IteratorT> &StackContext,
1574 CallStack<NodeT, IteratorT> &CallsiteContext,
AllocationType AllocType,
1576 std::map<uint64_t, uint32_t> &TotalSizeToContextIdTopNCold) {
1579 if (AllocType == AllocationType::Hot)
1580 AllocType = AllocationType::NotCold;
1582 ContextIdToAllocationType[++LastContextId] = AllocType;
1584 bool IsImportant =
false;
1585 if (!ContextSizeInfo.
empty()) {
1586 auto &
Entry = ContextIdToContextSizeInfos[LastContextId];
1589 if (AllocType == AllocationType::Cold && Opts.memprof_top_n_important > 0) {
1591 for (
auto &CSI : ContextSizeInfo)
1592 TotalCold += CSI.TotalSize;
1595 if (TotalSizeToContextIdTopNCold.size() < Opts.memprof_top_n_important ||
1598 TotalCold > TotalSizeToContextIdTopNCold.begin()->first) {
1599 if (TotalSizeToContextIdTopNCold.size() ==
1600 Opts.memprof_top_n_important) {
1602 auto IdToRemove = TotalSizeToContextIdTopNCold.begin()->second;
1603 TotalSizeToContextIdTopNCold.erase(
1604 TotalSizeToContextIdTopNCold.begin());
1605 assert(ImportantContextIdInfo.count(IdToRemove));
1606 ImportantContextIdInfo.erase(IdToRemove);
1608 TotalSizeToContextIdTopNCold[TotalCold] = LastContextId;
1612 Entry.insert(
Entry.begin(), ContextSizeInfo.begin(), ContextSizeInfo.end());
1616 AllocNode->AllocTypes |= (uint8_t)AllocType;
1621 ContextNode *PrevNode = AllocNode;
1625 SmallSet<uint64_t, 8> StackIdSet;
1628 ContextIter != StackContext.
end(); ++ContextIter) {
1629 auto StackId = getStackId(*ContextIter);
1631 ImportantContextIdInfo[LastContextId].StackIds.push_back(StackId);
1632 ContextNode *StackNode = getNodeForStackId(StackId);
1634 StackNode = createNewNode(
false);
1635 StackEntryIdToContextNodeMap[StackId] = StackNode;
1636 StackNode->OrigStackOrAllocId = StackId;
1640 if (!Opts.memprof_allow_recursive_callsites) {
1641 auto Ins = StackIdSet.
insert(StackId);
1643 StackNode->Recursive =
true;
1645 StackNode->AllocTypes |= (uint8_t)AllocType;
1646 PrevNode->addOrUpdateCallerEdge(StackNode, AllocType, LastContextId);
1647 PrevNode = StackNode;
1651template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1653CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::duplicateContextIds(
1654 const DenseSet<uint32_t> &StackSequenceContextIds,
1655 DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds,
1656 function_ref<
void(uint32_t OldId, uint32_t NewId)> OnDuplicate) {
1657 DenseSet<uint32_t> NewContextIds;
1658 NewContextIds.
reserve(StackSequenceContextIds.
size());
1659 for (
auto OldId : StackSequenceContextIds) {
1660 NewContextIds.
insert(++LastContextId);
1661 OldToNewContextIds[OldId].insert(LastContextId);
1663 OnDuplicate(OldId, LastContextId);
1664 assert(ContextIdToAllocationType.count(OldId));
1666 ContextIdToAllocationType[LastContextId] = ContextIdToAllocationType[OldId];
1667 auto CSI = ContextIdToContextSizeInfos.find(OldId);
1668 if (CSI != ContextIdToContextSizeInfos.end())
1669 ContextIdToContextSizeInfos[LastContextId] = CSI->second;
1670 if (DotAllocContextIds.
contains(OldId))
1671 DotAllocContextIds.
insert(LastContextId);
1673 return NewContextIds;
1676template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1677void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
1678 propagateDuplicateContextIds(
1679 const DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds) {
1681 auto GetNewIds = [&OldToNewContextIds](
const DenseSet<uint32_t> &ContextIds) {
1682 DenseSet<uint32_t> NewIds;
1683 for (
auto Id : ContextIds)
1684 if (
auto NewId = OldToNewContextIds.find(Id);
1685 NewId != OldToNewContextIds.end())
1691 auto UpdateCallers = [&](ContextNode *
Node,
1692 DenseSet<const ContextEdge *> &Visited,
1693 auto &&UpdateCallers) ->
void {
1694 for (
const auto &
Edge :
Node->CallerEdges) {
1698 ContextNode *NextNode =
Edge->Caller;
1699 DenseSet<uint32_t> NewIdsToAdd = GetNewIds(
Edge->getContextIds());
1702 if (!NewIdsToAdd.
empty()) {
1703 Edge->getContextIds().insert_range(NewIdsToAdd);
1704 UpdateCallers(NextNode, Visited, UpdateCallers);
1709 DenseSet<const ContextEdge *> Visited;
1710 for (
auto &Entry : AllocationCallToContextNodeMap) {
1712 UpdateCallers(Node, Visited, UpdateCallers);
1716template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1717void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::connectNewNode(
1718 ContextNode *NewNode, ContextNode *OrigNode,
bool TowardsCallee,
1719 const DenseSet<uint32_t> &ContextIds) {
1721 TowardsCallee ? OrigNode->CalleeEdges : OrigNode->CallerEdges;
1723 for (
auto EI = OrigEdges.begin(); EI != OrigEdges.end();) {
1725 DenseSet<uint32_t> NewEdgeContextIds;
1730 if (NewEdgeContextIds.
empty()) {
1734 if (TowardsCallee) {
1735 uint8_t NewAllocType = computeAllocType(NewEdgeContextIds);
1736 auto NewEdge = std::make_shared<ContextEdge>(
1737 Edge->Callee, NewNode, NewAllocType, std::move(NewEdgeContextIds));
1738 NewNode->CalleeEdges.push_back(NewEdge);
1739 NewEdge->Callee->CallerEdges.push_back(NewEdge);
1741 uint8_t NewAllocType = computeAllocType(NewEdgeContextIds);
1742 auto NewEdge = std::make_shared<ContextEdge>(
1743 NewNode,
Edge->Caller, NewAllocType, std::move(NewEdgeContextIds));
1744 NewNode->CallerEdges.push_back(NewEdge);
1745 NewEdge->Caller->CalleeEdges.push_back(NewEdge);
1749 if (
Edge->getContextIds().empty()) {
1750 removeEdgeFromGraph(
Edge.get(), &EI, TowardsCallee);
1753 Edge->AllocTypes = computeAllocType(
Edge->getContextIds());
1758template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1760 const std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>> &Edge) {
1764 assert(!Edge->ContextIds.empty());
1767template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1769 bool CheckEdges =
true) {
1770 if (
Node->isRemoved())
1774 auto NodeContextIds =
Node->getContextIds();
1778 if (
Node->CallerEdges.size()) {
1780 Node->CallerEdges.front()->ContextIds);
1784 set_union(CallerEdgeContextIds, Edge->ContextIds);
1790 assert(
Node->AllowRecursiveCallsitesAndContexts ||
1791 NodeContextIds == CallerEdgeContextIds ||
1794 if (
Node->CalleeEdges.size()) {
1796 Node->CalleeEdges.front()->ContextIds);
1800 set_union(CalleeEdgeContextIds, Edge->getContextIds());
1805 assert(
Node->AllowRecursiveCallsitesAndContexts ||
1806 NodeContextIds == CalleeEdgeContextIds);
1815 for (
const auto &
E :
Node->CalleeEdges)
1821template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
1822void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
1823 assignStackNodesPostOrder(ContextNode *Node,
1824 DenseSet<const ContextNode *> &Visited,
1825 DenseMap<
uint64_t, std::vector<CallContextInfo>>
1826 &StackIdToMatchingCalls,
1827 DenseMap<CallInfo, CallInfo> &CallToMatchingCall,
1828 const DenseSet<uint32_t> &ImportantContextIds) {
1836 auto CallerEdges =
Node->CallerEdges;
1837 for (
auto &
Edge : CallerEdges) {
1839 if (
Edge->isRemoved()) {
1843 assignStackNodesPostOrder(
Edge->Caller, Visited, StackIdToMatchingCalls,
1844 CallToMatchingCall, ImportantContextIds);
1853 if (
Node->IsAllocation ||
1854 !StackIdToMatchingCalls.count(
Node->OrigStackOrAllocId))
1857 auto &Calls = StackIdToMatchingCalls[
Node->OrigStackOrAllocId];
1861 if (Calls.size() == 1) {
1862 auto &[
Call, StackNodes,
Func, SavedContextIds, TrimmedInlinedDupIds] =
1864 if (StackNodes.size() == 1) {
1865 assert(SavedContextIds.empty());
1867 assert(TrimmedInlinedDupIds.empty());
1869 assert(Node == StackNodes[0]);
1870 if (
Node->Recursive)
1873 NonAllocationCallToContextNodeMap[
Call] =
Node;
1875 recordStackNode(StackNodes, Node,
Node->getContextIds(),
1876 ImportantContextIds);
1885 ContextNode *LastNode = getNodeForStackId(LastId);
1888 assert(LastNode == Node);
1890 ContextNode *LastNode =
Node;
1895 DenseSet<uint32_t> LastNodeContextIds = LastNode->getContextIds();
1897 [[maybe_unused]]
bool PrevIterCreatedNode =
false;
1898 bool CreatedNode =
false;
1899 for (
unsigned I = 0;
I < Calls.size();
1900 I++, PrevIterCreatedNode = CreatedNode) {
1901 CreatedNode =
false;
1902 auto &[
Call, StackNodes,
Func, SavedContextIds, TrimmedInlinedDupIds] =
1906 if (SavedContextIds.empty() && TrimmedInlinedDupIds.empty()) {
1913 auto MatchingCall = CallToMatchingCall[
Call];
1914 if (!NonAllocationCallToContextNodeMap.contains(MatchingCall)) {
1918 assert(
I > 0 && !PrevIterCreatedNode);
1921 NonAllocationCallToContextNodeMap[MatchingCall]->MatchingCalls.push_back(
1926 assert(LastNode == StackNodes.back());
1935 ContextNode *PrevNode = LastNode;
1936 bool Skip = SavedContextIds.empty();
1939 for (
auto NodeIter = StackNodes.rbegin() + 1;
1940 !Skip && NodeIter != StackNodes.rend(); NodeIter++) {
1941 ContextNode *CurNode = *NodeIter;
1945 assert(!CurNode->Recursive);
1947 auto *
Edge = CurNode->findEdgeFromCaller(PrevNode);
1959 if (SavedContextIds.empty()) {
1965 SavedContextIds.clear();
1972 if (!TrimmedInlinedDupIds.empty()) {
1973 StackNodes[0]->removeContextIdsNotPresent(TrimmedInlinedDupIds);
1974 SavedContextIds.insert_range(TrimmedInlinedDupIds);
1976 if (SavedContextIds.empty())
1980 ContextNode *NewNode = createNewNode(
false, Func,
Call);
1981 NonAllocationCallToContextNodeMap[
Call] = NewNode;
1983 NewNode->AllocTypes = computeAllocType(SavedContextIds);
1985 ContextNode *FirstNode = StackNodes[0];
1991 connectNewNode(NewNode, FirstNode,
true, SavedContextIds);
1996 connectNewNode(NewNode, LastNode,
false, SavedContextIds);
2001 for (ContextNode *CurNode : StackNodes) {
2008 auto *PrevEdge = CurNode->findEdgeFromCallee(PrevNode);
2015 set_subtract(PrevEdge->getContextIds(), SavedContextIds);
2016 if (PrevEdge->getContextIds().empty())
2017 removeEdgeFromGraph(PrevEdge);
2019 PrevEdge->AllocTypes = computeAllocType(PrevEdge->getContextIds());
2024 CurNode->AllocTypes = CurNode->CalleeEdges.empty()
2025 ? (uint8_t)AllocationType::None
2026 : CurNode->computeAllocType();
2030 recordStackNode(StackNodes, NewNode, SavedContextIds, ImportantContextIds);
2032 if (Opts.memprof_verify_nodes) {
2034 for (ContextNode *CurNode : StackNodes) {
2043template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
2044void CallsiteContextGraph<DerivedCCG, FuncTy,
2045 CallTy>::fixupImportantContexts() {
2046 if (ImportantContextIdInfo.empty())
2050 NumImportantContextIds = ImportantContextIdInfo.size();
2052 if (!Opts.memprof_fixup_important)
2055 if (Opts.memprof_export_to_dot)
2056 exportToDot(
"beforestackfixup");
2081 for (
auto &[CurContextId, Info] : ImportantContextIdInfo) {
2082 if (
Info.StackIdsToNode.empty())
2085 ContextNode *PrevNode =
nullptr;
2086 ContextNode *CurNode =
nullptr;
2087 DenseSet<const ContextEdge *> VisitedEdges;
2088 ArrayRef<uint64_t> AllStackIds(
Info.StackIds);
2091 for (
unsigned I = 0;
I < AllStackIds.size();
I++, PrevNode = CurNode) {
2095 auto LenToEnd = AllStackIds.size() -
I;
2103 auto CheckStackIds = AllStackIds.slice(
I, Len);
2104 auto EntryIt =
Info.StackIdsToNode.find(CheckStackIds);
2105 if (EntryIt ==
Info.StackIdsToNode.end())
2107 CurNode = EntryIt->second;
2124 auto *CurEdge = PrevNode->findEdgeFromCaller(CurNode);
2127 if (CurEdge->getContextIds().insert(CurContextId).second) {
2128 NumFixupEdgeIdsInserted++;
2133 NumFixupEdgesAdded++;
2134 DenseSet<uint32_t> ContextIds({CurContextId});
2135 auto AllocType = computeAllocType(ContextIds);
2136 auto NewEdge = std::make_shared<ContextEdge>(
2137 PrevNode, CurNode, AllocType, std::move(ContextIds));
2138 PrevNode->CallerEdges.push_back(NewEdge);
2139 CurNode->CalleeEdges.push_back(NewEdge);
2141 CurEdge = NewEdge.get();
2144 VisitedEdges.
insert(CurEdge);
2147 for (
auto &
Edge : PrevNode->CallerEdges) {
2151 Edge->getContextIds().erase(CurContextId);
2169template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
2170DenseSet<uint32_t> CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
2172 TrimmedAtNodeCache &Cache) {
2174 DenseSet<uint32_t>
Result;
2179 auto GetTrimmedAtNodeIndex = [&Cache](
const ContextNode *
Node) {
2181 Cache.NodeToIndex.try_emplace(Node, Cache.TrimmedAtNodeIds.size());
2182 unsigned Index = It->second;
2187 DenseSet<uint32_t> &Trimmed = Cache.TrimmedAtNodeIds.emplace_back();
2188 for (
const auto &CalleeEdge :
Node->CalleeEdges)
2190 for (
const auto &CallerEdge :
Node->CallerEdges) {
2192 if (Trimmed.
empty())
2200 SmallVector<unsigned, 8> TrimmedAtNodeIdsIndices;
2201 bool AnyTrimmed =
false;
2202 for (ContextNode *Node : StackNodes.
drop_back()) {
2204 if (
Node->Recursive)
2206 unsigned Index = GetTrimmedAtNodeIndex(Node);
2207 AnyTrimmed |= !Cache.TrimmedAtNodeIds[
Index].empty();
2208 TrimmedAtNodeIdsIndices.
push_back(Index);
2227 Result = Cache.TrimmedAtNodeIds[TrimmedAtNodeIdsIndices[0]];
2228 DenseSet<uint32_t> PrefixContextIds;
2229 for (
unsigned I = 1;
I < TrimmedAtNodeIdsIndices.
size();
I++) {
2230 auto *
Edge = StackNodes[
I]->findEdgeFromCallee(StackNodes[
I - 1]);
2234 PrefixContextIds =
Edge->getContextIds();
2237 if (PrefixContextIds.
empty())
2240 PrefixContextIds, Cache.TrimmedAtNodeIds[TrimmedAtNodeIdsIndices[
I]]));
2245template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
2246void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::updateStackNodes() {
2254 DenseMap<uint64_t, std::vector<CallContextInfo>> StackIdToMatchingCalls;
2255 for (
auto &[Func, CallsWithMetadata] : FuncToCallsWithMetadata) {
2256 for (
auto &
Call : CallsWithMetadata) {
2258 if (AllocationCallToContextNodeMap.count(
Call))
2260 std::vector<ContextNode *> StackNodes = getStackNodesForCall(
Call.call());
2263 if (StackNodes.empty())
2267 uint64_t LastId = StackNodes.back()->OrigStackOrAllocId;
2268 StackIdToMatchingCalls[LastId].push_back(
2269 {
Call.call(), std::move(StackNodes),
Func, {}, {}});
2285 return std::lexicographical_compare(
2286 A.begin(),
A.end(),
B.begin(),
B.end(),
2287 [](
const ContextNode *
X,
const ContextNode *
Y) {
2288 return X->OrigStackOrAllocId < Y->OrigStackOrAllocId;
2294 DenseMap<CallInfo, CallInfo> CallToMatchingCall;
2295 for (
auto &Entry : StackIdToMatchingCalls) {
2296 auto &Calls =
Entry.second;
2297 if (Calls.size() == 1)
2299 DenseMap<const FuncTy *, unsigned> FuncToIndex;
2300 for (
const auto &[Idx, CallCtxInfo] :
enumerate(Calls))
2301 FuncToIndex.
insert({CallCtxInfo.Func,
Idx});
2302 auto CallLess = [&FuncToIndex, &StackIdsLess](
const CallContextInfo &
A,
2303 const CallContextInfo &
B) {
2304 return A.StackNodes.size() >
B.StackNodes.size() ||
2305 (
A.StackNodes.size() ==
B.StackNodes.size() &&
2306 (StackIdsLess(
A.StackNodes,
B.StackNodes) ||
2307 (
A.StackNodes ==
B.StackNodes &&
2308 FuncToIndex[
A.Func] < FuncToIndex[
B.Func])));
2315 unsigned FirstInRun = 0;
2316 for (
unsigned I = 1;
I < Calls.size();
I++) {
2317 if (Calls[
I].Func != Calls[FirstInRun].Func ||
2318 Calls[
I].StackNodes != Calls[FirstInRun].StackNodes) {
2322 CallToMatchingCall[Calls[
I].Call] = Calls[FirstInRun].Call;
2332 DenseMap<uint32_t, DenseSet<uint32_t>> OldToNewContextIds;
2348 std::vector<ArrayRef<ContextNode *>> TrimmedInlinedDupCreatorNodes;
2351 DenseMap<uint32_t, SmallVector<std::pair<uint32_t, unsigned>, 1>>
2352 OrigToTrimmedInlinedDups;
2353 if (Opts.memprof_assign_trimmed_inlined_contexts) {
2354 TrimmedAtNodeCache Cache;
2355 for (
auto &Entry : StackIdToMatchingCalls) {
2356 auto &Calls =
Entry.second;
2359 if (Calls[0].StackNodes.back()->Recursive)
2361 for (
unsigned I = 0;
I < Calls.size();
I++) {
2362 auto &CallCtxInfo = Calls[
I];
2363 auto &StackNodes = CallCtxInfo.StackNodes;
2366 if (StackNodes.size() < 2)
2370 if (CallToMatchingCall.
contains(CallCtxInfo.Call))
2372 auto Trimmed = computeTrimmedInlinedContextIds(StackNodes, Cache);
2373 if (Trimmed.
empty())
2375 unsigned CreatorIdx = TrimmedInlinedDupCreatorNodes.size();
2376 TrimmedInlinedDupCreatorNodes.push_back(StackNodes);
2377 CallCtxInfo.TrimmedInlinedDupIds = duplicateContextIds(
2378 Trimmed, OldToNewContextIds, [&](uint32_t OldId, uint32_t NewId) {
2379 OrigToTrimmedInlinedDups[OldId].push_back({NewId, CreatorIdx});
2381 NumCallsAssignedTrimmedInlinedContexts++;
2382 NumTrimmedInlinedContextIds += Trimmed.
size();
2401 auto AddTrimmedInlinedDups = [&](DenseSet<uint32_t> &SavedContextIds,
2402 const ContextNode *LastNode) {
2403 SmallVector<uint32_t> DupIdsToAdd;
2406 for (
auto [DupId, CreatorIdx] : Dups) {
2408 TrimmedInlinedDupCreatorNodes[CreatorIdx];
2423 if (OrigToTrimmedInlinedDups.
size() < SavedContextIds.
size()) {
2424 for (
auto &[OrigId, Dups] : OrigToTrimmedInlinedDups)
2425 if (SavedContextIds.
contains(OrigId))
2428 for (
auto Id : SavedContextIds) {
2429 auto It = OrigToTrimmedInlinedDups.find(Id);
2430 if (It != OrigToTrimmedInlinedDups.end())
2431 AddDups(It->second);
2434 SavedContextIds.insert_range(DupIdsToAdd);
2436 for (
auto &It : StackIdToMatchingCalls) {
2437 auto &Calls = It.getSecond();
2439 if (Calls.size() == 1) {
2440 auto &StackNodes = Calls[0].StackNodes;
2441 if (StackNodes.size() == 1)
2450 ContextNode *LastNode = Calls[0].StackNodes.back();
2453 assert(LastNode == getNodeForStackId(LastId));
2455 if (LastNode->Recursive)
2460 DenseSet<uint32_t> LastNodeContextIds = LastNode->getContextIds();
2468 DenseSet<const FuncTy *> MatchingIdsFuncSet;
2471 for (
unsigned I = 0;
I < Calls.size();
I++) {
2472 auto &[
Call, StackNodes,
Func, SavedContextIds, TrimmedInlinedDupIds] =
2474 assert(SavedContextIds.empty());
2475 assert(LastNode == StackNodes.back());
2480 if (
I > 0 && StackNodes != Calls[
I - 1].StackNodes)
2481 MatchingIdsFuncSet.
clear();
2488 bool DuplicateContextIds =
false;
2489 for (
unsigned J =
I + 1; J < Calls.size(); J++) {
2490 auto &CallCtxInfo = Calls[J];
2491 if (CallCtxInfo.StackNodes != StackNodes)
2493 auto *NextFunc = CallCtxInfo.Func;
2494 if (NextFunc != Func) {
2497 DuplicateContextIds =
true;
2509 DenseSet<uint32_t> StackSequenceContextIds = LastNodeContextIds;
2511 ContextNode *PrevNode = LastNode;
2512 ContextNode *CurNode = LastNode;
2517 for (
auto NodeIter = StackNodes.rbegin() + 1;
2518 NodeIter != StackNodes.rend(); NodeIter++) {
2519 CurNode = *NodeIter;
2523 if (CurNode->Recursive) {
2528 auto *
Edge = CurNode->findEdgeFromCaller(PrevNode);
2549 if (StackSequenceContextIds.
empty()) {
2562 if (LastId != getLastStackId(
Call)) {
2563 for (
const auto &PE : LastNode->CallerEdges) {
2564 set_subtract(StackSequenceContextIds, PE->getContextIds());
2565 if (StackSequenceContextIds.
empty())
2569 if (StackSequenceContextIds.
empty())
2581 MatchingIdsFuncSet.
insert(Func);
2590 OldToNewContextIds.
reserve(OldToNewContextIds.
size() +
2591 StackSequenceContextIds.
size());
2594 ? duplicateContextIds(StackSequenceContextIds, OldToNewContextIds)
2595 : StackSequenceContextIds;
2596 assert(!SavedContextIds.empty());
2597 if (!OrigToTrimmedInlinedDups.empty())
2598 AddTrimmedInlinedDups(SavedContextIds, LastNode);
2600 if (!DuplicateContextIds) {
2604 set_subtract(LastNodeContextIds, StackSequenceContextIds);
2605 if (LastNodeContextIds.
empty())
2612 propagateDuplicateContextIds(OldToNewContextIds);
2614 if (Opts.memprof_verify_ccg)
2622 DenseSet<const ContextNode *> Visited;
2624 ImportantContextIdInfo.keys());
2625 for (
auto &Entry : AllocationCallToContextNodeMap)
2626 assignStackNodesPostOrder(
Entry.second, Visited, StackIdToMatchingCalls,
2627 CallToMatchingCall, ImportantContextIds);
2629 fixupImportantContexts();
2631 if (Opts.memprof_verify_ccg)
2635uint64_t ModuleCallsiteContextGraph::getLastStackId(Instruction *
Call) {
2636 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(
2638 return CallsiteContext.
back();
2641uint64_t IndexCallsiteContextGraph::getLastStackId(IndexCall &
Call) {
2643 CallStack<CallsiteInfo, SmallVector<unsigned>::const_iterator>
2646 return Index.getStackIdAtIndex(CallsiteContext.
back());
2662 auto Pos =
F.getName().find_last_of(
'.');
2665 bool Err =
F.getName().drop_front(Pos + 1).getAsInteger(10, CloneNo);
2671std::string ModuleCallsiteContextGraph::getLabel(
const Function *Func,
2672 const Instruction *
Call,
2673 unsigned CloneNo)
const {
2679std::string IndexCallsiteContextGraph::getLabel(
const FunctionSummary *Func,
2680 const IndexCall &
Call,
2681 unsigned CloneNo)
const {
2682 auto VI = FSToVIMap.find(Func);
2683 assert(VI != FSToVIMap.end());
2686 return CallerName +
" -> alloc";
2689 return CallerName +
" -> " +
2691 Callsite->Clones[CloneNo]);
2695std::string ModuleCallsiteContextGraph::getFuncName(
const Function *Func,
2696 unsigned CloneNo)
const {
2702void ModuleCallsiteContextGraph::populateFunctionsWithCallers() {
2705 for (
const auto &
F :
Mod)
2707 FunctionsWithCallers.insert(&
F);
2710std::string IndexCallsiteContextGraph::getFuncName(
const FunctionSummary *Func,
2711 unsigned CloneNo)
const {
2714 auto VI = FSToVIMap.find(Func);
2715 if (VI != FSToVIMap.end()) {
2716 if (!
VI->second.name().empty())
2724bool IndexCallsiteContextGraph::isFuncDead(
const FunctionSummary *Func)
const {
2725 return Index.withGlobalValueDeadStripping() &&
Func && !
Func->isLive();
2728void IndexCallsiteContextGraph::populateFunctionsWithCallers() {
2729 for (
const auto &
I : Index) {
2731 for (
const auto &S :
VI.getSummaryList()) {
2733 !isPrevailing(
VI.getGUID(), S.get()))
2735 if (
Index.withGlobalValueDeadStripping() && !S->isLive())
2737 auto AddReferenced = [&](ValueInfo RefVI) {
2738 for (
const auto &RefS : RefVI.getSummaryList()) {
2739 const GlobalValueSummary *
Base = RefS->getBaseObject();
2741 FunctionsWithCallers.insert(RefFS);
2745 for (
const auto &RefVI : S->refs())
2746 AddReferenced(RefVI);
2749 for (
const auto &CallEdge :
FS->calls())
2750 AddReferenced(CallEdge.first);
2755std::vector<ModuleCallsiteContextGraph::ContextNode *>
2756ModuleCallsiteContextGraph::getStackNodesForCall(Instruction *
Call) {
2757 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(
2759 return getStackNodesForCallsite<MDNode, MDNode::op_iterator>(CallsiteContext);
2762std::vector<IndexCallsiteContextGraph::ContextNode *>
2763IndexCallsiteContextGraph::getStackNodesForCall(IndexCall &
Call) {
2765 CallStack<CallsiteInfo, SmallVector<unsigned>::const_iterator>
2767 return getStackNodesForCallsite<CallsiteInfo,
2768 SmallVector<unsigned>::const_iterator>(
2772template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
2773template <
class NodeT,
class IteratorT>
2775 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *>
2776CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getStackNodesForCallsite(
2777 CallStack<NodeT, IteratorT> &CallsiteContext) {
2778 std::vector<ContextNode *> StackNodes;
2779 for (
auto IdOrIndex : CallsiteContext) {
2780 auto StackId = getStackId(IdOrIndex);
2781 ContextNode *
Node = getNodeForStackId(StackId);
2784 StackNodes.push_back(Node);
2797 if (!BB.hasAddressTaken())
2799 for (
const User *U :
2807ModuleCallsiteContextGraph::ModuleCallsiteContextGraph(
2809 llvm::function_ref<OptimizationRemarkEmitter &(
Function *)> OREGetter)
2814 std::map<uint64_t, uint32_t> TotalSizeToContextIdTopNCold;
2820 bool HasMemProfMetadata =
false;
2821 for (
auto &BB :
F) {
2822 for (
auto &
I : BB) {
2823 if (!
I.getMetadata(LLVMContext::MD_memprof) &&
2824 !
I.getMetadata(LLVMContext::MD_callsite))
2826 HasMemProfMetadata =
true;
2827 I.setMetadata(LLVMContext::MD_memprof,
nullptr);
2828 I.setMetadata(LLVMContext::MD_callsite,
nullptr);
2831 if (HasMemProfMetadata)
2832 NumFuncsSkippedUnsafeToClone++;
2835 std::vector<CallInfo> CallsWithMetadata;
2836 for (
auto &BB :
F) {
2837 for (
auto &
I : BB) {
2840 if (
auto *MemProfMD =
I.getMetadata(LLVMContext::MD_memprof)) {
2841 CallsWithMetadata.push_back(&
I);
2842 auto *AllocNode = addAllocNode(&
I, &
F);
2843 auto *CallsiteMD =
I.getMetadata(LLVMContext::MD_callsite);
2847 for (
auto &MDOp : MemProfMD->operands()) {
2849 std::vector<ContextTotalSize> ContextSizeInfo;
2851 if (MIBMD->getNumOperands() > 2) {
2852 for (
unsigned I = 2;
I < MIBMD->getNumOperands();
I++) {
2853 MDNode *ContextSizePair =
2862 ContextSizeInfo.push_back({FullStackId, TotalSize});
2868 addStackNodesForMIB<MDNode, MDNode::op_iterator>(
2869 AllocNode, StackContext, CallsiteContext,
2871 TotalSizeToContextIdTopNCold);
2875 if (Opts.memprof_export_to_dot &&
2876 AllocNode->OrigStackOrAllocId == Opts.memprof_dot_alloc_id)
2877 DotAllocContextIds = AllocNode->getContextIds();
2881 I.setMetadata(LLVMContext::MD_memprof,
nullptr);
2882 I.setMetadata(LLVMContext::MD_callsite,
nullptr);
2885 else if (
I.getMetadata(LLVMContext::MD_callsite)) {
2886 CallsWithMetadata.push_back(&
I);
2890 if (!CallsWithMetadata.empty())
2891 FuncToCallsWithMetadata[&
F] = CallsWithMetadata;
2894 if (Opts.memprof_dump_ccg) {
2895 dbgs() <<
"CCG before updating call stack chains:\n";
2899 if (Opts.memprof_export_to_dot)
2900 exportToDot(
"prestackupdate");
2904 if (Opts.memprof_export_to_dot)
2905 exportToDot(
"poststackupdate");
2907 handleCallsitesWithMultipleTargets();
2912 for (
auto &FuncEntry : FuncToCallsWithMetadata)
2913 for (
auto &
Call : FuncEntry.second)
2914 Call.call()->setMetadata(LLVMContext::MD_callsite,
nullptr);
2920IndexCallsiteContextGraph::findAliaseeGUIDsPrevailingInDifferentModule() {
2921 DenseSet<GlobalValue::GUID> AliaseeGUIDs;
2922 for (
auto &
I : Index) {
2924 for (
auto &S :
VI.getSummaryList()) {
2929 auto *AliaseeSummary = &AS->getAliasee();
2937 !isPrevailing(
VI.getGUID(), S.get()))
2942 auto AliaseeGUID = AS->getAliaseeGUID();
2944 if (!isPrevailing(AliaseeGUID, AliaseeSummary))
2945 AliaseeGUIDs.
insert(AliaseeGUID);
2948 AliaseesPrevailingInDiffModuleFromAlias += AliaseeGUIDs.
size();
2949 return AliaseeGUIDs;
2952IndexCallsiteContextGraph::IndexCallsiteContextGraph(
2953 const IPOOptions &Opts, ModuleSummaryIndex &Index,
2956 : CallsiteContextGraph(Opts),
Index(
Index), isPrevailing(isPrevailing) {
2963 findAliaseeGUIDsPrevailingInDifferentModule();
2967 std::map<uint64_t, uint32_t> TotalSizeToContextIdTopNCold;
2972 for (
const auto &
I : Index.sortedGlobalValueSummariesRange()) {
2973 auto VI = Index.getValueInfo(
I);
2974 if (GUIDsToSkip.
contains(VI.getGUID()))
2976 for (
auto &S : VI.getSummaryList()) {
2985 !isPrevailing(VI.getGUID(), S.get()))
2994 if (
FS->fflags().HasEscapingBlockAddress) {
2995 if (!
FS->allocs().empty() || !
FS->callsites().empty())
2996 NumFuncsSkippedUnsafeToClone++;
2999 std::vector<CallInfo> CallsWithMetadata;
3000 if (!
FS->allocs().empty()) {
3001 for (
auto &AN :
FS->mutableAllocs()) {
3006 if (AN.MIBs.empty())
3008 IndexCall AllocCall(&AN);
3009 CallsWithMetadata.push_back(AllocCall);
3010 auto *AllocNode = addAllocNode(AllocCall, FS);
3018 AN.ContextSizeInfos.size() == AN.MIBs.size());
3020 for (
auto &MIB : AN.MIBs) {
3023 std::vector<ContextTotalSize> ContextSizeInfo;
3024 if (!AN.ContextSizeInfos.empty()) {
3025 for (
auto [FullStackId, TotalSize] : AN.ContextSizeInfos[
I])
3026 ContextSizeInfo.push_back({FullStackId, TotalSize});
3028 addStackNodesForMIB<MIBInfo, SmallVector<unsigned>::const_iterator>(
3029 AllocNode, StackContext, EmptyContext, MIB.AllocType,
3030 ContextSizeInfo, TotalSizeToContextIdTopNCold);
3035 if (Opts.memprof_export_to_dot &&
3036 AllocNode->OrigStackOrAllocId == Opts.memprof_dot_alloc_id)
3037 DotAllocContextIds = AllocNode->getContextIds();
3043 AN.Versions[0] = (
uint8_t)allocTypeToUse(AllocNode->AllocTypes);
3047 if (!
FS->callsites().empty())
3048 for (
auto &SN :
FS->mutableCallsites()) {
3049 IndexCall StackNodeCall(&SN);
3050 CallsWithMetadata.push_back(StackNodeCall);
3053 if (!CallsWithMetadata.empty())
3054 FuncToCallsWithMetadata[
FS] = CallsWithMetadata;
3056 if (!
FS->allocs().empty() || !
FS->callsites().empty())
3061 if (Opts.memprof_dump_ccg) {
3062 dbgs() <<
"CCG before updating call stack chains:\n";
3066 if (Opts.memprof_export_to_dot)
3067 exportToDot(
"prestackupdate");
3071 if (Opts.memprof_export_to_dot)
3072 exportToDot(
"poststackupdate");
3074 handleCallsitesWithMultipleTargets();
3079template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3080void CallsiteContextGraph<DerivedCCG, FuncTy,
3081 CallTy>::handleCallsitesWithMultipleTargets() {
3096 std::vector<std::pair<CallInfo, ContextNode *>> NewCallToNode;
3097 for (
auto &Entry : NonAllocationCallToContextNodeMap) {
3098 auto *
Node = Entry.second;
3107 std::vector<CallInfo> AllCalls;
3108 AllCalls.reserve(
Node->MatchingCalls.size() + 1);
3109 AllCalls.push_back(
Node->Call);
3123 if (partitionCallsByCallee(
Node, AllCalls, NewCallToNode))
3126 auto It = AllCalls.begin();
3128 for (; It != AllCalls.end(); ++It) {
3131 for (
auto EI =
Node->CalleeEdges.begin(); EI !=
Node->CalleeEdges.end();
3134 if (!Edge->Callee->hasCall())
3136 assert(NodeToCallingFunc.count(Edge->Callee));
3138 if (!calleesMatch(
ThisCall.call(), EI, TailCallToContextNodeMap)) {
3147 if (
Node->Call != ThisCall) {
3148 Node->setCall(ThisCall);
3159 Node->MatchingCalls.clear();
3162 if (It == AllCalls.end()) {
3163 RemovedEdgesWithMismatchedCallees++;
3167 Node->setCall(CallInfo());
3172 for (++It; It != AllCalls.end(); ++It) {
3176 Node->MatchingCalls.push_back(ThisCall);
3185 NonAllocationCallToContextNodeMap.remove_if([](
const auto &it) {
3186 return !it.second->hasCall() || it.second->Call != it.first;
3190 for (
auto &[
Call,
Node] : NewCallToNode)
3191 NonAllocationCallToContextNodeMap[
Call] =
Node;
3195 for (
auto &[
Call,
Node] : TailCallToContextNodeMap)
3196 NonAllocationCallToContextNodeMap[
Call] =
Node;
3199template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3200bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::partitionCallsByCallee(
3202 std::vector<std::pair<CallInfo, ContextNode *>> &NewCallToNode) {
3206 struct CallsWithSameCallee {
3207 std::vector<CallInfo> Calls;
3208 ContextNode *
Node =
nullptr;
3214 for (
auto ThisCall : AllCalls) {
3215 auto *
F = getCalleeFunc(
ThisCall.call());
3217 CalleeFuncToCallInfo[
F].Calls.push_back(ThisCall);
3226 for (
const auto &Edge :
Node->CalleeEdges) {
3227 if (!Edge->Callee->hasCall())
3229 const FuncTy *ProfiledCalleeFunc = NodeToCallingFunc[Edge->Callee];
3230 if (CalleeFuncToCallInfo.
contains(ProfiledCalleeFunc))
3231 CalleeNodeToCallInfo[Edge->Callee] =
3232 &CalleeFuncToCallInfo[ProfiledCalleeFunc];
3238 if (CalleeNodeToCallInfo.
empty())
3250 ContextNode *UnmatchedCalleesNode =
nullptr;
3252 bool UsedOrigNode =
false;
3257 auto CalleeEdges =
Node->CalleeEdges;
3258 for (
auto &Edge : CalleeEdges) {
3259 if (!Edge->Callee->hasCall())
3264 ContextNode *CallerNodeToUse =
nullptr;
3268 if (!CalleeNodeToCallInfo.
contains(Edge->Callee)) {
3269 if (!UnmatchedCalleesNode)
3270 UnmatchedCalleesNode =
3271 createNewNode(
false, NodeToCallingFunc[
Node]);
3272 CallerNodeToUse = UnmatchedCalleesNode;
3276 auto *Info = CalleeNodeToCallInfo[Edge->Callee];
3279 if (!UsedOrigNode) {
3282 Node->MatchingCalls.clear();
3283 UsedOrigNode =
true;
3286 createNewNode(
false, NodeToCallingFunc[
Node]);
3287 assert(!Info->Calls.empty());
3290 Info->Node->setCall(Info->Calls.front());
3296 NewCallToNode.push_back({Info->Node->Call, Info->Node});
3298 CallerNodeToUse = Info->Node;
3302 if (CallerNodeToUse ==
Node)
3305 moveCalleeEdgeToNewCaller(Edge, CallerNodeToUse);
3312 for (
auto &
I : CalleeNodeToCallInfo)
3313 removeNoneTypeCallerEdges(
I.second->Node);
3314 if (UnmatchedCalleesNode)
3315 removeNoneTypeCallerEdges(UnmatchedCalleesNode);
3316 removeNoneTypeCallerEdges(
Node);
3329 return Index.getStackIdAtIndex(IdOrIndex);
3332template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3333bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::calleesMatch(
3334 CallTy
Call, EdgeIter &EI,
3335 MapVector<CallInfo, ContextNode *> &TailCallToContextNodeMap) {
3337 const FuncTy *ProfiledCalleeFunc = NodeToCallingFunc[
Edge->Callee];
3338 const FuncTy *CallerFunc = NodeToCallingFunc[
Edge->Caller];
3341 std::vector<std::pair<CallTy, FuncTy *>> FoundCalleeChain;
3342 if (!calleeMatchesFunc(
Call, ProfiledCalleeFunc, CallerFunc,
3347 if (FoundCalleeChain.empty())
3351 auto *CurEdge =
Callee->findEdgeFromCaller(Caller);
3355 CurEdge->ContextIds.insert_range(
Edge->ContextIds);
3356 CurEdge->AllocTypes |=
Edge->AllocTypes;
3361 auto NewEdge = std::make_shared<ContextEdge>(
3362 Callee, Caller,
Edge->AllocTypes,
Edge->ContextIds);
3363 Callee->CallerEdges.push_back(NewEdge);
3364 if (Caller ==
Edge->Caller) {
3368 EI =
Caller->CalleeEdges.insert(EI, NewEdge);
3371 "Iterator position not restored after insert and increment");
3373 Caller->CalleeEdges.push_back(NewEdge);
3378 auto *CurCalleeNode =
Edge->Callee;
3379 for (
auto &[NewCall, Func] : FoundCalleeChain) {
3380 ContextNode *NewNode =
nullptr;
3382 if (TailCallToContextNodeMap.
count(NewCall)) {
3383 NewNode = TailCallToContextNodeMap[NewCall];
3384 NewNode->AllocTypes |=
Edge->AllocTypes;
3386 FuncToCallsWithMetadata[
Func].push_back({NewCall});
3388 NewNode = createNewNode(
false, Func, NewCall);
3389 TailCallToContextNodeMap[NewCall] = NewNode;
3390 NewNode->AllocTypes =
Edge->AllocTypes;
3394 AddEdge(NewNode, CurCalleeNode);
3396 CurCalleeNode = NewNode;
3400 AddEdge(
Edge->Caller, CurCalleeNode);
3408 removeEdgeFromGraph(
Edge.get(), &EI,
true);
3420bool ModuleCallsiteContextGraph::findProfiledCalleeThroughTailCalls(
3422 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain,
3423 bool &FoundMultipleCalleeChains) {
3426 if (
Depth > Opts.memprof_tail_call_search_depth)
3430 FoundCalleeChain.push_back({Callsite,
F});
3445 bool FoundSingleCalleeChain =
false;
3446 for (
auto &BB : *CalleeFunc) {
3447 for (
auto &
I : BB) {
3449 if (!CB || !CB->isTailCall())
3451 auto *CalledValue = CB->getCalledOperand();
3452 auto *CalledFunction = CB->getCalledFunction();
3453 if (CalledValue && !CalledFunction) {
3454 CalledValue = CalledValue->stripPointerCasts();
3461 assert(!CalledFunction &&
3462 "Expected null called function in callsite for alias");
3465 if (!CalledFunction)
3467 if (CalledFunction == ProfiledCallee) {
3468 if (FoundSingleCalleeChain) {
3469 FoundMultipleCalleeChains =
true;
3472 FoundSingleCalleeChain =
true;
3473 FoundProfiledCalleeCount++;
3474 FoundProfiledCalleeDepth +=
Depth;
3475 if (
Depth > FoundProfiledCalleeMaxDepth)
3476 FoundProfiledCalleeMaxDepth =
Depth;
3477 SaveCallsiteInfo(&
I, CalleeFunc);
3478 }
else if (findProfiledCalleeThroughTailCalls(
3479 ProfiledCallee, CalledFunction,
Depth + 1,
3480 FoundCalleeChain, FoundMultipleCalleeChains)) {
3483 assert(!FoundMultipleCalleeChains);
3484 if (FoundSingleCalleeChain) {
3485 FoundMultipleCalleeChains =
true;
3488 FoundSingleCalleeChain =
true;
3489 SaveCallsiteInfo(&
I, CalleeFunc);
3490 }
else if (FoundMultipleCalleeChains)
3495 return FoundSingleCalleeChain;
3498const Function *ModuleCallsiteContextGraph::getCalleeFunc(Instruction *
Call) {
3500 if (!CB->getCalledOperand() || CB->isIndirectCall())
3502 auto *CalleeVal = CB->getCalledOperand()->stripPointerCasts();
3509bool ModuleCallsiteContextGraph::calleeMatchesFunc(
3511 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain) {
3513 if (!CB->getCalledOperand() || CB->isIndirectCall())
3515 auto *CalleeVal = CB->getCalledOperand()->stripPointerCasts();
3517 if (CalleeFunc == Func)
3520 if (Alias && Alias->getAliasee() == Func)
3531 bool FoundMultipleCalleeChains =
false;
3532 if (!findProfiledCalleeThroughTailCalls(Func, CalleeVal,
Depth,
3534 FoundMultipleCalleeChains)) {
3535 LLVM_DEBUG(
dbgs() <<
"Not found through unique tail call chain: "
3536 <<
Func->getName() <<
" from " << CallerFunc->
getName()
3537 <<
" that actually called " << CalleeVal->getName()
3538 << (FoundMultipleCalleeChains
3539 ?
" (found multiple possible chains)"
3542 if (FoundMultipleCalleeChains)
3543 FoundProfiledCalleeNonUniquelyCount++;
3550 if (
llvm::any_of(FoundCalleeChain, [](
const auto &Entry) {
3553 FoundCalleeChain.clear();
3560bool ModuleCallsiteContextGraph::sameCallee(Instruction *Call1,
3561 Instruction *Call2) {
3563 if (!CB1->getCalledOperand() || CB1->isIndirectCall())
3565 auto *CalleeVal1 = CB1->getCalledOperand()->stripPointerCasts();
3568 if (!CB2->getCalledOperand() || CB2->isIndirectCall())
3570 auto *CalleeVal2 = CB2->getCalledOperand()->stripPointerCasts();
3572 return CalleeFunc1 == CalleeFunc2;
3575bool IndexCallsiteContextGraph::findProfiledCalleeThroughTailCalls(
3576 ValueInfo ProfiledCallee, ValueInfo CurCallee,
unsigned Depth,
3577 std::vector<std::pair<ValueInfo, FunctionSummary *>> &FoundCalleeChain,
3578 bool &FoundMultipleCalleeChains) {
3581 if (
Depth > Opts.memprof_tail_call_search_depth)
3588 auto SaveTailCall = [&](ValueInfo
Callee, FunctionSummary *
FS) {
3589 FoundCalleeChain.push_back({
Callee,
FS});
3598 auto IsProfiledCallee = [&](ValueInfo
Callee) {
3599 if (Callee == ProfiledCallee)
3601 for (
auto &S :
Callee.getSummaryList()) {
3603 !isPrevailing(
Callee.getGUID(), S.get()))
3606 return AS && AS->getAliaseeVI() == ProfiledCallee;
3615 bool FoundSingleCalleeChain =
false;
3618 !isPrevailing(CurCallee.
getGUID(), S.get()))
3623 auto FSVI = CurCallee;
3626 FSVI = AS->getAliaseeVI();
3627 for (
auto &CallEdge :
FS->calls()) {
3628 if (!CallEdge.second.hasTailCall())
3633 if (CallEdge.second.hasIndirectCall() &&
3634 !Opts.memprof_indirect_tail_call_search)
3636 if (IsProfiledCallee(CallEdge.first)) {
3637 if (FoundSingleCalleeChain) {
3638 FoundMultipleCalleeChains =
true;
3641 FoundSingleCalleeChain =
true;
3642 FoundProfiledCalleeCount++;
3643 FoundProfiledCalleeDepth +=
Depth;
3644 if (
Depth > FoundProfiledCalleeMaxDepth)
3645 FoundProfiledCalleeMaxDepth =
Depth;
3646 if (CallEdge.second.hasIndirectCall())
3647 FoundProfiledCalleeIndirectTailCallCount++;
3648 SaveTailCall(CallEdge.first, FS);
3650 assert(!FSToVIMap.count(FS) || FSToVIMap[FS] == FSVI);
3651 FSToVIMap[
FS] = FSVI;
3652 }
else if (findProfiledCalleeThroughTailCalls(
3653 ProfiledCallee, CallEdge.first,
Depth + 1,
3654 FoundCalleeChain, FoundMultipleCalleeChains)) {
3657 assert(!FoundMultipleCalleeChains);
3658 if (FoundSingleCalleeChain) {
3659 FoundMultipleCalleeChains =
true;
3662 FoundSingleCalleeChain =
true;
3663 if (CallEdge.second.hasIndirectCall())
3664 FoundProfiledCalleeIndirectTailCallCount++;
3665 SaveTailCall(CallEdge.first, FS);
3667 assert(!FSToVIMap.count(FS) || FSToVIMap[FS] == FSVI);
3668 FSToVIMap[
FS] = FSVI;
3669 }
else if (FoundMultipleCalleeChains)
3674 return FoundSingleCalleeChain;
3677const FunctionSummary *
3678IndexCallsiteContextGraph::getCalleeFunc(IndexCall &
Call) {
3680 if (
Callee.getSummaryList().empty())
3685bool IndexCallsiteContextGraph::calleeMatchesFunc(
3686 IndexCall &
Call,
const FunctionSummary *Func,
3687 const FunctionSummary *CallerFunc,
3688 std::vector<std::pair<IndexCall, FunctionSummary *>> &FoundCalleeChain) {
3692 AliasSummary *Alias =
3693 Callee.getSummaryList().empty()
3696 assert(FSToVIMap.count(Func));
3697 auto FuncVI = FSToVIMap[
Func];
3698 if (Callee == FuncVI ||
3713 bool FoundMultipleCalleeChains =
false;
3714 std::vector<std::pair<ValueInfo, FunctionSummary *>> FoundCalleeVIChain;
3715 if (!findProfiledCalleeThroughTailCalls(FuncVI, Callee,
Depth,
3717 FoundMultipleCalleeChains)) {
3718 LLVM_DEBUG(
dbgs() <<
"Not found through unique tail call chain: " << FuncVI
3719 <<
" from " << FSToVIMap[CallerFunc]
3720 <<
" that actually called " << Callee
3721 << (FoundMultipleCalleeChains
3722 ?
" (found multiple possible chains)"
3725 if (FoundMultipleCalleeChains)
3726 FoundProfiledCalleeNonUniquelyCount++;
3733 if (
llvm::any_of(FoundCalleeVIChain, [](
const auto &Entry) {
3734 return Entry.second->fflags().HasEscapingBlockAddress;
3743 for (
auto &[CalleeVI, FS] : FoundCalleeVIChain) {
3744 auto &CallsiteInfoPtr =
3745 FunctionCalleesToSynthesizedCallsiteInfos[
FS][CalleeVI];
3746 if (!CallsiteInfoPtr)
3750 std::make_unique<CallsiteInfo>(CalleeVI, SmallVector<unsigned>());
3751 FoundCalleeChain.push_back({CallsiteInfoPtr.get(),
FS});
3757bool IndexCallsiteContextGraph::sameCallee(IndexCall &Call1, IndexCall &Call2) {
3760 return Callee1 == Callee2;
3763template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3764void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::dump()
3770template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3771void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::print(
3772 raw_ostream &OS)
const {
3773 OS <<
"Node " <<
this <<
"\n";
3777 OS <<
" (recursive)";
3779 if (!MatchingCalls.empty()) {
3780 OS <<
"\tMatchingCalls:\n";
3781 for (
auto &MatchingCall : MatchingCalls) {
3783 MatchingCall.print(OS);
3787 OS <<
"\tNodeId: " <<
NodeId <<
"\n";
3789 OS <<
"\tContextIds:";
3791 auto ContextIds = getContextIds();
3792 std::vector<uint32_t> SortedIds(ContextIds.
begin(), ContextIds.
end());
3793 std::sort(SortedIds.begin(), SortedIds.end());
3794 for (
auto Id : SortedIds)
3797 OS <<
"\tCalleeEdges:\n";
3798 for (
auto &
Edge : CalleeEdges)
3799 OS <<
"\t\t" << *
Edge <<
" (Callee NodeId: " <<
Edge->Callee->NodeId
3801 OS <<
"\tCallerEdges:\n";
3802 for (
auto &
Edge : CallerEdges)
3803 OS <<
"\t\t" << *
Edge <<
" (Caller NodeId: " <<
Edge->Caller->NodeId
3805 if (!Clones.empty()) {
3808 for (
auto *
C : Clones)
3809 OS <<
LS <<
C <<
" NodeId: " <<
C->NodeId;
3811 }
else if (CloneOf) {
3812 OS <<
"\tClone of " << CloneOf <<
" NodeId: " << CloneOf->NodeId <<
"\n";
3816template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3817void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge::dump()
3823template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3824void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge::print(
3825 raw_ostream &OS)
const {
3826 OS <<
"Edge from Callee " <<
Callee <<
" to Caller: " <<
Caller
3827 << (IsBackedge ?
" (BE)" :
"")
3829 OS <<
" ContextIds:";
3830 std::vector<uint32_t> SortedIds(ContextIds.
begin(), ContextIds.
end());
3831 std::sort(SortedIds.begin(), SortedIds.end());
3832 for (
auto Id : SortedIds)
3836template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3837void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::dump()
const {
3841template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3842void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::print(
3843 raw_ostream &OS)
const {
3844 OS <<
"Callsite Context Graph:\n";
3845 using GraphType =
const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
3847 if (
Node->isRemoved())
3854template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3855void CallsiteContextGraph<DerivedCCG, FuncTy,
3856 CallTy>::capturePreCloningContextInfo() {
3857 for (
const auto &Entry : AllocationCallToContextNodeMap) {
3858 const ContextNode *AllocNode =
Entry.second;
3862 for (
const auto &
Edge : AllocNode->CallerEdges) {
3863 if (!
Edge->isRemoved() &&
Edge->Caller->hasCall()) {
3864 PreCloningAllocHasMatchedCaller.insert(AllocNode);
3868 DenseSet<uint32_t> ContextIds = AllocNode->getContextIds();
3869 for (uint32_t Id : ContextIds) {
3870 PreCloningContextInfo
Info;
3876 Info.Chain.push_back(AllocNode);
3877 SmallPtrSet<const ContextNode *, 16> Visited;
3878 Visited.
insert(AllocNode);
3879 const ContextNode *Cur = AllocNode;
3881 const ContextNode *
Next =
nullptr;
3882 for (
const auto &
Edge : Cur->CallerEdges) {
3883 if (
Edge->isRemoved() ||
Edge->IsBackedge)
3885 if (
Edge->getContextIds().contains(Id) &&
3892 for (
const auto &
Edge : Cur->CallerEdges) {
3893 if (
Edge->isRemoved())
3895 if (
Edge->getContextIds().contains(Id) &&
3912 Info.MaxMatchedFrame = 0;
3913 for (
unsigned I = 1;
I <
Info.Chain.size(); ++
I) {
3914 if (
Info.Chain[
I]->hasCall()) {
3915 Info.MaxMatchedFrame =
I;
3917 const ContextNode *Unmatched =
Info.Chain[
I];
3918 Info.UnmatchedStackId = Unmatched->OrigStackOrAllocId;
3919 Info.StoppedAtRecursive = Unmatched->Recursive;
3923 if (
auto It = NodeToCallingFunc.find(Unmatched);
3924 It != NodeToCallingFunc.end()) {
3925 Info.StoppedAtMismatchedCallee =
true;
3926 Info.UnmatchedCallingFunc = It->second;
3936 if (
Info.MaxMatchedFrame > 0 &&
3937 Info.MaxMatchedFrame + 1 ==
Info.Chain.size()) {
3938 const ContextNode *OutermostMatchedNode =
3940 for (
const auto &
Edge : OutermostMatchedNode->CallerEdges) {
3941 if (!
Edge->isRemoved() &&
Edge->Caller->hasCall()) {
3942 Info.OutermostMatchedNodeHasOtherCallers =
true;
3948 PreCloningContextInfoMap[
Id] = std::move(Info);
3953template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
3955CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::formatContextReportSuffix(
3956 const ContextNode *Node, uint32_t Id)
const {
3957 auto InfoIt = PreCloningContextInfoMap.find(Id);
3958 if (InfoIt == PreCloningContextInfoMap.end())
3960 const PreCloningContextInfo &
Info = InfoIt->second;
3967 const ContextNode *OrigAlloc =
Node->getOrigNode();
3968 const FuncTy *AllocFunc = getCallingFunc(OrigAlloc);
3969 unsigned AllocCloneNo =
Node->Call.cloneNo();
3970 std::string AllocFuncStr = getFuncName(AllocFunc, AllocCloneNo);
3971 if (isFuncDead(AllocFunc)) {
3972 AllocFuncStr +=
" (dead)";
3973 }
else if (!PreCloningAllocHasMatchedCaller.contains(OrigAlloc) &&
3974 Info.Chain.size() > 1) {
3978 AllocFuncStr += AllocFunc && !FunctionsWithCallers.contains(AllocFunc)
3979 ?
" (no references in IR/summary)"
3980 :
" (no matched callers)";
3986 unsigned TotalFrames =
Info.Chain.size() > 0 ?
Info.Chain.size() - 1 : 0;
3987 unsigned Matched =
Info.MaxMatchedFrame;
3988 std::string StatusStr;
3989 if (TotalFrames == 0) {
3990 StatusStr =
"inlined into leaf";
3991 }
else if (Matched < TotalFrames) {
3996 if (
Info.StoppedAtRecursive)
3997 StatusStr =
"unmatched recursive callsite";
3998 else if (
Info.StoppedAtMismatchedCallee)
3999 StatusStr =
"unmatched callsite (mismatched callee in " +
4000 getFuncName(
Info.UnmatchedCallingFunc, 0) +
")";
4002 StatusStr =
"unmatched callsite";
4003 StatusStr +=
" at frame " + std::to_string(Matched + 1) +
"/" +
4004 std::to_string(TotalFrames) +
" (stack id " +
4005 std::to_string(
Info.UnmatchedStackId) +
")";
4007 const ContextNode *OutermostMatchedNode =
Info.Chain[Matched];
4008 const FuncTy *OutermostMatchedFunc = getCallingFunc(OutermostMatchedNode);
4009 unsigned NumOutermostMatchedFuncClones =
4010 std::max<unsigned>(1, FuncToNumClones.lookup(OutermostMatchedFunc));
4011 bool HasCallersAbove =
4012 NumOutermostMatchedFuncClones > 1 ||
4013 Info.OutermostMatchedNodeHasOtherCallers ||
4014 (OutermostMatchedFunc &&
4015 FunctionsWithCallers.contains(OutermostMatchedFunc));
4016 if (HasCallersAbove) {
4017 StatusStr =
"trimmed at frame " + std::to_string(Matched) +
" in " +
4018 getFuncName(OutermostMatchedFunc, 0);
4020 StatusStr =
"matched " + std::to_string(Matched) +
" frames to " +
4021 getFuncName(OutermostMatchedFunc, 0);
4030 std::string ReachesStr;
4032 const ContextNode *OutermostMatchedNode =
Info.Chain[Matched];
4033 const FuncTy *OutermostMatchedFunc = getCallingFunc(OutermostMatchedNode);
4034 unsigned NumOutermostMatchedFuncClones =
4035 std::max<unsigned>(1, FuncToNumClones.lookup(OutermostMatchedFunc));
4036 ReachesStr =
"; reaches ";
4041 SmallSet<unsigned, 4> ReportedAllocClones;
4042 bool FirstPath =
true;
4043 for (
unsigned OutermostMatchedFuncClone = 0;
4044 OutermostMatchedFuncClone < NumOutermostMatchedFuncClones;
4045 ++OutermostMatchedFuncClone) {
4049 std::vector<const FuncTy *> PathFuncs(Matched + 1);
4050 std::vector<unsigned> PathClones(Matched + 1);
4051 PathFuncs[0] = OutermostMatchedFunc;
4052 PathClones[0] = OutermostMatchedFuncClone;
4053 unsigned CurClone = OutermostMatchedFuncClone;
4054 for (
unsigned Step = 0; Step < Matched; ++Step) {
4055 unsigned FrameIdx = Matched - Step;
4056 const ContextNode *CallNode =
Info.Chain[FrameIdx];
4057 unsigned NextClone =
4058 OrigNodeAndCloneToCalleeClone.lookup({CallNode, CurClone});
4059 const FuncTy *CalleeFunc = getCallingFunc(
Info.Chain[FrameIdx - 1]);
4060 PathFuncs[Step + 1] = CalleeFunc;
4061 PathClones[Step + 1] = NextClone;
4062 CurClone = NextClone;
4065 if (!ReportedAllocClones.
insert(CurClone).second)
4071 const ContextNode *ReachedAlloc =
4072 OrigAllocAndCloneToNode.lookup({OrigAlloc, CurClone});
4076 std::string ReachedTypeStr;
4079 (uint8_t)getAllocationCallType(ReachedAlloc->Call));
4080 else if (CurClone == 0)
4084 ReachedTypeStr =
"None";
4090 std::string PathStr;
4091 bool SkippedPrev =
false;
4092 bool PrintFullPath =
4093 Matched + 1 <= Opts.memprof_report_hinted_sizes_detail_max_path_len;
4094 for (
unsigned S = 0; S <= Matched; ++S) {
4095 bool IsCloned = PathClones[S] > 0;
4096 bool PrevCloned = S > 0 ? (PathClones[S - 1] > 0) : IsCloned;
4097 bool NextCloned = S + 1 <= Matched ? (PathClones[S + 1] > 0) : IsCloned;
4098 bool Include = PrintFullPath || (S <= 1) || (S + 1 >= Matched) ||
4099 (IsCloned != PrevCloned) || (IsCloned != NextCloned);
4102 PathStr +=
" -> ...";
4107 SkippedPrev =
false;
4108 if (!PathStr.empty())
4110 PathStr += getFuncName(PathFuncs[S], PathClones[S]);
4112 ReachesStr += ReachedTypeStr +
" via " + PathStr;
4116 return " [alloc in " + AllocFuncStr +
"; " + StatusStr + ReachesStr +
"]";
4119template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4120void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::printTotalSizes(
4122 function_ref<
void(StringRef, StringRef,
const Twine &)> EmitRemark)
const {
4123 using GraphType =
const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
4125 if (
Node->isRemoved())
4127 if (!
Node->IsAllocation)
4129 DenseSet<uint32_t> ContextIds =
Node->getContextIds();
4130 auto AllocTypeFromCall = getAllocationCallType(
Node->Call);
4131 std::vector<uint32_t> SortedIds(ContextIds.
begin(), ContextIds.
end());
4132 std::sort(SortedIds.begin(), SortedIds.end());
4133 for (
auto Id : SortedIds) {
4134 auto TypeI = ContextIdToAllocationType.find(Id);
4135 assert(TypeI != ContextIdToAllocationType.end());
4137 bool ComputedSuffix =
false;
4138 auto GetSuffix = [&]() ->
const std::string & {
4139 if (!ComputedSuffix) {
4140 Suffix = Opts.memprof_report_hinted_sizes_detail
4141 ? formatContextReportSuffix(Node, Id)
4143 ComputedSuffix =
true;
4147 auto CSI = ContextIdToContextSizeInfos.find(Id);
4148 if (CSI != ContextIdToContextSizeInfos.end()) {
4149 for (
auto &Info : CSI->second) {
4152 " full allocation context " + std::to_string(
Info.FullStackId) +
4153 " with total size " + std::to_string(
Info.TotalSize) +
" is " +
4155 if (allocTypeToUse(
Node->AllocTypes) !=
4156 allocTypeToUse((uint8_t)AllocTypeFromCall))
4158 " due to cold byte percent";
4160 Msg +=
" (internal context id " + std::to_string(Id) +
")";
4162 OS <<
Msg << GetSuffix() <<
"\n";
4172 if (allocTypeToUse(
Node->AllocTypes) !=
4173 allocTypeToUse((uint8_t)AllocTypeFromCall))
4175 " due to cold byte percent";
4177 Msg +=
" (internal context id " + std::to_string(Id) +
")";
4179 OS <<
Msg << GetSuffix() <<
"\n";
4187template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4188void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::check()
const {
4189 using GraphType =
const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
4192 for (
auto &
Edge :
Node->CallerEdges)
4197template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4199 using GraphType =
const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
4200 using NodeRef =
const ContextNode<DerivedCCG, FuncTy, CallTy> *;
4202 using NodePtrTy = std::unique_ptr<ContextNode<DerivedCCG, FuncTy, CallTy>>;
4218 return G->NodeOwner.begin()->get();
4221 using EdgePtrTy = std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>>;
4222 static const ContextNode<DerivedCCG, FuncTy, CallTy> *
4241template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4246 using GraphType =
const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
4252 std::string LabelString =
4253 (
Twine(
"OrigId: ") + (
Node->IsAllocation ?
"Alloc" :
"") +
4256 LabelString +=
"\n";
4257 if (
Node->hasCall()) {
4258 auto Func =
G->NodeToCallingFunc.find(
Node);
4259 assert(Func !=
G->NodeToCallingFunc.end());
4261 G->getLabel(Func->second,
Node->Call.call(),
Node->Call.cloneNo());
4262 for (
auto &MatchingCall :
Node->MatchingCalls) {
4263 LabelString +=
"\n";
4264 LabelString +=
G->getLabel(Func->second, MatchingCall.call(),
4265 MatchingCall.cloneNo());
4268 LabelString +=
"null call";
4269 if (
Node->Recursive)
4270 LabelString +=
" (recursive)";
4272 LabelString +=
" (external)";
4278 auto ContextIds =
Node->getContextIds();
4282 const IPOOptions &Opts =
G->Opts;
4283 bool DoHighlight = doHighlight(Opts);
4284 bool Highlight =
false;
4286 assert(Opts.memprof_dot_context_id || Opts.memprof_dot_alloc_id);
4287 if (Opts.memprof_dot_context_id)
4288 Highlight = ContextIds.
contains(*Opts.memprof_dot_context_id);
4292 std::string AttributeString = (
Twine(
"tooltip=\"") + getNodeId(
Node) +
" " +
4293 getContextIds(ContextIds) +
"\"")
4297 AttributeString +=
",fontsize=\"30\"";
4299 (
Twine(
",fillcolor=\"") +
4300 getColor(
Node->AllocTypes, Highlight, DoHighlight) +
"\"")
4302 if (
Node->CloneOf) {
4303 AttributeString +=
",color=\"blue\"";
4304 AttributeString +=
",style=\"filled,bold,dashed\"";
4306 AttributeString +=
",style=\"filled\"";
4307 return AttributeString;
4312 auto &Edge = *(ChildIter.getCurrent());
4317 const IPOOptions &Opts =
G->Opts;
4318 bool DoHighlight = doHighlight(Opts);
4319 bool Highlight =
false;
4321 assert(Opts.memprof_dot_context_id || Opts.memprof_dot_alloc_id);
4322 if (Opts.memprof_dot_context_id)
4323 Highlight = Edge->ContextIds.contains(*Opts.memprof_dot_context_id);
4327 auto Color = getColor(Edge->AllocTypes, Highlight, DoHighlight);
4328 std::string AttributeString =
4329 (
Twine(
"tooltip=\"") + getContextIds(Edge->ContextIds) +
"\"" +
4331 Twine(
",fillcolor=\"") + Color +
"\"" +
Twine(
",color=\"") + Color +
4334 if (Edge->IsBackedge)
4335 AttributeString +=
",style=\"dotted\"";
4338 AttributeString +=
",penwidth=\"2.0\",weight=\"2\"";
4339 return AttributeString;
4345 if (
Node->isRemoved())
4347 const IPOOptions &Opts =
G->Opts;
4353 return !
Node->getContextIds().contains(*Opts.memprof_dot_context_id);
4362 static bool doHighlight(
const IPOOptions &Opts) {
4363 return (Opts.memprof_dot_alloc_id &&
4365 (Opts.memprof_dot_context_id &&
4369 static std::string getContextIds(
const DenseSet<uint32_t> &ContextIds) {
4370 std::string IdString =
"ContextIds:";
4371 if (ContextIds.
size() < 100) {
4372 std::vector<uint32_t> SortedIds(ContextIds.
begin(), ContextIds.
end());
4373 std::sort(SortedIds.begin(), SortedIds.end());
4374 for (
auto Id : SortedIds)
4375 IdString += (
" " + Twine(Id)).str();
4377 IdString += (
" (" + Twine(ContextIds.
size()) +
" ids)").str();
4382 static std::string getColor(uint8_t AllocTypes,
bool Highlight,
4389 if (AllocTypes == (uint8_t)AllocationType::NotCold)
4391 return !DoHighlight || Highlight ?
"brown1" :
"lightpink";
4392 if (AllocTypes == (uint8_t)AllocationType::Cold)
4393 return !DoHighlight || Highlight ?
"cyan" :
"lightskyblue";
4395 ((uint8_t)AllocationType::NotCold | (uint8_t)AllocationType::Cold))
4396 return Highlight ?
"magenta" :
"mediumorchid1";
4400 static std::string getNodeId(NodeRef Node) {
4401 std::stringstream SStream;
4402 SStream << std::hex <<
"N0x" << (
unsigned long long)Node;
4403 std::string
Result = SStream.str();
4408template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4409void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::exportToDot(
4410 std::string Label)
const {
4412 this,
"",
false, Label,
4413 (Opts.memprof_dot_file_path_prefix +
"ccg." + Label +
".dot").str());
4416template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4417typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
4418CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::moveEdgeToNewCalleeClone(
4419 const std::shared_ptr<ContextEdge> &
Edge,
4420 DenseSet<uint32_t> ContextIdsToMove) {
4422 assert(NodeToCallingFunc.count(Node));
4423 ContextNode *Clone =
4424 createNewNode(
Node->IsAllocation, NodeToCallingFunc[Node],
Node->Call);
4425 Node->addClone(Clone);
4426 Clone->MatchingCalls =
Node->MatchingCalls;
4427 moveEdgeToExistingCalleeClone(
Edge, Clone,
true,
4432template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4433void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
4434 moveEdgeToExistingCalleeClone(
const std::shared_ptr<ContextEdge> &
Edge,
4435 ContextNode *NewCallee,
bool NewClone,
4436 DenseSet<uint32_t> ContextIdsToMove) {
4439 assert(NewCallee->getOrigNode() ==
Edge->Callee->getOrigNode());
4441 bool EdgeIsRecursive =
Edge->Callee ==
Edge->Caller;
4443 ContextNode *OldCallee =
Edge->Callee;
4447 auto ExistingEdgeToNewCallee = NewCallee->findEdgeFromCaller(
Edge->Caller);
4451 if (ContextIdsToMove.
empty())
4452 ContextIdsToMove =
Edge->getContextIds();
4456 if (
Edge->getContextIds().size() == ContextIdsToMove.
size()) {
4459 NewCallee->AllocTypes |=
Edge->AllocTypes;
4461 if (ExistingEdgeToNewCallee) {
4464 ExistingEdgeToNewCallee->getContextIds().insert_range(ContextIdsToMove);
4465 ExistingEdgeToNewCallee->AllocTypes |=
Edge->AllocTypes;
4466 assert(
Edge->ContextIds == ContextIdsToMove);
4467 removeEdgeFromGraph(
Edge.get());
4470 Edge->Callee = NewCallee;
4471 NewCallee->CallerEdges.push_back(
Edge);
4473 OldCallee->eraseCallerEdge(
Edge.get());
4480 auto CallerEdgeAllocType = computeAllocType(ContextIdsToMove);
4481 if (ExistingEdgeToNewCallee) {
4484 ExistingEdgeToNewCallee->getContextIds().insert_range(ContextIdsToMove);
4485 ExistingEdgeToNewCallee->AllocTypes |= CallerEdgeAllocType;
4488 auto NewEdge = std::make_shared<ContextEdge>(
4489 NewCallee,
Edge->Caller, CallerEdgeAllocType, ContextIdsToMove);
4490 Edge->Caller->CalleeEdges.push_back(NewEdge);
4491 NewCallee->CallerEdges.push_back(NewEdge);
4495 NewCallee->AllocTypes |= CallerEdgeAllocType;
4497 Edge->AllocTypes = computeAllocType(
Edge->ContextIds);
4502 for (
auto &OldCalleeEdge : OldCallee->CalleeEdges) {
4503 ContextNode *CalleeToUse = OldCalleeEdge->Callee;
4507 if (CalleeToUse == OldCallee) {
4511 if (EdgeIsRecursive) {
4515 CalleeToUse = NewCallee;
4519 DenseSet<uint32_t> EdgeContextIdsToMove =
4521 set_subtract(OldCalleeEdge->getContextIds(), EdgeContextIdsToMove);
4522 OldCalleeEdge->AllocTypes =
4523 computeAllocType(OldCalleeEdge->getContextIds());
4530 if (
auto *NewCalleeEdge = NewCallee->findEdgeFromCallee(CalleeToUse)) {
4531 NewCalleeEdge->getContextIds().insert_range(EdgeContextIdsToMove);
4532 NewCalleeEdge->AllocTypes |= computeAllocType(EdgeContextIdsToMove);
4536 auto NewEdge = std::make_shared<ContextEdge>(
4537 CalleeToUse, NewCallee, computeAllocType(EdgeContextIdsToMove),
4538 EdgeContextIdsToMove);
4539 NewCallee->CalleeEdges.push_back(NewEdge);
4540 NewEdge->Callee->CallerEdges.push_back(NewEdge);
4544 OldCallee->AllocTypes = OldCallee->computeAllocType();
4546 assert((OldCallee->AllocTypes == (uint8_t)AllocationType::None) ==
4547 OldCallee->emptyContextIds());
4548 if (Opts.memprof_verify_ccg) {
4551 for (
const auto &OldCalleeEdge : OldCallee->CalleeEdges)
4554 for (
const auto &NewCalleeEdge : NewCallee->CalleeEdges)
4560template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4561void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
4562 moveCalleeEdgeToNewCaller(
const std::shared_ptr<ContextEdge> &
Edge,
4563 ContextNode *NewCaller) {
4564 auto *OldCallee =
Edge->Callee;
4565 auto *NewCallee = OldCallee;
4568 bool Recursive =
Edge->Caller ==
Edge->Callee;
4570 NewCallee = NewCaller;
4572 ContextNode *OldCaller =
Edge->Caller;
4573 OldCaller->eraseCalleeEdge(
Edge.get());
4577 auto ExistingEdgeToNewCaller = NewCaller->findEdgeFromCallee(NewCallee);
4579 if (ExistingEdgeToNewCaller) {
4582 ExistingEdgeToNewCaller->getContextIds().insert_range(
4583 Edge->getContextIds());
4584 ExistingEdgeToNewCaller->AllocTypes |=
Edge->AllocTypes;
4585 Edge->ContextIds.clear();
4586 Edge->AllocTypes = (uint8_t)AllocationType::None;
4587 OldCallee->eraseCallerEdge(
Edge.get());
4590 Edge->Caller = NewCaller;
4591 NewCaller->CalleeEdges.push_back(
Edge);
4593 assert(NewCallee == NewCaller);
4596 Edge->Callee = NewCallee;
4597 NewCallee->CallerEdges.push_back(
Edge);
4598 OldCallee->eraseCallerEdge(
Edge.get());
4604 NewCaller->AllocTypes |=
Edge->AllocTypes;
4611 bool IsNewNode = NewCaller->CallerEdges.empty();
4620 for (
auto &OldCallerEdge : OldCaller->CallerEdges) {
4621 auto OldCallerCaller = OldCallerEdge->Caller;
4625 OldCallerEdge->getContextIds(),
Edge->getContextIds());
4626 if (OldCaller == OldCallerCaller) {
4627 OldCallerCaller = NewCaller;
4633 set_subtract(OldCallerEdge->getContextIds(), EdgeContextIdsToMove);
4634 OldCallerEdge->AllocTypes =
4635 computeAllocType(OldCallerEdge->getContextIds());
4640 auto *ExistingCallerEdge = NewCaller->findEdgeFromCaller(OldCallerCaller);
4643 assert(IsNewNode || ExistingCallerEdge ||
4644 Opts.memprof_allow_recursive_callsites);
4645 if (ExistingCallerEdge) {
4646 ExistingCallerEdge->getContextIds().insert_range(EdgeContextIdsToMove);
4647 ExistingCallerEdge->AllocTypes |=
4648 computeAllocType(EdgeContextIdsToMove);
4651 auto NewEdge = std::make_shared<ContextEdge>(
4652 NewCaller, OldCallerCaller, computeAllocType(EdgeContextIdsToMove),
4653 EdgeContextIdsToMove);
4654 NewCaller->CallerEdges.push_back(NewEdge);
4655 NewEdge->Caller->CalleeEdges.push_back(NewEdge);
4660 OldCaller->AllocTypes = OldCaller->computeAllocType();
4662 assert((OldCaller->AllocTypes == (uint8_t)AllocationType::None) ==
4663 OldCaller->emptyContextIds());
4664 if (Opts.memprof_verify_ccg) {
4667 for (
const auto &OldCallerEdge : OldCaller->CallerEdges)
4670 for (
const auto &NewCallerEdge : NewCaller->CallerEdges)
4676template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4677void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
4678 recursivelyRemoveNoneTypeCalleeEdges(
4679 ContextNode *Node, DenseSet<const ContextNode *> &Visited) {
4684 removeNoneTypeCalleeEdges(Node);
4686 for (
auto *Clone :
Node->Clones)
4687 recursivelyRemoveNoneTypeCalleeEdges(Clone, Visited);
4691 auto CallerEdges =
Node->CallerEdges;
4692 for (
auto &
Edge : CallerEdges) {
4694 if (
Edge->isRemoved()) {
4698 recursivelyRemoveNoneTypeCalleeEdges(
Edge->Caller, Visited);
4703template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4704void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::markBackedges() {
4707 if (!Opts.memprof_clone_recursive_contexts)
4709 DenseSet<const ContextNode *> Visited;
4710 DenseSet<const ContextNode *> CurrentStack;
4711 for (
auto &Entry : NonAllocationCallToContextNodeMap) {
4713 if (
Node->isRemoved())
4716 if (!
Node->CallerEdges.empty())
4718 markBackedges(Node, Visited, CurrentStack);
4724template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4725void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::markBackedges(
4726 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
4727 DenseSet<const ContextNode *> &CurrentStack) {
4728 auto I = Visited.
insert(Node);
4732 for (
auto &CalleeEdge :
Node->CalleeEdges) {
4733 auto *
Callee = CalleeEdge->Callee;
4734 if (Visited.
count(Callee)) {
4737 if (CurrentStack.
count(Callee))
4738 CalleeEdge->IsBackedge =
true;
4741 CurrentStack.
insert(Callee);
4742 markBackedges(Callee, Visited, CurrentStack);
4743 CurrentStack.
erase(Callee);
4747template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4748void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::identifyClones() {
4749 DenseSet<const ContextNode *> Visited;
4750 for (
auto &Entry : AllocationCallToContextNodeMap) {
4752 identifyClones(
Entry.second, Visited,
Entry.second->getContextIds());
4755 for (
auto &Entry : AllocationCallToContextNodeMap)
4756 recursivelyRemoveNoneTypeCalleeEdges(
Entry.second, Visited);
4757 if (Opts.memprof_verify_ccg)
4769template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
4770void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::identifyClones(
4771 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
4772 const DenseSet<uint32_t> &AllocContextIds) {
4773 if (Opts.memprof_verify_nodes)
4782 if (!
Node->hasCall())
4801 auto CallerEdges =
Node->CallerEdges;
4802 for (
auto &
Edge : CallerEdges) {
4804 if (
Edge->isRemoved()) {
4810 if (
Edge->IsBackedge) {
4813 assert(Opts.memprof_clone_recursive_contexts);
4817 if (!Visited.
count(
Edge->Caller) && !
Edge->Caller->CloneOf) {
4818 identifyClones(
Edge->Caller, Visited, AllocContextIds);
4841 const unsigned AllocTypeCloningPriority[] = { 3, 4,
4845 [&](
const std::shared_ptr<ContextEdge> &
A,
4846 const std::shared_ptr<ContextEdge> &
B) {
4849 if (A->ContextIds.empty())
4855 if (B->ContextIds.empty())
4858 if (A->AllocTypes == B->AllocTypes)
4861 return A->Caller->NodeId < B->Caller->NodeId;
4862 return AllocTypeCloningPriority[A->AllocTypes] <
4863 AllocTypeCloningPriority[B->AllocTypes];
4866 assert(
Node->AllocTypes != (uint8_t)AllocationType::None);
4868 DenseSet<uint32_t> RecursiveContextIds;
4869 assert(Opts.memprof_allow_recursive_contexts ||
4870 !Opts.memprof_clone_recursive_contexts);
4873 if (Opts.memprof_allow_recursive_callsites &&
4874 !Opts.memprof_allow_recursive_contexts) {
4875 DenseSet<uint32_t> AllCallerContextIds;
4876 for (
auto &CE :
Node->CallerEdges) {
4879 AllCallerContextIds.
reserve(
CE->getContextIds().size());
4880 for (
auto Id :
CE->getContextIds())
4881 if (!AllCallerContextIds.
insert(Id).second)
4882 RecursiveContextIds.
insert(Id);
4892 auto CallerEdges =
Node->CallerEdges;
4893 for (
auto &CallerEdge : CallerEdges) {
4895 if (CallerEdge->isRemoved()) {
4899 assert(CallerEdge->Callee == Node);
4908 if (!CallerEdge->Caller->hasCall())
4913 auto CallerEdgeContextsForAlloc =
4915 if (!RecursiveContextIds.
empty())
4916 CallerEdgeContextsForAlloc =
4918 if (CallerEdgeContextsForAlloc.empty())
4921 auto CallerAllocTypeForAlloc = computeAllocType(CallerEdgeContextsForAlloc);
4925 std::vector<uint8_t> CalleeEdgeAllocTypesForCallerEdge;
4926 CalleeEdgeAllocTypesForCallerEdge.reserve(
Node->CalleeEdges.size());
4927 for (
auto &CalleeEdge :
Node->CalleeEdges)
4928 CalleeEdgeAllocTypesForCallerEdge.push_back(intersectAllocTypes(
4929 CalleeEdge->getContextIds(), CallerEdgeContextsForAlloc));
4945 assert(CallerEdge->AllocTypes != (uint8_t)AllocationType::None);
4946 assert(
Node->AllocTypes != (uint8_t)AllocationType::None);
4947 if (!CallerEdge->IsBackedge &&
4948 allocTypeToUse(CallerAllocTypeForAlloc) ==
4949 allocTypeToUse(
Node->AllocTypes) &&
4950 allocTypesMatch<DerivedCCG, FuncTy, CallTy>(
4951 CalleeEdgeAllocTypesForCallerEdge,
Node->CalleeEdges)) {
4955 if (CallerEdge->IsBackedge) {
4958 assert(Opts.memprof_clone_recursive_contexts);
4959 DeferredBackedges++;
4972 if (CallerEdge->IsBackedge && !CallerEdge->Caller->CloneOf &&
4973 !Visited.
count(CallerEdge->Caller)) {
4974 const auto OrigIdCount = CallerEdge->getContextIds().size();
4977 identifyClones(CallerEdge->Caller, Visited, CallerEdgeContextsForAlloc);
4978 removeNoneTypeCalleeEdges(CallerEdge->Caller);
4982 bool UpdatedEdge =
false;
4983 if (OrigIdCount > CallerEdge->getContextIds().size()) {
4984 for (
auto E :
Node->CallerEdges) {
4986 if (
E->Caller->CloneOf != CallerEdge->Caller)
4990 auto CallerEdgeContextsForAllocNew =
4992 if (CallerEdgeContextsForAllocNew.empty())
5002 CallerEdgeContextsForAlloc.swap(CallerEdgeContextsForAllocNew);
5012 if (CallerEdge->isRemoved())
5022 CallerEdgeContextsForAlloc, CallerEdge->getContextIds());
5023 if (CallerEdgeContextsForAlloc.empty())
5028 CallerAllocTypeForAlloc = computeAllocType(CallerEdgeContextsForAlloc);
5029 CalleeEdgeAllocTypesForCallerEdge.clear();
5030 for (
auto &CalleeEdge :
Node->CalleeEdges) {
5031 CalleeEdgeAllocTypesForCallerEdge.push_back(intersectAllocTypes(
5032 CalleeEdge->getContextIds(), CallerEdgeContextsForAlloc));
5038 ContextNode *Clone =
nullptr;
5039 for (
auto *CurClone :
Node->Clones) {
5040 if (allocTypeToUse(CurClone->AllocTypes) !=
5041 allocTypeToUse(CallerAllocTypeForAlloc))
5048 assert(!BothSingleAlloc ||
5049 CurClone->AllocTypes == CallerAllocTypeForAlloc);
5055 if (BothSingleAlloc || allocTypesMatchClone<DerivedCCG, FuncTy, CallTy>(
5056 CalleeEdgeAllocTypesForCallerEdge, CurClone)) {
5064 moveEdgeToExistingCalleeClone(CallerEdge, Clone,
false,
5065 CallerEdgeContextsForAlloc);
5067 Clone = moveEdgeToNewCalleeClone(CallerEdge, CallerEdgeContextsForAlloc);
5070 assert(Clone->AllocTypes != (uint8_t)AllocationType::None);
5077 assert(
Node->AllocTypes != (uint8_t)AllocationType::None);
5079 if (Opts.memprof_verify_nodes)
5083void ModuleCallsiteContextGraph::updateAllocationCall(
5099 .emit(OptimizationRemark(
DEBUG_TYPE,
"MemprofAttribute",
Call.call())
5100 <<
ore::NV(
"AllocationCall",
Call.call()) <<
" in clone "
5102 <<
" marked with memprof allocation attribute "
5103 <<
ore::NV(
"Attribute", AllocTypeString));
5106void IndexCallsiteContextGraph::updateAllocationCall(CallInfo &
Call,
5110 assert(AI->Versions.size() >
Call.cloneNo());
5111 AI->Versions[
Call.cloneNo()] = (uint8_t)AllocType;
5115ModuleCallsiteContextGraph::getAllocationCallType(
const CallInfo &
Call)
const {
5117 if (!CB->getAttributes().hasFnAttr(
"memprof"))
5118 return AllocationType::None;
5119 StringRef AllocTypeString =
5120 CB->getAttributes().getFnAttr(
"memprof").getValueAsString();
5121 if (AllocTypeString ==
"cold")
5122 return AllocationType::Cold;
5123 if (AllocTypeString ==
"ambiguous")
5125 (uint8_t)AllocationType::Cold);
5126 return AllocationType::NotCold;
5130IndexCallsiteContextGraph::getAllocationCallType(
const CallInfo &
Call)
const {
5132 assert(AI->Versions.size() >
Call.cloneNo());
5136void ModuleCallsiteContextGraph::updateCall(CallInfo &CallerCall,
5137 FuncInfo CalleeFunc) {
5138 auto *CurF = getCalleeFunc(CallerCall.call());
5139 auto NewCalleeCloneNo = CalleeFunc.cloneNo();
5146 if (CurCalleeCloneNo != NewCalleeCloneNo) {
5148 << CurCalleeCloneNo <<
" now " << NewCalleeCloneNo
5150 MismatchedCloneAssignments++;
5153 if (NewCalleeCloneNo > 0)
5154 cast<CallBase>(CallerCall.call())->setCalledFunction(CalleeFunc.func());
5155 OREGetter(CallerCall.call()->getFunction())
5156 .emit(OptimizationRemark(
DEBUG_TYPE,
"MemprofCall", CallerCall.call())
5157 <<
ore::NV(
"Call", CallerCall.call()) <<
" in clone "
5158 <<
ore::NV(
"Caller", CallerCall.call()->getFunction())
5159 <<
" assigned to call function clone "
5160 <<
ore::NV(
"Callee", CalleeFunc.func()));
5163void IndexCallsiteContextGraph::updateCall(CallInfo &CallerCall,
5164 FuncInfo CalleeFunc) {
5167 "Caller cannot be an allocation which should not have profiled calls");
5168 assert(CI->Clones.size() > CallerCall.cloneNo());
5169 auto NewCalleeCloneNo = CalleeFunc.cloneNo();
5170 auto &CurCalleeCloneNo = CI->Clones[CallerCall.cloneNo()];
5175 if (CurCalleeCloneNo != 0 && CurCalleeCloneNo != NewCalleeCloneNo) {
5177 << CurCalleeCloneNo <<
" now " << NewCalleeCloneNo
5179 MismatchedCloneAssignments++;
5181 CurCalleeCloneNo = NewCalleeCloneNo;
5193 SP->replaceLinkageName(MDName);
5197 TempDISubprogram NewDecl = Decl->
clone();
5198 NewDecl->replaceLinkageName(MDName);
5202CallsiteContextGraph<ModuleCallsiteContextGraph,
Function,
5204ModuleCallsiteContextGraph::cloneFunctionForCallsite(
5205 FuncInfo &Func, CallInfo &
Call, DenseMap<CallInfo, CallInfo> &CallMap,
5206 std::vector<CallInfo> &CallsWithMetadataInFunc,
unsigned CloneNo) {
5209 "Attempting to clone function with escaping block address");
5215 NewFunc->setMetadata(LLVMContext::MD_kcfi_type,
nullptr);
5217 assert(!
Func.func()->getParent()->getFunction(Name));
5218 NewFunc->setName(Name);
5220 for (
auto &Inst : CallsWithMetadataInFunc) {
5222 assert(Inst.cloneNo() == 0);
5225 OREGetter(
Func.func())
5226 .emit(OptimizationRemark(
DEBUG_TYPE,
"MemprofClone",
Func.func())
5227 <<
"created clone " <<
ore::NV(
"NewFunction", NewFunc));
5228 return {NewFunc, CloneNo};
5231CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
5232 IndexCall>::FuncInfo
5233IndexCallsiteContextGraph::cloneFunctionForCallsite(
5234 FuncInfo &Func, CallInfo &
Call, DenseMap<CallInfo, CallInfo> &CallMap,
5235 std::vector<CallInfo> &CallsWithMetadataInFunc,
unsigned CloneNo) {
5249 for (
auto &Inst : CallsWithMetadataInFunc) {
5251 assert(Inst.cloneNo() == 0);
5253 assert(AI->Versions.size() == CloneNo);
5256 AI->Versions.push_back(0);
5259 assert(CI && CI->Clones.size() == CloneNo);
5262 CI->Clones.push_back(0);
5264 CallMap[Inst] = {Inst.call(), CloneNo};
5266 return {
Func.func(), CloneNo};
5283template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5284void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::mergeClones() {
5285 if (!Opts.memprof_merge_clones)
5290 DenseMap<uint32_t, ContextNode *> ContextIdToAllocationNode;
5291 for (
auto &Entry : AllocationCallToContextNodeMap) {
5293 for (
auto Id :
Node->getContextIds())
5294 ContextIdToAllocationNode[
Id] =
Node->getOrigNode();
5295 for (
auto *Clone :
Node->Clones) {
5296 for (
auto Id : Clone->getContextIds())
5297 ContextIdToAllocationNode[
Id] = Clone->getOrigNode();
5304 DenseSet<const ContextNode *> Visited;
5305 for (
auto &Entry : AllocationCallToContextNodeMap) {
5308 mergeClones(Node, Visited, ContextIdToAllocationNode);
5314 auto Clones =
Node->Clones;
5315 for (
auto *Clone : Clones)
5316 mergeClones(Clone, Visited, ContextIdToAllocationNode);
5319 if (Opts.memprof_dump_ccg) {
5320 dbgs() <<
"CCG after merging:\n";
5323 if (Opts.memprof_export_to_dot)
5324 exportToDot(
"aftermerge");
5326 if (Opts.memprof_verify_ccg) {
5332template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5333void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::mergeClones(
5334 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
5335 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode) {
5345 bool FoundUnvisited =
true;
5347 while (FoundUnvisited) {
5349 FoundUnvisited =
false;
5352 auto CallerEdges =
Node->CallerEdges;
5353 for (
auto CallerEdge : CallerEdges) {
5355 if (CallerEdge->Callee != Node)
5359 if (Opts.memprof_merge_iteration && !Visited.
contains(CallerEdge->Caller))
5360 FoundUnvisited =
true;
5361 mergeClones(CallerEdge->Caller, Visited, ContextIdToAllocationNode);
5365 TotalMergeInvokes++;
5366 TotalMergeIters += Iters;
5367 if (Iters > MaxMergeIters)
5368 MaxMergeIters = Iters;
5371 mergeNodeCalleeClones(Node, Visited, ContextIdToAllocationNode);
5374template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5375void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::mergeNodeCalleeClones(
5376 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
5377 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode) {
5379 if (
Node->emptyContextIds())
5384 MapVector<ContextNode *, std::vector<std::shared_ptr<ContextEdge>>>
5385 OrigNodeToCloneEdges;
5386 for (
const auto &
E :
Node->CalleeEdges) {
5391 OrigNodeToCloneEdges[
Base].push_back(
E);
5397 auto CalleeCallerEdgeLessThan = [](
const std::shared_ptr<ContextEdge> &
A,
5398 const std::shared_ptr<ContextEdge> &
B) {
5399 if (
A->Callee->CallerEdges.size() !=
B->Callee->CallerEdges.size())
5400 return A->Callee->CallerEdges.size() <
B->Callee->CallerEdges.size();
5401 if (
A->Callee->CloneOf && !
B->Callee->CloneOf)
5403 else if (!
A->Callee->CloneOf &&
B->Callee->CloneOf)
5406 return A->Callee->NodeId <
B->Callee->NodeId;
5411 for (
auto Entry : OrigNodeToCloneEdges) {
5414 auto &CalleeEdges =
Entry.second;
5415 auto NumCalleeClones = CalleeEdges.size();
5417 if (NumCalleeClones == 1)
5428 DenseSet<ContextNode *> OtherCallersToShareMerge;
5429 findOtherCallersToShareMerge(Node, CalleeEdges, ContextIdToAllocationNode,
5430 OtherCallersToShareMerge);
5435 ContextNode *MergeNode =
nullptr;
5436 DenseMap<ContextNode *, unsigned> CallerToMoveCount;
5437 for (
auto CalleeEdge : CalleeEdges) {
5438 auto *OrigCallee = CalleeEdge->Callee;
5444 if (CalleeEdge->Callee->CallerEdges.size() == 1) {
5445 MergeNode = OrigCallee;
5446 NonNewMergedNodes++;
5453 if (!OtherCallersToShareMerge.
empty()) {
5454 bool MoveAllCallerEdges =
true;
5455 for (
auto CalleeCallerE : OrigCallee->CallerEdges) {
5456 if (CalleeCallerE == CalleeEdge)
5458 if (!OtherCallersToShareMerge.
contains(CalleeCallerE->Caller)) {
5459 MoveAllCallerEdges =
false;
5465 if (MoveAllCallerEdges) {
5466 MergeNode = OrigCallee;
5467 NonNewMergedNodes++;
5474 assert(MergeNode != OrigCallee);
5475 moveEdgeToExistingCalleeClone(CalleeEdge, MergeNode,
5478 MergeNode = moveEdgeToNewCalleeClone(CalleeEdge);
5483 if (!OtherCallersToShareMerge.
empty()) {
5487 auto OrigCalleeCallerEdges = OrigCallee->CallerEdges;
5488 for (
auto &CalleeCallerE : OrigCalleeCallerEdges) {
5489 if (CalleeCallerE == CalleeEdge)
5491 if (!OtherCallersToShareMerge.
contains(CalleeCallerE->Caller))
5493 CallerToMoveCount[CalleeCallerE->Caller]++;
5494 moveEdgeToExistingCalleeClone(CalleeCallerE, MergeNode,
5498 removeNoneTypeCalleeEdges(OrigCallee);
5499 removeNoneTypeCalleeEdges(MergeNode);
5517template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5518void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
5519 findOtherCallersToShareMerge(
5521 std::vector<std::shared_ptr<ContextEdge>> &CalleeEdges,
5522 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode,
5523 DenseSet<ContextNode *> &OtherCallersToShareMerge) {
5524 auto NumCalleeClones = CalleeEdges.size();
5527 DenseMap<ContextNode *, unsigned> OtherCallersToSharedCalleeEdgeCount;
5530 unsigned PossibleOtherCallerNodes = 0;
5534 if (CalleeEdges[0]->
Callee->CallerEdges.size() < 2)
5540 DenseMap<ContextEdge *, DenseSet<ContextNode *>> CalleeEdgeToAllocNodes;
5541 for (
auto CalleeEdge : CalleeEdges) {
5542 assert(CalleeEdge->Callee->CallerEdges.size() > 1);
5545 for (
auto CalleeCallerEdges : CalleeEdge->Callee->CallerEdges) {
5546 if (CalleeCallerEdges->Caller == Node) {
5547 assert(CalleeCallerEdges == CalleeEdge);
5550 OtherCallersToSharedCalleeEdgeCount[CalleeCallerEdges->Caller]++;
5553 if (OtherCallersToSharedCalleeEdgeCount[CalleeCallerEdges->Caller] ==
5555 PossibleOtherCallerNodes++;
5559 for (
auto Id : CalleeEdge->getContextIds()) {
5560 auto *
Alloc = ContextIdToAllocationNode.
lookup(Id);
5564 MissingAllocForContextId++;
5567 CalleeEdgeToAllocNodes[CalleeEdge.get()].
insert(
Alloc);
5574 for (
auto CalleeEdge : CalleeEdges) {
5575 assert(CalleeEdge->Callee->CallerEdges.size() > 1);
5577 if (!PossibleOtherCallerNodes)
5579 auto &CurCalleeAllocNodes = CalleeEdgeToAllocNodes[CalleeEdge.get()];
5581 for (
auto &CalleeCallerE : CalleeEdge->Callee->CallerEdges) {
5583 if (CalleeCallerE == CalleeEdge)
5587 if (OtherCallersToSharedCalleeEdgeCount[CalleeCallerE->Caller] !=
5592 for (
auto Id : CalleeCallerE->getContextIds()) {
5593 auto *
Alloc = ContextIdToAllocationNode.
lookup(Id);
5598 if (!CurCalleeAllocNodes.contains(
Alloc)) {
5599 OtherCallersToSharedCalleeEdgeCount[CalleeCallerE->Caller] = 0;
5600 PossibleOtherCallerNodes--;
5607 if (!PossibleOtherCallerNodes)
5612 for (
auto &[OtherCaller,
Count] : OtherCallersToSharedCalleeEdgeCount) {
5613 if (
Count != NumCalleeClones)
5615 OtherCallersToShareMerge.
insert(OtherCaller);
5619template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5620const typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
5621CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::resolveImplicitSource(
5622 const ContextNode *Node,
const ImplicitSource &Src) {
5623 if (!Src.Source->emptyContextIds())
5629 if (
Node->hasContextId(Src.ContextId))
5631 for (
const ContextNode *
C :
Node->Clones)
5632 if (
C->hasContextId(Src.ContextId))
5637 assert(
false &&
"trimmed context id on no clone of its callsite node");
5679template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5680void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::assignImplicitCallers(
5681 ContextNode *Node,
const DenseSet<uint32_t> &TrimmedContextIds,
5682 DenseMap<ContextNode *, FuncInfo> &CallsiteToCalleeFuncCloneMap,
5683 const std::map<FuncInfo, ContextNode *> &FuncCloneToCurNodeCloneMap,
5684 ImplicitSourceMap &ImplicitSources) {
5685 auto HasEdgeToNodeFamily = [&](
const ContextNode *
N) {
5687 [&](
const std::shared_ptr<ContextEdge> &
E) {
5688 return E->Callee->getOrigNode() == Node;
5722 auto ImpliesContextIds =
5723 [&](ContextNode *
K, ContextNode *
Y,
const DenseSet<uint32_t> &Ids,
5724 DenseMap<std::pair<ContextNode *, ContextNode *>, DenseSet<uint32_t>>
5726 auto &&ImpliesContextIds) ->
bool {
5727 assert(
K->getOrigNode() ==
Y->getOrigNode());
5728 DenseSet<uint32_t> &VisitedIds = Visited[{
K,
Y}];
5729 DenseSet<uint32_t> NewIds;
5731 if (VisitedIds.
insert(Id).second)
5739 DenseSet<uint32_t> IdsOnCallerEdges;
5740 for (
auto &YEdge :
Y->CallerEdges) {
5741 DenseSet<uint32_t> IdsFromZ =
5743 if (IdsFromZ.
empty())
5746 IdsFromCallers.
push_back({YEdge->Caller, std::move(IdsFromZ)});
5750 if (IdsOnCallerEdges.
size() < NewIds.
size())
5754 for (
auto &[Z, IdsFromZ] : IdsFromCallers) {
5755 for (
auto &KEdge :
K->CallerEdges) {
5756 ContextNode *
C = KEdge->Caller;
5757 if (
C == Z ||
C->getOrigNode() !=
Z->getOrigNode())
5761 DenseSet<uint32_t> IdsNotOnC;
5762 for (
auto Id : IdsFromZ)
5763 if (!
C->hasContextId(Id))
5765 if (!IdsNotOnC.
empty() &&
5766 ImpliesContextIds(
C, Z, IdsNotOnC, Visited, ImpliesContextIds))
5775 auto SameVersion = [&](
const ContextNode *
A,
const ContextNode *
B) {
5778 if (
Node->IsAllocation)
5779 return allocTypeToUse(
A->AllocTypes) == allocTypeToUse(
B->AllocTypes);
5780 auto AIt = CallsiteToCalleeFuncCloneMap.
find(
A);
5781 auto BIt = CallsiteToCalleeFuncCloneMap.
find(
B);
5782 return AIt != CallsiteToCalleeFuncCloneMap.
end() &&
5783 BIt != CallsiteToCalleeFuncCloneMap.
end() &&
5784 AIt->second == BIt->second;
5788 DenseSet<const ContextNode *> ImplicitCallers;
5793 auto ProcessCaller = [&](
const std::shared_ptr<ContextEdge> &
Edge) {
5794 ContextNode *
Y =
Edge->Caller;
5795 ContextNode *Orig =
Y->getOrigNode();
5796 if (!
Y->hasCall() || Orig->Clones.empty())
5798 DenseSet<uint32_t> TrimmedIds =
5800 if (TrimmedIds.
empty())
5802 auto YIt = CallsiteToCalleeFuncCloneMap.
find(
Y);
5803 if (YIt == CallsiteToCalleeFuncCloneMap.
end())
5806 const FuncInfo YFuncClone = YIt->second;
5809 auto RequiredIt = FuncCloneToCurNodeCloneMap.find(YFuncClone);
5810 assert(RequiredIt != FuncCloneToCurNodeCloneMap.end());
5811 const ContextNode *
Required = RequiredIt->second;
5819 auto RecordImplicitSource = [&](
const FuncInfo &
F,
const ContextNode *Src) {
5822 if (
F.cloneNo() != 0)
5823 ImplicitSources.try_emplace({
Node,
F.cloneNo()},
5824 ImplicitSource{Src, *TrimmedIds.
begin()});
5830 if (K ==
Y || !
K->hasCall() ||
K->emptyContextIds() ||
5831 HasEdgeToNodeFamily(K) || ImplicitCallers.
contains(K))
5833 DenseMap<std::pair<ContextNode *, ContextNode *>, DenseSet<uint32_t>>
5835 if (!ImpliesContextIds(K,
Y, TrimmedIds, Visited, ImpliesContextIds))
5838 ImplicitCallers.
insert(K);
5839 auto KIt = CallsiteToCalleeFuncCloneMap.
find(K);
5840 if (KIt == CallsiteToCalleeFuncCloneMap.
end()) {
5843 CallsiteToCalleeFuncCloneMap[
K] = YFuncClone;
5844 RecordImplicitSource(YFuncClone, Required);
5845 NumImplicitCallersAssigned++;
5848 const FuncInfo KFuncClone = KIt->second;
5849 if (KFuncClone == YFuncClone) {
5851 RecordImplicitSource(YFuncClone, Required);
5854 unsigned KCloneNo = KFuncClone.cloneNo();
5855 auto KNodeCloneIt = FuncCloneToCurNodeCloneMap.find(KFuncClone);
5856 if (KNodeCloneIt == FuncCloneToCurNodeCloneMap.end()) {
5858 if (KCloneNo == 0) {
5862 if (
Node->IsAllocation) {
5863 if (allocTypeToUse(
Required->AllocTypes) == AllocationType::NotCold)
5865 }
else if (
auto It = CallsiteToCalleeFuncCloneMap.
find(Required);
5866 It != CallsiteToCalleeFuncCloneMap.
end() &&
5867 It->second.cloneNo() == 0)
5873 auto [It,
Inserted] = ImplicitSources.try_emplace(
5876 NumImplicitCallersSourced++;
5877 if (SameVersion(It->second.Source, Required))
5880 }
else if (SameVersion(KNodeCloneIt->second, Required)) {
5883 RecordImplicitSource(KFuncClone, KNodeCloneIt->second);
5887 NumImplicitCallersUnresolved++;
5893 for (
auto &
Edge :
Node->CallerEdges)
5894 ProcessCaller(
Edge);
5895 for (
auto *Clone :
Node->Clones)
5896 for (
auto &
Edge : Clone->CallerEdges)
5897 ProcessCaller(
Edge);
5941template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
5942bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::assignFunctions() {
5950 DenseSet<uint32_t> TrimmedContextIds;
5951 for (
auto &NodePtr : NodeOwner) {
5952 ContextNode *
N = NodePtr.get();
5953 if (
N->IsAllocation ||
N->CalleeEdges.empty() ||
5954 (
N->CallerEdges.empty() &&
N->Clones.empty() && !
N->CloneOf))
5959 DenseSet<uint32_t> CallerIds;
5960 for (
auto &
E :
N->CallerEdges)
5962 for (
auto &CalleeEdge :
N->CalleeEdges)
5963 for (
auto Id : CalleeEdge->getContextIds())
5965 TrimmedContextIds.
insert(Id);
5967 NumTrimmedContextIds += TrimmedContextIds.
size();
5971 DenseMap<ContextNode *, FuncInfo> CallsiteToCalleeFuncCloneMap;
5975 auto RecordCalleeFuncOfCallsite = [&](ContextNode *
Caller,
5976 const FuncInfo &CalleeFunc) {
5978 CallsiteToCalleeFuncCloneMap[
Caller] = CalleeFunc;
5982 struct FuncCloneInfo {
5987 DenseMap<CallInfo, CallInfo> CallMap;
6023 struct UnassignedCallCloneInfo {
6025 const ContextNode *
Source =
nullptr;
6027 DenseMap<const ContextNode *, std::map<unsigned, UnassignedCallCloneInfo>>
6028 UnassignedCallClones;
6032 for (
auto &[Func, CallsWithMetadata] : FuncToCallsWithMetadata) {
6033 FuncInfo OrigFunc(Func);
6038 std::vector<FuncCloneInfo> FuncCloneInfos;
6045 std::vector<unsigned> FuncCloneParent;
6048 ImplicitSourceMap ImplicitSources;
6055 struct OrigCallsInfo {
6059 DenseMap<const ContextNode *, OrigCallsInfo> OrigNodeToOrigCalls;
6060 for (
auto &
Call : CallsWithMetadata) {
6061 ContextNode *
Node = getNodeForInst(
Call);
6063 OrigNodeToOrigCalls[
Node] = {
Call,
Node->MatchingCalls};
6065 for (
auto &
Call : CallsWithMetadata) {
6066 ContextNode *
Node = getNodeForInst(
Call);
6070 if (!Node ||
Node->Clones.empty())
6073 "Not having a call should have prevented cloning");
6077 std::map<FuncInfo, ContextNode *> FuncCloneToCurNodeCloneMap;
6081 auto AssignCallsiteCloneToFuncClone = [&](
const FuncInfo &FuncClone,
6083 ContextNode *CallsiteClone,
6086 FuncCloneToCurNodeCloneMap[FuncClone] = CallsiteClone;
6088 assert(FuncCloneInfos.size() > FuncClone.cloneNo());
6089 DenseMap<CallInfo, CallInfo> &CallMap =
6090 FuncCloneInfos[FuncClone.cloneNo()].CallMap;
6091 CallInfo CallClone(
Call);
6092 if (
auto It = CallMap.
find(
Call); It != CallMap.
end())
6093 CallClone = It->second;
6094 CallsiteClone->setCall(CallClone);
6100 CallsiteClone->MatchingCalls.clear();
6101 for (
const CallInfo &OrigMatchingCall :
6102 OrigNodeToOrigCalls[Node].MatchingCalls) {
6103 CallInfo CallClone(OrigMatchingCall);
6104 if (
auto It = CallMap.
find(OrigMatchingCall); It != CallMap.
end())
6105 CallClone = It->second;
6106 CallsiteClone->MatchingCalls.push_back(CallClone);
6114 auto MoveEdgeToNewCalleeCloneAndSetUp =
6115 [&](
const std::shared_ptr<ContextEdge> &
Edge) {
6116 ContextNode *OrigCallee =
Edge->Callee;
6117 ContextNode *NewClone = moveEdgeToNewCalleeClone(
Edge);
6118 removeNoneTypeCalleeEdges(NewClone);
6119 assert(NewClone->AllocTypes != (uint8_t)AllocationType::None);
6123 if (CallsiteToCalleeFuncCloneMap.
count(OrigCallee))
6124 RecordCalleeFuncOfCallsite(
6125 NewClone, CallsiteToCalleeFuncCloneMap[OrigCallee]);
6132 std::deque<ContextNode *> ClonesWorklist;
6134 if (!
Node->emptyContextIds())
6135 ClonesWorklist.push_back(Node);
6141 unsigned NodeCloneCount = 0;
6142 while (!ClonesWorklist.empty()) {
6143 ContextNode *Clone = ClonesWorklist.front();
6144 ClonesWorklist.pop_front();
6146 if (Opts.memprof_verify_nodes)
6153 if (FuncCloneInfos.size() < NodeCloneCount) {
6155 if (NodeCloneCount == 1) {
6160 Clone->CallerEdges, [&](
const std::shared_ptr<ContextEdge> &
E) {
6161 return CallsiteToCalleeFuncCloneMap.count(E->Caller);
6165 FuncCloneInfos.push_back(
6166 {OrigFunc, DenseMap<CallInfo, CallInfo>()});
6167 FuncCloneParent.push_back(0);
6168 AssignCallsiteCloneToFuncClone(
6169 OrigFunc,
Call, Clone,
6170 AllocationCallToContextNodeMap.count(
Call));
6171 for (
auto &CE : Clone->CallerEdges) {
6173 if (!
CE->Caller->hasCall())
6175 RecordCalleeFuncOfCallsite(
CE->Caller, OrigFunc);
6185 FuncInfo PreviousAssignedFuncClone;
6187 Clone->CallerEdges, [&](
const std::shared_ptr<ContextEdge> &
E) {
6188 return CallsiteToCalleeFuncCloneMap.count(E->Caller);
6190 bool CallerAssignedToCloneOfFunc =
false;
6191 if (EI != Clone->CallerEdges.end()) {
6192 const std::shared_ptr<ContextEdge> &
Edge = *EI;
6193 PreviousAssignedFuncClone =
6194 CallsiteToCalleeFuncCloneMap[
Edge->Caller];
6195 CallerAssignedToCloneOfFunc =
true;
6200 DenseMap<CallInfo, CallInfo> NewCallMap;
6201 unsigned CloneNo = FuncCloneInfos.size();
6202 assert(CloneNo > 0 &&
"Clone 0 is the original function, which "
6203 "should already exist in the map");
6204 FuncInfo NewFuncClone = cloneFunctionForCallsite(
6205 OrigFunc,
Call, NewCallMap, CallsWithMetadata, CloneNo);
6206 FuncCloneInfos.push_back({NewFuncClone, std::move(NewCallMap)});
6209 FuncCloneParent.push_back(CallerAssignedToCloneOfFunc
6210 ? PreviousAssignedFuncClone.cloneNo()
6212 FunctionClonesAnalysis++;
6218 if (!CallerAssignedToCloneOfFunc) {
6219 AssignCallsiteCloneToFuncClone(
6220 NewFuncClone,
Call, Clone,
6221 AllocationCallToContextNodeMap.count(
Call));
6222 for (
auto &CE : Clone->CallerEdges) {
6224 if (!
CE->Caller->hasCall())
6226 RecordCalleeFuncOfCallsite(
CE->Caller, NewFuncClone);
6238 auto CallerEdges = Clone->CallerEdges;
6239 for (
auto CE : CallerEdges) {
6241 if (
CE->isRemoved()) {
6247 if (!
CE->Caller->hasCall())
6250 if (!CallsiteToCalleeFuncCloneMap.
count(
CE->Caller) ||
6254 CallsiteToCalleeFuncCloneMap[
CE->Caller] !=
6255 PreviousAssignedFuncClone)
6258 RecordCalleeFuncOfCallsite(
CE->Caller, NewFuncClone);
6271 auto CalleeEdges =
CE->Caller->CalleeEdges;
6272 for (
auto CalleeEdge : CalleeEdges) {
6275 if (CalleeEdge->isRemoved()) {
6280 ContextNode *
Callee = CalleeEdge->Callee;
6284 if (Callee == Clone || !
Callee->hasCall())
6289 if (Callee == CalleeEdge->Caller)
6291 ContextNode *NewClone =
6292 MoveEdgeToNewCalleeCloneAndSetUp(CalleeEdge);
6295 removeNoneTypeCalleeEdges(Callee);
6308 auto &OrigCalls = OrigNodeToOrigCalls[
Callee->getOrigNode()];
6309 DenseMap<CallInfo, CallInfo> &CallMap =
6310 FuncCloneInfos[NewFuncClone.cloneNo()].CallMap;
6312 CallInfo NewCall(CallMap[OrigCalls.Call]);
6314 NewClone->setCall(NewCall);
6316 NewClone->MatchingCalls.clear();
6317 for (
auto &OrigMatchingCall : OrigCalls.MatchingCalls) {
6319 CallInfo NewCall(CallMap[OrigMatchingCall]);
6321 NewClone->MatchingCalls.push_back(NewCall);
6330 auto FindFirstAvailFuncClone = [&]() {
6335 for (
auto &CF : FuncCloneInfos) {
6336 if (!FuncCloneToCurNodeCloneMap.count(CF.FuncClone))
6337 return CF.FuncClone;
6340 "Expected an available func clone for this callsite clone");
6357 std::map<FuncInfo, ContextNode *> FuncCloneToNewCallsiteCloneMap;
6358 FuncInfo FuncCloneAssignedToCurCallsiteClone;
6362 auto CloneCallerEdges = Clone->CallerEdges;
6363 for (
auto &
Edge : CloneCallerEdges) {
6367 if (
Edge->isRemoved())
6370 if (!
Edge->Caller->hasCall())
6374 if (CallsiteToCalleeFuncCloneMap.
count(
Edge->Caller)) {
6375 FuncInfo FuncCloneCalledByCaller =
6376 CallsiteToCalleeFuncCloneMap[
Edge->Caller];
6386 if ((FuncCloneToCurNodeCloneMap.count(FuncCloneCalledByCaller) &&
6387 FuncCloneToCurNodeCloneMap[FuncCloneCalledByCaller] !=
6395 (FuncCloneAssignedToCurCallsiteClone &&
6396 FuncCloneAssignedToCurCallsiteClone !=
6397 FuncCloneCalledByCaller)) {
6412 if (FuncCloneToNewCallsiteCloneMap.count(
6413 FuncCloneCalledByCaller)) {
6414 ContextNode *NewClone =
6415 FuncCloneToNewCallsiteCloneMap[FuncCloneCalledByCaller];
6416 moveEdgeToExistingCalleeClone(
Edge, NewClone);
6418 removeNoneTypeCalleeEdges(NewClone);
6421 ContextNode *NewClone = MoveEdgeToNewCalleeCloneAndSetUp(
Edge);
6422 FuncCloneToNewCallsiteCloneMap[FuncCloneCalledByCaller] =
6425 ClonesWorklist.push_back(NewClone);
6429 removeNoneTypeCalleeEdges(Clone);
6437 if (!FuncCloneAssignedToCurCallsiteClone) {
6438 FuncCloneAssignedToCurCallsiteClone = FuncCloneCalledByCaller;
6440 AssignCallsiteCloneToFuncClone(
6441 FuncCloneCalledByCaller,
Call, Clone,
6442 AllocationCallToContextNodeMap.count(
Call));
6446 assert(FuncCloneAssignedToCurCallsiteClone ==
6447 FuncCloneCalledByCaller);
6456 if (!FuncCloneAssignedToCurCallsiteClone) {
6457 FuncCloneAssignedToCurCallsiteClone = FindFirstAvailFuncClone();
6458 assert(FuncCloneAssignedToCurCallsiteClone);
6460 AssignCallsiteCloneToFuncClone(
6461 FuncCloneAssignedToCurCallsiteClone,
Call, Clone,
6462 AllocationCallToContextNodeMap.count(
Call));
6464 assert(FuncCloneToCurNodeCloneMap
6465 [FuncCloneAssignedToCurCallsiteClone] == Clone);
6467 RecordCalleeFuncOfCallsite(
Edge->Caller,
6468 FuncCloneAssignedToCurCallsiteClone);
6488 if (!FuncCloneAssignedToCurCallsiteClone) {
6489 FuncCloneAssignedToCurCallsiteClone = FindFirstAvailFuncClone();
6490 assert(FuncCloneAssignedToCurCallsiteClone &&
6491 "No available func clone for this callsite clone");
6492 AssignCallsiteCloneToFuncClone(
6493 FuncCloneAssignedToCurCallsiteClone,
Call, Clone,
6494 AllocationCallToContextNodeMap.contains(
Call));
6497 assignImplicitCallers(Node, TrimmedContextIds,
6498 CallsiteToCalleeFuncCloneMap,
6499 FuncCloneToCurNodeCloneMap, ImplicitSources);
6500 if (Opts.memprof_verify_ccg) {
6502 for (
const auto &PE :
Node->CalleeEdges)
6504 for (
const auto &CE :
Node->CallerEdges)
6506 for (
auto *Clone :
Node->Clones) {
6508 for (
const auto &PE : Clone->CalleeEdges)
6510 for (
const auto &CE : Clone->CallerEdges)
6516 if (Opts.memprof_report_hinted_sizes_detail)
6517 FuncToNumClones[
Func] = std::max<unsigned>(1, FuncCloneInfos.size());
6518 if (FuncCloneInfos.size() < 2)
6524 for (
auto &
Call : CallsWithMetadata) {
6525 ContextNode *
Node = getNodeForInst(
Call);
6526 if (!Node || !
Node->hasCall() ||
Node->emptyContextIds())
6531 DenseMap<unsigned, const ContextNode *> FuncCloneToNodeClone;
6532 FuncCloneToNodeClone[
Node->Call.cloneNo()] =
Node;
6540 for (
auto *
C :
Node->Clones)
6541 if (!
C->emptyContextIds() ||
6542 !ImplicitSources.contains({Node, C->Call.cloneNo()}))
6543 FuncCloneToNodeClone[
C->Call.cloneNo()] =
C;
6546 if (FuncCloneToNodeClone.
size() >= FuncCloneInfos.size())
6549 for (
auto &FC : FuncCloneInfos) {
6550 unsigned I =
FC.FuncClone.cloneNo();
6553 if (
I == 0 || FuncCloneToNodeClone.
contains(
I)) {
6561 auto &
Info = UnassignedCallClones[
Node][
I];
6562 auto &CallVector =
Info.Calls;
6563 for (
unsigned P =
I;;
P = FuncCloneParent[
P]) {
6564 if (
auto It = ImplicitSources.find({Node, P});
6565 It != ImplicitSources.end()) {
6566 Info.Source = resolveImplicitSource(Node, It->second);
6569 if (
auto It = FuncCloneToNodeClone.
find(
P);
6570 It != FuncCloneToNodeClone.
end()) {
6571 Info.Source = It->second;
6577 DenseMap<CallInfo, CallInfo> &CallMap =
FC.CallMap;
6578 if (
auto It = CallMap.
find(
Call); It != CallMap.
end()) {
6579 CallInfo CallClone = It->second;
6580 CallVector.push_back(CallClone);
6584 assert(
false &&
"Expected to find call in CallMap");
6590 for (
const CallInfo &OrigMatchingCall :
6591 OrigNodeToOrigCalls[Node].MatchingCalls) {
6592 if (
auto It = CallMap.
find(OrigMatchingCall); It != CallMap.
end()) {
6593 CallInfo CallClone = It->second;
6594 CallVector.push_back(CallClone);
6598 assert(
false &&
"Expected to find call in CallMap");
6606 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
6608 auto UpdateCalls = [&](ContextNode *
Node,
6609 DenseSet<const ContextNode *> &Visited,
6610 auto &&UpdateCalls) {
6611 auto Inserted = Visited.insert(Node);
6615 for (
auto *Clone :
Node->Clones)
6616 UpdateCalls(Clone, Visited, UpdateCalls);
6618 for (
auto &
Edge :
Node->CallerEdges)
6619 UpdateCalls(
Edge->Caller, Visited, UpdateCalls);
6623 if (!
Node->hasCall() ||
Node->emptyContextIds())
6629 auto GetUnassignedCallClones = [&](ContextNode *
Node) {
6632 auto UnassignedIt = UnassignedCallClones.
find(Node);
6633 if (UnassignedIt == UnassignedCallClones.
end())
6635 DenseSet<unsigned> NodeCallClones;
6636 for (
auto *
C :
Node->Clones)
6637 if (!
C->emptyContextIds())
6638 NodeCallClones.
insert(
C->Call.cloneNo());
6639 for (
auto &[CloneNo, Info] : UnassignedIt->second) {
6643 if (NodeCallClones.
contains(CloneNo))
6650 if (
Node->IsAllocation) {
6651 auto GetAllocTypeToUse = [&](
const ContextNode *
Node) {
6652 auto AT = allocTypeToUse(
Node->AllocTypes);
6664 !ContextIdToContextSizeInfos.empty()) {
6667 for (
auto Id :
Node->getContextIds()) {
6668 auto TypeI = ContextIdToAllocationType.find(Id);
6669 assert(TypeI != ContextIdToAllocationType.end());
6670 auto CSI = ContextIdToContextSizeInfos.find(Id);
6671 if (CSI != ContextIdToContextSizeInfos.end()) {
6672 for (
auto &Info : CSI->second) {
6674 if (TypeI->second == AllocationType::Cold)
6675 TotalCold +=
Info.TotalSize;
6680 AT = AllocationType::Cold;
6684 updateAllocationCall(
Node->Call, GetAllocTypeToUse(Node));
6685 if (Opts.memprof_report_hinted_sizes_detail)
6686 OrigAllocAndCloneToNode[{
Node->getOrigNode(),
Node->Call.cloneNo()}] =
6691 for (
auto &[Source, Calls] : GetUnassignedCallClones(Node)) {
6692 auto AT = GetAllocTypeToUse(Source);
6693 for (
auto &
Call : Calls) {
6694 updateAllocationCall(
Call, AT);
6696 if (Opts.memprof_report_hinted_sizes_detail)
6697 OrigAllocAndCloneToNode[{
Node->getOrigNode(),
Call.cloneNo()}] =
6704 auto CalleeFuncIt = CallsiteToCalleeFuncCloneMap.
find(Node);
6705 if (CalleeFuncIt != CallsiteToCalleeFuncCloneMap.
end()) {
6706 auto &CalleeFunc = CalleeFuncIt->second;
6707 updateCall(
Node->Call, CalleeFunc);
6708 if (Opts.memprof_report_hinted_sizes_detail)
6709 OrigNodeAndCloneToCalleeClone[{
6710 Node->getOrigNode(),
Node->Call.cloneNo()}] = CalleeFunc.cloneNo();
6712 for (
auto &
Call :
Node->MatchingCalls)
6713 updateCall(
Call, CalleeFunc);
6719 for (
auto &[Source, Calls] : GetUnassignedCallClones(Node)) {
6720 auto It = CallsiteToCalleeFuncCloneMap.
find(Source);
6722 if (It == CallsiteToCalleeFuncCloneMap.
end())
6724 if (It == CallsiteToCalleeFuncCloneMap.
end())
6726 for (
auto &
Call : Calls) {
6727 updateCall(
Call, It->second);
6728 if (Opts.memprof_report_hinted_sizes_detail)
6729 OrigNodeAndCloneToCalleeClone[{
Node->getOrigNode(),
Call.cloneNo()}] =
6730 It->second.cloneNo();
6740 DenseSet<const ContextNode *> Visited;
6741 for (
auto &Entry : AllocationCallToContextNodeMap)
6742 UpdateCalls(
Entry.second, Visited, UpdateCalls);
6764 for (
auto [Index, SN] :
enumerate(FS->callsites())) {
6769 SN.Clones.size() >
I &&
6770 "Callsite summary has fewer entries than other summaries in function");
6771 if (SN.Clones.size() <=
I || !SN.Clones[
I])
6773 AddRecord(
'c', Index, SN.Clones[
I]);
6776 for (
auto [Index, AN] :
enumerate(FS->allocs())) {
6780 assert(AN.Versions.size() >
I &&
6781 "Alloc summary has fewer entries than other summaries in function");
6782 if (AN.Versions.size() <=
I ||
6785 AddRecord(
'a', Index, AN.Versions[
I]);
6794 for (
auto &SN : FS->callsites()) {
6795 assert(SN.Clones.size() >
I && SN.Clones.size() > J &&
6796 "Callsite summary has fewer entries than other summaries in "
6798 if (SN.Clones[
I] != SN.Clones[J])
6801 for (
auto &AN : FS->allocs()) {
6802 assert(AN.Versions.size() >
I && AN.Versions.size() > J &&
6803 "Alloc summary has fewer entries than other summaries in function");
6804 if (AN.Versions[
I] != AN.Versions[J])
6820 NewGV->takeName(DeclGV);
6827 auto CloneFuncAliases = [&](
Function *NewF,
unsigned I) {
6828 if (!FuncToAliasMap.count(&
F))
6830 for (
auto *
A : FuncToAliasMap[&
F]) {
6832 auto *PrevA = M.getNamedAlias(AliasName);
6834 A->getType()->getPointerAddressSpace(),
6835 A->getLinkage(), AliasName, NewF);
6836 NewA->copyAttributesFrom(
A);
6838 TakeDeclNameAndReplace(PrevA, NewA);
6847 FunctionsClonedThinBackend++;
6864 for (
unsigned I = 1;
I < NumClones;
I++) {
6865 VMaps.
emplace_back(std::make_unique<ValueToValueMapTy>());
6871 if (
auto It = HashToFunc.
find(Hash); It != HashToFunc.
end()) {
6872 FunctionCloneDuplicatesThinBackend++;
6873 auto [Func, OrigI] = It->second;
6875 "Duplicate clone hash collision");
6876 if (Func->hasAvailableExternallyLinkage()) {
6882 auto Decl = M.getOrInsertFunction(Name, Func->getFunctionType());
6884 <<
"created clone decl " <<
ore::NV(
"Decl", Decl.getCallee()));
6887 auto *PrevF = M.getFunction(Name);
6890 TakeDeclNameAndReplace(PrevF, Alias);
6892 <<
"created clone alias " <<
ore::NV(
"Alias", Alias));
6895 CloneFuncAliases(Func,
I);
6899 "Attempting to clone function with escaping block address");
6901 HashToFunc[Hash] = {NewF,
I};
6902 FunctionClonesThinBackend++;
6904 NewF->
setMetadata(LLVMContext::MD_kcfi_type,
nullptr);
6907 for (
auto &BB : *NewF) {
6908 for (
auto &Inst : BB) {
6909 Inst.setMetadata(LLVMContext::MD_memprof,
nullptr);
6910 Inst.setMetadata(LLVMContext::MD_callsite,
nullptr);
6913 auto *PrevF = M.getFunction(Name);
6915 TakeDeclNameAndReplace(PrevF, NewF);
6917 NewF->setName(Name);
6920 <<
"created clone " <<
ore::NV(
"NewFunction", NewF));
6923 CloneFuncAliases(NewF,
I);
6932static std::optional<GlobalValue::GUID>
6934 if (
auto *MD =
F.getMetadata(
"thinlto_alias_guid"))
6936 return std::nullopt;
6943 const Function *CallingFunc =
nullptr) {
6947 assert(AliasVI &&
"Expected ValueInfo for imported alias GUID");
6970 MDNode *SrcFileMD = GO ? GO->getMetadata(
"thinlto_src_file") :
nullptr;
6980 SrcFileMD = CallingFunc->getMetadata(
"thinlto_src_file");
6987 StringRef SrcFile = M.getSourceFileName();
7024 &OrigNameGUIDToTailCallCallsite,
7028 auto End = MapTailCallCalleeVIToCallsite.
end();
7032 auto It = MapTailCallCalleeVIToCallsite.
find(VI);
7041 auto It = MapTailCallCalleeVIToCallsite.
find(LocalVI);
7051 if (!OrigNameGUIDToTailCallCallsite) {
7054 OrigNameGUIDToTailCallCallsite.emplace();
7055 for (
const auto &[CalleeVI, Callsite] : MapTailCallCalleeVIToCallsite) {
7064 AliasVIToGV.emplace();
7070 AliasVIToGV->try_emplace(VI, &
A);
7073 Callee = AliasVIToGV->lookup(CalleeVI);
7079 auto [It, Inserted] = OrigNameGUIDToTailCallCallsite->try_emplace(
7083 if (!Inserted && It->second != &Callsite)
7084 It->second =
nullptr;
7087 return OrigNameGUIDToTailCallCallsite->lookup(CandidateGUID);
7090bool MemProfContextDisambiguation::initializeIndirectCallPromotionInfo(
7092 ICallAnalysis = std::make_unique<ICallPromotionAnalysis>();
7093 Symtab = std::make_unique<InstrProfSymtab>();
7111 AliaseeGUIDToImportedAlias.reset();
7112 if (
Error E = Symtab->create(M,
true,
false,
7114 std::string SymtabFailure =
toString(std::move(
E));
7115 M.getContext().emitError(
"Failed to create symtab: " + SymtabFailure);
7128 auto MIBIter = AllocNode.
MIBs.begin();
7129 for (
auto &MDOp : MemProfMD->
operands()) {
7138 if (MIBIter->StackIdIndices.empty()) {
7142 auto StackIdIndexIter = MIBIter->StackIdIndices.begin();
7147 auto ContextIterBegin =
7151 (ContextIterBegin != StackContext.
end() && *ContextIterBegin == 0) ? 1
7153 for (
auto ContextIter = ContextIterBegin; ContextIter != StackContext.
end();
7158 if (LastStackContextId == *ContextIter)
7160 LastStackContextId = *ContextIter;
7161 assert(StackIdIndexIter != MIBIter->StackIdIndices.end());
7171bool MemProfContextDisambiguation::applyImport(
7172 Module &M,
const ModuleSummaryIndex *Summary) {
7179 std::map<const Function *, SmallPtrSet<const GlobalAlias *, 1>>
7181 for (
auto &
A :
M.aliases()) {
7182 auto *Aliasee =
A.getAliaseeObject();
7184 FuncToAliasMap[
F].insert(&
A);
7187 if (!initializeIndirectCallPromotionInfo(M))
7193 std::optional<DenseMap<ValueInfo, const GlobalAlias *>> AliasVIToGV;
7199 OptimizationRemarkEmitter ORE(&
F);
7202 bool ClonesCreated =
false;
7203 unsigned NumClonesCreated = 0;
7204 auto CloneFuncIfNeeded = [&](
unsigned NumClones, FunctionSummary *
FS) {
7214 if (ClonesCreated) {
7215 assert(NumClonesCreated == NumClones);
7222 ClonesCreated =
true;
7223 NumClonesCreated = NumClones;
7226 auto CloneCallsite = [&](
const CallsiteInfo &StackNode, CallBase *CB,
7227 Function *CalledFunction, FunctionSummary *
FS) {
7229 CloneFuncIfNeeded(StackNode.
Clones.
size(), FS);
7241 if (CalledFunction != CB->getCalledOperand() &&
7242 (!GA || CalledFunction != GA->getAliaseeObject())) {
7243 SkippedCallsCloning++;
7249 auto CalleeOrigName = CalledFunction->getName();
7250 for (
unsigned J = 0; J < StackNode.
Clones.
size(); J++) {
7253 if (J > 0 && VMaps[J - 1]->
empty())
7257 if (!StackNode.
Clones[J])
7259 auto NewF =
M.getOrInsertFunction(
7261 CalledFunction->getFunctionType());
7275 ORE.emit(OptimizationRemark(
DEBUG_TYPE,
"MemprofCall", CBClone)
7276 <<
ore::NV(
"Call", CBClone) <<
" in clone "
7278 <<
" assigned to call function clone "
7279 <<
ore::NV(
"Callee", NewF.getCallee()));
7293 Summary->findSummaryInModule(TheFnVI,
M.getModuleIdentifier());
7297 auto SrcModuleMD =
F.getMetadata(
"thinlto_src_module");
7299 "enable-import-metadata is needed to emit thinlto_src_module");
7300 StringRef SrcModule =
7303 if (GVS->modulePath() == SrcModule) {
7304 GVSummary = GVS.get();
7308 assert(GVSummary && GVSummary->modulePath() == SrcModule);
7318 if (
FS->allocs().empty() &&
FS->callsites().empty())
7321 auto SI =
FS->callsites().begin();
7322 auto AI =
FS->allocs().begin();
7327 DenseMap<ValueInfo, CallsiteInfo> MapTailCallCalleeVIToCallsite;
7330 for (
auto CallsiteIt =
FS->callsites().rbegin();
7331 CallsiteIt !=
FS->callsites().rend(); CallsiteIt++) {
7332 auto &Callsite = *CallsiteIt;
7336 if (!Callsite.StackIdIndices.empty())
7338 MapTailCallCalleeVIToCallsite.
insert({Callsite.Callee, Callsite});
7342 std::optional<DenseMap<uint64_t, const CallsiteInfo *>>
7343 OrigNameGUIDToTailCallCallsite;
7351 for (
auto &BB :
F) {
7352 for (
auto &
I : BB) {
7358 auto *CalledValue = CB->getCalledOperand();
7359 auto *CalledFunction = CB->getCalledFunction();
7360 if (CalledValue && !CalledFunction) {
7361 CalledValue = CalledValue->stripPointerCasts();
7368 assert(!CalledFunction &&
7369 "Expected null called function in callsite for alias");
7373 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(
7374 I.getMetadata(LLVMContext::MD_callsite));
7375 auto *MemProfMD =
I.getMetadata(LLVMContext::MD_memprof);
7381 if (CB->getAttributes().hasFnAttr(
"memprof") && !MemProfMD) {
7382 CB->getAttributes().getFnAttr(
"memprof").getValueAsString() ==
"cold"
7383 ? AllocTypeColdThinBackend++
7384 : AllocTypeNotColdThinBackend++;
7385 OrigAllocsThinBackend++;
7386 AllocVersionsThinBackend++;
7387 if (!MaxAllocVersionsThinBackend)
7388 MaxAllocVersionsThinBackend = 1;
7395 auto &AllocNode = *(AI++);
7402 CloneFuncIfNeeded(AllocNode.Versions.size(), FS);
7404 OrigAllocsThinBackend++;
7405 AllocVersionsThinBackend += AllocNode.Versions.size();
7406 if (MaxAllocVersionsThinBackend < AllocNode.Versions.size())
7407 MaxAllocVersionsThinBackend = AllocNode.Versions.size();
7419 if (AllocNode.Versions.size() == 1 &&
7421 UnclonableAllocsThinBackend++;
7424 for (
unsigned J = 0; J < AllocNode.Versions.size(); J++) {
7427 if (J > 0 && VMaps[J - 1]->
empty())
7430 if (AllocNode.Versions[J] == (uint8_t)AllocationType::None)
7438 AllocTy = AllocationType::NotCold;
7440 if (AllocTy == AllocationType::Cold)
7441 AllocTypeColdThinBackend++;
7442 else if (IsAmbiguous)
7443 AllocTypeAmbiguousThinBackend++;
7445 AllocTypeNotColdThinBackend++;
7465 ORE.emit(OptimizationRemark(
DEBUG_TYPE,
"MemprofAttribute", CBClone)
7466 <<
ore::NV(
"AllocationCall", CBClone) <<
" in clone "
7468 <<
" marked with memprof allocation attribute "
7469 <<
ore::NV(
"Attribute", AllocTypeString));
7471 }
else if (!CallsiteContext.empty()) {
7472 if (!CalledFunction) {
7476 assert(!CI || !CI->isInlineAsm());
7486 auto NumClones = recordICPInfo(
7488 [&](
const InstrProfValueData &Candidate) {
7489 assert(SI !=
FS->callsites().end());
7491 auto CalleeValueInfo =
Summary->getValueInfo(Candidate.Value);
7493 Summary->getGUIDFromOriginalID(Candidate.Value);
7501 assert(!CalleeValueInfo ||
SI->Callee == CalleeValueInfo ||
7502 (
SI->Callee &&
SI->Callee.getGUID() == LocalGUID));
7511 CloneFuncIfNeeded(NumClones, FS);
7516 assert(SI !=
FS->callsites().end());
7517 auto &StackNode = *(
SI++);
7523 for (
auto StackId : CallsiteContext) {
7525 assert(
Summary->getStackIdAtIndex(*StackIdIndexIter) == StackId);
7530 CloneCallsite(StackNode, CB, CalledFunction, FS);
7532 }
else if (CB->isTailCall() && CalledFunction) {
7537 if (CalleeVI && MapTailCallCalleeVIToCallsite.
count(CalleeVI)) {
7538 auto Callsite = MapTailCallCalleeVIToCallsite.
find(CalleeVI);
7539 assert(Callsite != MapTailCallCalleeVIToCallsite.
end());
7540 CloneCallsite(Callsite->second, CB, CalledFunction, FS);
7542 }
else if (CB->isTailCall() && !CalledFunction &&
7543 !MapTailCallCalleeVIToCallsite.
empty()) {
7549 auto PrevNumICallAnalysisInfo = ICallAnalysisInfo.
size();
7550 auto NumClones = recordICPInfo(
7552 [&](
const InstrProfValueData &Candidate) {
7554 Candidate.Value, MapTailCallCalleeVIToCallsite,
7555 OrigNameGUIDToTailCallCallsite, AliasVIToGV, M, Summary,
7559 if (ICallAnalysisInfo.
size() > PrevNumICallAnalysisInfo)
7560 IndirectTailCallsRecordedForICPThinBackend++;
7562 CloneFuncIfNeeded(NumClones, FS);
7568 performICP(M, VMaps, ICallAnalysisInfo, ORE);
7578 for (
auto &BB :
F) {
7579 for (
auto &
I : BB) {
7582 I.setMetadata(LLVMContext::MD_memprof,
nullptr);
7583 I.setMetadata(LLVMContext::MD_callsite,
nullptr);
7591unsigned MemProfContextDisambiguation::recordICPInfo(
7593 function_ref<
const CallsiteInfo *(
const InstrProfValueData &)> GetCallsite,
7596 uint32_t NumCandidates;
7598 auto CandidateProfileData =
7599 ICallAnalysis->getPromotionCandidatesForInstruction(
7600 CB, TotalCount, NumCandidates,
7602 if (CandidateProfileData.empty())
7608 bool ICPNeeded =
false;
7609 unsigned NumClones = 0;
7611 for (
const auto &Candidate : CandidateProfileData) {
7612 const CallsiteInfo *Callsite = GetCallsite(Candidate);
7620 [](
unsigned CloneNo) { return CloneNo != 0; });
7630 ICallAnalysisInfo.
push_back({CB, CandidateProfileData.vec(), NumCandidates,
7631 TotalCount, NumClones, std::move(Callsites)});
7635void MemProfContextDisambiguation::performICP(
7638 OptimizationRemarkEmitter &ORE) {
7646 for (
auto &Info : ICallAnalysisInfo) {
7648 auto TotalCount =
Info.TotalCount;
7649 unsigned NumClones =
Info.NumClones;
7652 assert(
Info.CandidateProfileData.size() ==
Info.Callsites.size());
7653 for (
unsigned I = 0;
I <
Info.CandidateProfileData.size();
I++) {
7654 auto &Candidate =
Info.CandidateProfileData[
I];
7655 const CallsiteInfo *StackNode =
Info.Callsites[
I];
7663 Function *TargetFunction = Symtab->getFunction(Candidate.Value);
7674 if (!TargetFunction && StackNode && StackNode->
Callee &&
7685 if (!TargetFunction) {
7686 if (!AliaseeGUIDToImportedAlias) {
7687 AliaseeGUIDToImportedAlias.emplace();
7691 if (
auto AliaseeGUID = Fn.getGUIDIfAssigned())
7692 AliaseeGUIDToImportedAlias->try_emplace(*AliaseeGUID, &Fn);
7695 TargetFunction = AliaseeGUIDToImportedAlias->lookup(Candidate.Value);
7696 if (!TargetFunction && StackNode && StackNode->
Callee &&
7699 AliaseeGUIDToImportedAlias->lookup(StackNode->
Callee.
getGUID());
7701 if (TargetFunction ==
nullptr ||
7706 (Opts.memprof_require_definition_for_promotion &&
7709 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnableToFindTarget", CB)
7710 <<
"Memprof cannot promote indirect call: target with md5sum "
7711 <<
ore::NV(
"target md5sum", Candidate.Value) <<
" not found";
7716 RemainingCandidates.
push_back(Candidate);
7721 const char *Reason =
nullptr;
7724 return OptimizationRemarkMissed(
DEBUG_TYPE,
"UnableToPromote", CB)
7725 <<
"Memprof cannot promote indirect call to "
7726 <<
ore::NV(
"TargetFunction", TargetFunction)
7727 <<
" with count of " <<
ore::NV(
"TotalCount", TotalCount)
7730 RemainingCandidates.
push_back(Candidate);
7739 CallBase *CBClone = CB;
7740 for (
unsigned J = 0; J < NumClones; J++) {
7743 if (J > 0 && VMaps[J - 1]->
empty())
7753 TotalCount, isSamplePGO, &ORE);
7754 auto *TargetToUse = TargetFunction;
7757 if (StackNode && StackNode->
Clones[J]) {
7772 if (Opts.memprof_icp_noinline_threshold &&
7773 Candidate.Count < Opts.memprof_icp_noinline_threshold)
7776 <<
ore::NV(
"Call", CBClone) <<
" in clone "
7778 <<
" promoted and assigned to call function clone "
7779 <<
ore::NV(
"Callee", TargetToUse));
7783 TotalCount -= Candidate.Count;
7787 CallBase *CBClone = CB;
7788 for (
unsigned J = 0; J < NumClones; J++) {
7791 if (J > 0 && VMaps[J - 1]->
empty())
7797 CBClone->
setMetadata(LLVMContext::MD_prof,
nullptr);
7800 if (TotalCount != 0)
7802 IPVK_IndirectCallTarget,
Info.NumCandidates);
7807template <
typename DerivedCCG,
typename FuncTy,
typename CallTy>
7808bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::process(
7809 function_ref<
void(StringRef, StringRef,
const Twine &)> EmitRemark,
7810 bool AllowExtraAnalysis) {
7811 if (Opts.memprof_dump_ccg) {
7812 dbgs() <<
"CCG before cloning:\n";
7815 if (Opts.memprof_export_to_dot)
7816 exportToDot(
"postbuild");
7818 if (Opts.memprof_verify_ccg) {
7825 capturePreCloningContextInfo();
7829 if (Opts.memprof_verify_ccg) {
7833 if (Opts.memprof_dump_ccg) {
7834 dbgs() <<
"CCG after cloning:\n";
7837 if (Opts.memprof_export_to_dot)
7838 exportToDot(
"cloned");
7840 bool Changed = assignFunctions();
7842 if (Opts.memprof_dump_ccg) {
7843 dbgs() <<
"CCG after assigning function clones:\n";
7846 if (Opts.memprof_export_to_dot)
7847 exportToDot(
"clonefuncassign");
7856 populateFunctionsWithCallers();
7857 printTotalSizes(
errs(), EmitRemark);
7863static std::unique_ptr<ModuleSummaryIndex>
7866 if (!ReadSummaryFile) {
7868 "Error loading file '" +
Filename +
"': ");
7872 if (!ImportSummaryForTestingOrErr) {
7874 "Error parsing file '" +
Filename +
"': ");
7877 return std::move(*ImportSummaryForTestingOrErr);
7880bool MemProfContextDisambiguation::processModule(
7882 llvm::function_ref<OptimizationRemarkEmitter &(
Function *)> OREGetter) {
7885 const ModuleSummaryIndex *
Summary = ImportSummary;
7889 std::unique_ptr<ModuleSummaryIndex> SummaryForTesting;
7890 assert(Opts.memprof_import_summary.empty() || !Summary);
7891 if (!Summary && !Opts.memprof_import_summary.empty()) {
7894 Summary = SummaryForTesting.get();
7900 return applyImport(M, Summary);
7910 if (!Opts.supports_hot_cold_new)
7913 ModuleCallsiteContextGraph CCG(M, OREGetter);
7916 return CCG.process();
7921 : ImportSummary(Summary), isSamplePGO(isSamplePGO) {}
7925 return C.get<IPOOptions>().memprof_context_disambiguation;
7930 return C.get<IPOOptions>().supports_hot_cold_new;
7937 !Opts.memprof_dot_alloc_id)
7939 "-memprof-dot-scope=alloc requires -memprof-dot-alloc-id");
7941 !Opts.memprof_dot_context_id)
7943 "-memprof-dot-scope=context requires -memprof-dot-context-id");
7945 Opts.memprof_dot_alloc_id && Opts.memprof_dot_context_id)
7947 "-memprof-dot-scope=all can't have both -memprof-dot-alloc-id and "
7948 "-memprof-dot-context-id");
7958 if (!processModule(M, OREGetter))
7981 for (
auto &
I : Index) {
7982 auto VI = Index.getValueInfo(
I);
7983 for (
auto &S : VI.getSummaryList()) {
7987 !isPrevailing(VI.getGUID(), S.get()))
7990 if (!FS || FS->callsites().empty())
7992 CalleeToEdge.
clear();
7993 for (
auto &CI : FS->callsites()) {
7994 if (!CI.Callee ||
llvm::all_of(CI.Clones, [](
unsigned CloneNo) {
7995 return CloneNo == 0;
8002 NumClonedCalleeCallsites++;
8004 if (CalleeToEdge.
empty())
8005 for (
auto &[CalleeVI, Edge] : FS->mutableCalls())
8006 CalleeToEdge[CalleeVI] = &Edge;
8007 auto It = CalleeToEdge.
find(CI.Callee);
8008 if (It == CalleeToEdge.
end())
8015 if (!Edge->hasIndirectCall())
8017 NumClonedCalleeIndirectCallsites++;
8018 if (!Edge->requiresDeclImport()) {
8019 Edge->setRequiresDeclImport(
true);
8020 NumClonedCalleeEdgesMarkedRequiresDeclImport++;
8039 assert(Index.withSupportsHotColdNew() == Opts.supports_hot_cold_new);
8040 if (!Opts.supports_hot_cold_new)
8043 bool AllowExtraAnalysis =
8048 IndexCallsiteContextGraph CCG(Opts, Index, isPrevailing);
8049 Changed = CCG.process(EmitRemark, AllowExtraAnalysis);
8055 if (
Changed && Opts.memprof_import_cloned_indirect_targets &&
8056 !Opts.memprof_require_definition_for_promotion)
8072 for (
auto &BB :
F) {
8073 for (
auto &
I : BB) {
8077 if (CI->hasFnAttr(
"memprof")) {
8078 CI->removeFnAttr(
"memprof");
8081 if (!CI->hasMetadata(LLVMContext::MD_callsite)) {
8082 assert(!CI->hasMetadata(LLVMContext::MD_memprof));
8088 CI->setMetadata(LLVMContext::MD_memprof,
nullptr);
8089 CI->setMetadata(LLVMContext::MD_callsite,
nullptr);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Unify divergent function exit nodes
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Module.h This file contains the declarations for the Module class.
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
uint64_t ComputeHash(const FunctionSummary *FS, unsigned I)
static bool clonesHaveSameVersions(const FunctionSummary *FS, unsigned I, unsigned J)
static std::optional< GlobalValue::GUID > getImportedAliasGUID(const Function &F)
static void updateClonedCalleeEdgesForImport(ModuleSummaryIndex &Index, llvm::function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
static ValueInfo findValueInfoForGV(const GlobalValue &GV, const Module &M, const ModuleSummaryIndex *ImportSummary, const Function *CallingFunc=nullptr)
static void checkEdge(const std::shared_ptr< ContextEdge< DerivedCCG, FuncTy, CallTy > > &Edge)
bool checkColdOrNotCold(uint8_t AllocType)
static std::string getAllocTypeString(uint8_t AllocTypes)
static void checkDotOptions(const IPOOptions &Opts)
static bool hasEscapingBlockAddress(const Function &F)
static unsigned getMemProfCloneNum(const Function &F)
static SmallVector< std::unique_ptr< ValueToValueMapTy >, 4 > createFunctionClones(Function &F, unsigned NumClones, Module &M, OptimizationRemarkEmitter &ORE, std::map< const Function *, SmallPtrSet< const GlobalAlias *, 1 > > &FuncToAliasMap, FunctionSummary *FS)
static void checkNode(const ContextNode< DerivedCCG, FuncTy, CallTy > *Node, bool CheckEdges=true)
static std::string getMemProfFuncName(Twine Base, unsigned CloneNo)
static const CallsiteInfo * findIndirectTailCallCallsite(uint64_t CandidateGUID, const DenseMap< ValueInfo, CallsiteInfo > &MapTailCallCalleeVIToCallsite, std::optional< DenseMap< uint64_t, const CallsiteInfo * > > &OrigNameGUIDToTailCallCallsite, std::optional< DenseMap< ValueInfo, const GlobalAlias * > > &AliasVIToGV, const Module &M, const ModuleSummaryIndex *ImportSummary, InstrProfSymtab &Symtab)
static std::unique_ptr< ModuleSummaryIndex > loadImportSummaryForTesting(StringRef Filename)
static void updateSubprogramLinkageName(Function *NewFunc, StringRef Name)
static void checkAllocContextIds(const AllocInfo &AllocNode, const MDNode *MemProfMD, const CallStack< MDNode, MDNode::op_iterator > &CallsiteContext, const ModuleSummaryIndex *ImportSummary)
This is the interface to build a ModuleSummaryIndex for a module.
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
static constexpr StringLiteral Filename
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
FunctionAnalysisManager FAM
std::pair< BasicBlock *, BasicBlock * > Edge
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
void print(OutputBuffer &OB) const
ValueInfo getAliaseeVI() const
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
Get the array size.
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
bool empty() const
Check if the array is empty.
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
LLVM Basic Block Representation.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
void setCalledOperand(Value *V)
Subprogram description. Uses SubclassData1.
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
iterator find(const_arg_type_t< KeyT > Val)
void reserve(size_type NumEntries)
Grow the DenseMap so that it can contain at least NumEntries items before resizing again.
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
Function summary information to aid decisions and implementation of importing.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
DISubprogram * getSubprogram() const
Get the attached subprogram.
const Function & getFunction() const
static LLVM_ABI GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set a particular kind of metadata attachment.
Function and variable summary information to aid decisions and implementation of importing.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
static bool isLocalLinkage(LinkageTypes Linkage)
LLVM_ABI bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
bool hasLocalLinkage() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
LLVM_ABI GUID getGUID() const
Return a 64-bit global unique ID for this value.
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
bool isWeakForLinker() const
@ InternalLinkage
Rename collisions when linking (static functions).
A symbol table used for function [IR]PGO name look-up with keys (such as pointers,...
Function * getFunction(uint64_t FuncMD5Hash) const
Return function from the name's md5 hash. Return nullptr if not found.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
This is an important class for using LLVM in a threaded context.
const MDOperand & getOperand(unsigned I) const
ArrayRef< MDOperand > operands() const
unsigned getNumOperands() const
Return number of MDNode operands.
LLVM_ABI TempMDNode clone() const
Create a (temporary) clone of this.
static std::enable_if_t< std::is_base_of< MDNode, T >::value, T * > replaceWithUniqued(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a uniqued one.
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
size_type count(const KeyT &Key) const
static LLVM_ABI bool isEnabled(const cl::LibraryOptionsContext &C)
Return -memprof-context-disambiguation.
LLVM_ABI MemProfContextDisambiguation(const ModuleSummaryIndex *Summary=nullptr, bool isSamplePGO=false)
static LLVM_ABI bool supportsHotColdNew(const cl::LibraryOptionsContext &C)
Return -supports-hot-cold-new.
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
static StringRef getOriginalNameBeforePromote(StringRef Name)
Helper to obtain the unpromoted name for a global value (or the original name if not promoted).
ValueInfo getValueInfo(const GlobalValueSummaryMapTy::value_type &R) const
Return a ValueInfo for the index value_type (convenient when iterating index).
uint64_t getStackIdAtIndex(unsigned Index) const
GlobalValue::GUID getGUIDFromOriginalID(GlobalValue::GUID OriginalID) const
Return the GUID for OriginalId in the OidGuidMap.
A Module instance is used to store all the information related to an LLVM module.
LLVMContext & getContext() const
Get the global data context.
A NodeSet contains a set of SUnit DAG nodes with additional information that assigns a priority to th...
A discriminated union of two or more pointer types, with the discriminator in the low bits of the poi...
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
A class that wrap the SHA1 algorithm.
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
LLVM_ABI std::array< uint8_t, 20 > result()
Return the current raw 160-bits SHA1 for the digested data since the last call to init().
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
std::pair< StringRef, StringRef > rsplit(StringRef Separator) const
Split into two substrings around the last occurrence of a separator string.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
LLVMContext & getContext() const
All values hold a context through their type.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
std::pair< iterator, bool > insert(const ValueT &V)
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
bool erase(const ValueT &V)
void insert_range(Range &&R)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
bool remove_if(Predicate Pred)
Remove all elements for which Pred returns true.
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
An efficient, type-erasing, non-owning reference to a callable.
Helper class to iterate through stack ids in both metadata (memprof MIB and callsite) and the corresp...
CallStackIterator beginAfterSharedPrefix(const CallStack &Other)
CallStackIterator end() const
This class implements an extremely fast bulk output stream that can only output to a stream.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ CE
Windows NT (Windows on ARM)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
LLVM_ABI AllocationType getMIBAllocType(const MDNode *MIB)
Returns the allocation type from an MIB metadata node.
LLVM_ABI bool metadataMayIncludeContextSizeInfo()
Whether the alloc memprof metadata may include context size info for some MIBs (but possibly not all)...
LLVM_ABI bool hasSingleAllocType(uint8_t AllocTypes)
True if the AllocTypes bitmask contains just a single type.
LLVM_ABI bool isAmbiguousAllocType(uint8_t AllocTypes)
True if the AllocTypes bitmask contains both NotCold and Cold, i.e.
LLVM_ABI std::string getAllocTypeAttributeString(AllocationType Type)
Returns the string to use in attributes with the given type.
LLVM_ABI MDNode * getMIBStackNode(const MDNode *MIB)
Returns the stack node from an MIB metadata node.
LLVM_ABI void removeAnyExistingAmbiguousAttribute(CallBase *CB)
Removes any existing "ambiguous" memprof attribute.
LLVM_ABI void addAmbiguousAttribute(CallBase *CB)
Adds an "ambiguous" memprof attribute to call with a matched allocation profile but that we haven't y...
DiagnosticInfoOptimizationBase::Argument NV
LLVM_ABI CallBase & promoteIndirectCall(CallBase &CB, Function *F, uint64_t Count, uint64_t TotalCount, bool AttachProfToDirectCall, OptimizationRemarkEmitter *ORE)
NodeAddr< NodeBase * > Node
NodeAddr< FuncNode * > Func
friend class Instruction
Iterator for Instructions in a `BasicBlock.
uint64_t read64le(const void *P)
void write32le(void *P, uint32_t V)
This is an optimization pass for GlobalISel generic memory operations.
cl::opt< unsigned > MinClonedColdBytePercent("memprof-cloning-cold-threshold", cl::init(100), cl::Hidden, cl::desc("Min percent of cold bytes to hint alloc cold during cloning"))
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
void stable_sort(R &&Range)
cl::opt< bool > MemProfReportHintedSizes("memprof-report-hinted-sizes", cl::init(false), cl::Hidden, cl::desc("Report total allocation sizes of hinted allocations"))
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isLegalToPromote(const CallBase &CB, Function *Callee, const char **FailureReason=nullptr)
Return true if the given indirect call site can be made to call Callee.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
cl::opt< bool > MemProfUseAmbiguousAttributes
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
void set_intersect(S1Ty &S1, const S2Ty &S2)
set_intersect(A, B) - Compute A := A ^ B Identical to set_intersection, except that it works on set<>...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool mayHaveMemprofSummary(const CallBase *CB)
Returns true if the instruction could have memprof metadata, used to ensure consistency between summa...
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
void set_subtract(S1Ty &S1, const S2Ty &S2)
set_subtract(A, B) - Compute A := A - B
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
raw_ostream & WriteGraph(raw_ostream &O, const GraphType &G, bool ShortNames=false, const Twine &Title="")
bool isa_and_nonnull(const Y &Val)
bool set_intersects(const S1Ty &S1, const S2Ty &S2)
set_intersects(A, B) - Return true iff A ^ B is non empty
detail::concat_range< ValueT, RangeTs... > concat(RangeTs &&...Ranges)
Returns a concatenated range across two or more ranges.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
LLVM_ABI Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndex(MemoryBufferRef Buffer)
Parse the specified bitcode buffer, returning the module summary index.
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
const IPOOptions & getIPOOptions(const LLVMContext &C)
LLVM_ABI void annotateValueSite(Module &M, Instruction &Inst, const InstrProfRecord &InstrProfR, InstrProfValueKind ValueKind, uint32_t SiteIndx, uint32_t MaxMDCount=3)
Get the value profile data for value site SiteIdx from InstrProfR and annotate the instruction Inst w...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
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...
S1Ty set_intersection(const S1Ty &S1, const S2Ty &S2)
set_intersection(A, B) - Return A ^ B
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI unsigned getMaxSummaryIndirectEdges(const LLVMContext &C)
Return -module-summary-max-indirect-edges.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
S1Ty set_difference(const S1Ty &S1, const S2Ty &S2)
set_difference(A, B) - Return A - B
bool isMemProfClone(const GlobalValue &GV)
Returns true if GV is a MemProf context-disambiguated clone.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
constexpr StringLiteral MemProfCloneSuffix
@ End
Run the machine verifier once, at the end of the pipeline.
LLVM_ABI Function * CloneFunction(Function *F, ValueToValueMapTy &VMap, ClonedCodeInfo *CodeInfo=nullptr)
Return a copy of the specified function and add it to that function's module.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
DOTGraphTraits(bool IsSimple=false)
typename GTraits::NodeRef NodeRef
static std::string getEdgeAttributes(NodeRef, ChildIteratorType ChildIter, GraphType G)
const CallsiteContextGraph< DerivedCCG, FuncTy, CallTy > * GraphType
typename GTraits::ChildIteratorType ChildIteratorType
static std::string getNodeAttributes(NodeRef Node, GraphType G)
static bool isNodeHidden(NodeRef Node, GraphType G)
static std::string getNodeLabel(NodeRef Node, GraphType G)
GraphTraits< GraphType > GTraits
static NodeRef getNode(const NodePtrTy &P)
static const ContextNode< DerivedCCG, FuncTy, CallTy > * GetCallee(const EdgePtrTy &P)
static ChildIteratorType child_end(NodeRef N)
std::unique_ptr< ContextNode< DerivedCCG, FuncTy, CallTy > > NodePtrTy
mapped_iterator< typename std::vector< std::shared_ptr< ContextEdge< DerivedCCG, FuncTy, CallTy > > >::const_iterator, decltype(&GetCallee)> ChildIteratorType
const CallsiteContextGraph< DerivedCCG, FuncTy, CallTy > * GraphType
const ContextNode< DerivedCCG, FuncTy, CallTy > * NodeRef
mapped_iterator< typename std::vector< NodePtrTy >::const_iterator, decltype(&getNode)> nodes_iterator
static ChildIteratorType child_begin(NodeRef N)
static NodeRef getEntryNode(GraphType G)
static nodes_iterator nodes_begin(GraphType G)
static nodes_iterator nodes_end(GraphType G)
std::shared_ptr< ContextEdge< DerivedCCG, FuncTy, CallTy > > EdgePtrTy
Summary of memprof metadata on allocations.
std::vector< MIBInfo > MIBs
Class to accumulate and hold information about a callee.
Summary of memprof callsite metadata.
SmallVector< unsigned > StackIdIndices
SmallVector< unsigned > Clones
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
DefaultDOTGraphTraits(bool simple=false)
An information struct used to provide DenseMap with the various necessary components for a given valu...
typename GraphType::UnknownGraphTypeError NodeRef
Struct that holds a reference to a particular GUID in a global value summary.
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
GlobalValue::GUID getGUID() const
PointerUnion< CallsiteInfo *, AllocInfo * > SimpleType
static SimpleType getSimplifiedValue(IndexCall &Val)
const PointerUnion< CallsiteInfo *, AllocInfo * > SimpleType
static SimpleType getSimplifiedValue(const IndexCall &Val)
Define a template that can be specialized by smart pointers to reflect the fact that they are automat...