LLVM 22.0.0git
MemProfContextDisambiguation.cpp
Go to the documentation of this file.
1//==-- MemProfContextDisambiguation.cpp - Disambiguate contexts -------------=//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements support for context disambiguation of allocation
10// calls for profile guided heap optimization. Specifically, it uses Memprof
11// profiles which indicate context specific allocation behavior (currently
12// distinguishing cold vs hot memory allocations). Cloning is performed to
13// expose the cold allocation call contexts, and the allocation calls are
14// subsequently annotated with an attribute for later transformation.
15//
16// The transformations can be performed either directly on IR (regular LTO), or
17// on a ThinLTO index (and later applied to the IR during the ThinLTO backend).
18// Both types of LTO operate on a the same base graph representation, which
19// uses CRTP to support either IR or Index formats.
20//
21//===----------------------------------------------------------------------===//
22
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/MapVector.h"
29#include "llvm/ADT/SmallSet.h"
31#include "llvm/ADT/Statistic.h"
38#include "llvm/IR/Module.h"
40#include "llvm/Pass.h"
44#include "llvm/Support/SHA1.h"
46#include "llvm/Transforms/IPO.h"
50#include <deque>
51#include <sstream>
52#include <unordered_map>
53#include <vector>
54using namespace llvm;
55using namespace llvm::memprof;
56
57#define DEBUG_TYPE "memprof-context-disambiguation"
58
59STATISTIC(FunctionClonesAnalysis,
60 "Number of function clones created during whole program analysis");
61STATISTIC(FunctionClonesThinBackend,
62 "Number of function clones created during ThinLTO backend");
63STATISTIC(FunctionsClonedThinBackend,
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");
72STATISTIC(AllocTypeNotColdThinBackend,
73 "Number of not cold static allocations (possibly cloned) during "
74 "ThinLTO backend");
75STATISTIC(AllocTypeColdThinBackend, "Number of cold static allocations "
76 "(possibly cloned) during ThinLTO backend");
77STATISTIC(OrigAllocsThinBackend,
78 "Number of original (not cloned) allocations with memprof profiles "
79 "during ThinLTO backend");
81 AllocVersionsThinBackend,
82 "Number of allocation versions (including clones) during ThinLTO backend");
83STATISTIC(MaxAllocVersionsThinBackend,
84 "Maximum number of allocation versions created for an original "
85 "allocation during ThinLTO backend");
86STATISTIC(UnclonableAllocsThinBackend,
87 "Number of unclonable ambigous allocations during ThinLTO backend");
88STATISTIC(RemovedEdgesWithMismatchedCallees,
89 "Number of edges removed due to mismatched callees (profiled vs IR)");
90STATISTIC(FoundProfiledCalleeCount,
91 "Number of profiled callees found via tail calls");
92STATISTIC(FoundProfiledCalleeDepth,
93 "Aggregate depth of profiled callees found via tail calls");
94STATISTIC(FoundProfiledCalleeMaxDepth,
95 "Maximum depth of profiled callees found via tail calls");
96STATISTIC(FoundProfiledCalleeNonUniquelyCount,
97 "Number of profiled callees found via multiple tail call chains");
98STATISTIC(DeferredBackedges, "Number of backedges with deferred cloning");
99STATISTIC(NewMergedNodes, "Number of new nodes created during merging");
100STATISTIC(NonNewMergedNodes, "Number of non new nodes used during merging");
101STATISTIC(MissingAllocForContextId,
102 "Number of missing alloc nodes for context ids");
103STATISTIC(SkippedCallsCloning,
104 "Number of calls skipped during cloning due to unexpected operand");
105STATISTIC(MismatchedCloneAssignments,
106 "Number of callsites assigned to call multiple non-matching clones");
107STATISTIC(TotalMergeInvokes, "Number of merge invocations for nodes");
108STATISTIC(TotalMergeIters, "Number of merge iterations for nodes");
109STATISTIC(MaxMergeIters, "Max merge iterations for nodes");
110STATISTIC(NumImportantContextIds, "Number of important context ids");
111STATISTIC(NumFixupEdgeIdsInserted, "Number of fixup edge ids inserted");
112STATISTIC(NumFixupEdgesAdded, "Number of fixup edges added");
113STATISTIC(NumFixedContexts, "Number of contexts with fixed edges");
114
116 "memprof-dot-file-path-prefix", cl::init(""), cl::Hidden,
117 cl::value_desc("filename"),
118 cl::desc("Specify the path prefix of the MemProf dot files."));
119
120static cl::opt<bool> ExportToDot("memprof-export-to-dot", cl::init(false),
122 cl::desc("Export graph to dot files."));
123
124// TODO: Remove this option once new handling is validated more widely.
126 "memprof-merge-iteration", cl::init(true), cl::Hidden,
127 cl::desc("Iteratively apply merging on a node to catch new callers"));
128
129// How much of the graph to export to dot.
131 All, // The full CCG graph.
132 Alloc, // Only contexts for the specified allocation.
133 Context, // Only the specified context.
134};
135
137 "memprof-dot-scope", cl::desc("Scope of graph to export to dot"),
140 clEnumValN(DotScope::All, "all", "Export full callsite graph"),
142 "Export only nodes with contexts feeding given "
143 "-memprof-dot-alloc-id"),
144 clEnumValN(DotScope::Context, "context",
145 "Export only nodes with given -memprof-dot-context-id")));
146
148 AllocIdForDot("memprof-dot-alloc-id", cl::init(0), cl::Hidden,
149 cl::desc("Id of alloc to export if -memprof-dot-scope=alloc "
150 "or to highlight if -memprof-dot-scope=all"));
151
153 "memprof-dot-context-id", cl::init(0), cl::Hidden,
154 cl::desc("Id of context to export if -memprof-dot-scope=context or to "
155 "highlight otherwise"));
156
157static cl::opt<bool>
158 DumpCCG("memprof-dump-ccg", cl::init(false), cl::Hidden,
159 cl::desc("Dump CallingContextGraph to stdout after each stage."));
160
161static cl::opt<bool>
162 VerifyCCG("memprof-verify-ccg", cl::init(false), cl::Hidden,
163 cl::desc("Perform verification checks on CallingContextGraph."));
164
165static cl::opt<bool>
166 VerifyNodes("memprof-verify-nodes", cl::init(false), cl::Hidden,
167 cl::desc("Perform frequent verification checks on nodes."));
168
170 "memprof-import-summary",
171 cl::desc("Import summary to use for testing the ThinLTO backend via opt"),
172 cl::Hidden);
173
175 TailCallSearchDepth("memprof-tail-call-search-depth", cl::init(5),
177 cl::desc("Max depth to recursively search for missing "
178 "frames through tail calls."));
179
180// Optionally enable cloning of callsites involved with recursive cycles
182 "memprof-allow-recursive-callsites", cl::init(true), cl::Hidden,
183 cl::desc("Allow cloning of callsites involved in recursive cycles"));
184
186 "memprof-clone-recursive-contexts", cl::init(true), cl::Hidden,
187 cl::desc("Allow cloning of contexts through recursive cycles"));
188
189// Generally this is needed for correct assignment of allocation clones to
190// function clones, however, allow it to be disabled for debugging while the
191// functionality is new and being tested more widely.
192static cl::opt<bool>
193 MergeClones("memprof-merge-clones", cl::init(true), cl::Hidden,
194 cl::desc("Merge clones before assigning functions"));
195
196// When disabled, try to detect and prevent cloning of recursive contexts.
197// This is only necessary until we support cloning through recursive cycles.
198// Leave on by default for now, as disabling requires a little bit of compile
199// time overhead and doesn't affect correctness, it will just inflate the cold
200// hinted bytes reporting a bit when -memprof-report-hinted-sizes is enabled.
202 "memprof-allow-recursive-contexts", cl::init(true), cl::Hidden,
203 cl::desc("Allow cloning of contexts having recursive cycles"));
204
205// Set the minimum absolute count threshold for allowing inlining of indirect
206// calls promoted during cloning.
208 "memprof-icp-noinline-threshold", cl::init(2), cl::Hidden,
209 cl::desc("Minimum absolute count for promoted target to be inlinable"));
210
211namespace llvm {
213 "enable-memprof-context-disambiguation", cl::init(false), cl::Hidden,
214 cl::ZeroOrMore, cl::desc("Enable MemProf context disambiguation"));
215
216// Indicate we are linking with an allocator that supports hot/cold operator
217// new interfaces.
219 "supports-hot-cold-new", cl::init(false), cl::Hidden,
220 cl::desc("Linking with hot/cold operator new interfaces"));
221
223 "memprof-require-definition-for-promotion", cl::init(false), cl::Hidden,
224 cl::desc(
225 "Require target function definition when promoting indirect calls"));
226
229
231 "memprof-top-n-important", cl::init(10), cl::Hidden,
232 cl::desc("Number of largest cold contexts to consider important"));
233
235 "memprof-fixup-important", cl::init(true), cl::Hidden,
236 cl::desc("Enables edge fixup for important contexts"));
237
239
240} // namespace llvm
241
242namespace {
243
244/// CRTP base for graphs built from either IR or ThinLTO summary index.
245///
246/// The graph represents the call contexts in all memprof metadata on allocation
247/// calls, with nodes for the allocations themselves, as well as for the calls
248/// in each context. The graph is initially built from the allocation memprof
249/// metadata (or summary) MIBs. It is then updated to match calls with callsite
250/// metadata onto the nodes, updating it to reflect any inlining performed on
251/// those calls.
252///
253/// Each MIB (representing an allocation's call context with allocation
254/// behavior) is assigned a unique context id during the graph build. The edges
255/// and nodes in the graph are decorated with the context ids they carry. This
256/// is used to correctly update the graph when cloning is performed so that we
257/// can uniquify the context for a single (possibly cloned) allocation.
258template <typename DerivedCCG, typename FuncTy, typename CallTy>
259class CallsiteContextGraph {
260public:
261 CallsiteContextGraph() = default;
262 CallsiteContextGraph(const CallsiteContextGraph &) = default;
263 CallsiteContextGraph(CallsiteContextGraph &&) = default;
264
265 /// Main entry point to perform analysis and transformations on graph.
266 bool process();
267
268 /// Perform cloning on the graph necessary to uniquely identify the allocation
269 /// behavior of an allocation based on its context.
270 void identifyClones();
271
272 /// Assign callsite clones to functions, cloning functions as needed to
273 /// accommodate the combinations of their callsite clones reached by callers.
274 /// For regular LTO this clones functions and callsites in the IR, but for
275 /// ThinLTO the cloning decisions are noted in the summaries and later applied
276 /// in applyImport.
277 bool assignFunctions();
278
279 void dump() const;
280 void print(raw_ostream &OS) const;
281 void printTotalSizes(raw_ostream &OS) const;
282
284 const CallsiteContextGraph &CCG) {
285 CCG.print(OS);
286 return OS;
287 }
288
289 friend struct GraphTraits<
290 const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *>;
291 friend struct DOTGraphTraits<
292 const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *>;
293
294 void exportToDot(std::string Label) const;
295
296 /// Represents a function clone via FuncTy pointer and clone number pair.
297 struct FuncInfo final
298 : public std::pair<FuncTy *, unsigned /*Clone number*/> {
299 using Base = std::pair<FuncTy *, unsigned>;
300 FuncInfo(const Base &B) : Base(B) {}
301 FuncInfo(FuncTy *F = nullptr, unsigned CloneNo = 0) : Base(F, CloneNo) {}
302 explicit operator bool() const { return this->first != nullptr; }
303 FuncTy *func() const { return this->first; }
304 unsigned cloneNo() const { return this->second; }
305 };
306
307 /// Represents a callsite clone via CallTy and clone number pair.
308 struct CallInfo final : public std::pair<CallTy, unsigned /*Clone number*/> {
309 using Base = std::pair<CallTy, unsigned>;
310 CallInfo(const Base &B) : Base(B) {}
311 CallInfo(CallTy Call = nullptr, unsigned CloneNo = 0)
312 : Base(Call, CloneNo) {}
313 explicit operator bool() const { return (bool)this->first; }
314 CallTy call() const { return this->first; }
315 unsigned cloneNo() const { return this->second; }
316 void setCloneNo(unsigned N) { this->second = N; }
317 void print(raw_ostream &OS) const {
318 if (!operator bool()) {
319 assert(!cloneNo());
320 OS << "null Call";
321 return;
322 }
323 call()->print(OS);
324 OS << "\t(clone " << cloneNo() << ")";
325 }
326 void dump() const {
327 print(dbgs());
328 dbgs() << "\n";
329 }
330 friend raw_ostream &operator<<(raw_ostream &OS, const CallInfo &Call) {
331 Call.print(OS);
332 return OS;
333 }
334 };
335
336 struct ContextEdge;
337
338 /// Node in the Callsite Context Graph
339 struct ContextNode {
340 // Assigned to nodes as they are created, useful for debugging.
341 unsigned NodeId = 0;
342
343 // Keep this for now since in the IR case where we have an Instruction* it
344 // is not as immediately discoverable. Used for printing richer information
345 // when dumping graph.
346 bool IsAllocation;
347
348 // Keeps track of when the Call was reset to null because there was
349 // recursion.
350 bool Recursive = false;
351
352 // This will be formed by ORing together the AllocationType enum values
353 // for contexts including this node.
354 uint8_t AllocTypes = 0;
355
356 // The corresponding allocation or interior call. This is the primary call
357 // for which we have created this node.
358 CallInfo Call;
359
360 // List of other calls that can be treated the same as the primary call
361 // through cloning. I.e. located in the same function and have the same
362 // (possibly pruned) stack ids. They will be updated the same way as the
363 // primary call when assigning to function clones.
364 SmallVector<CallInfo, 0> MatchingCalls;
365
366 // For alloc nodes this is a unique id assigned when constructed, and for
367 // callsite stack nodes it is the original stack id when the node is
368 // constructed from the memprof MIB metadata on the alloc nodes. Note that
369 // this is only used when matching callsite metadata onto the stack nodes
370 // created when processing the allocation memprof MIBs, and for labeling
371 // nodes in the dot graph. Therefore we don't bother to assign a value for
372 // clones.
373 uint64_t OrigStackOrAllocId = 0;
374
375 // Edges to all callees in the profiled call stacks.
376 // TODO: Should this be a map (from Callee node) for more efficient lookup?
377 std::vector<std::shared_ptr<ContextEdge>> CalleeEdges;
378
379 // Edges to all callers in the profiled call stacks.
380 // TODO: Should this be a map (from Caller node) for more efficient lookup?
381 std::vector<std::shared_ptr<ContextEdge>> CallerEdges;
382
383 // Returns true if we need to look at the callee edges for determining the
384 // node context ids and allocation type.
385 bool useCallerEdgesForContextInfo() const {
386 // Typically if the callee edges are empty either the caller edges are
387 // also empty, or this is an allocation (leaf node). However, if we are
388 // allowing recursive callsites and contexts this will be violated for
389 // incompletely cloned recursive cycles.
390 assert(!CalleeEdges.empty() || CallerEdges.empty() || IsAllocation ||
392 // When cloning for a recursive context, during cloning we might be in the
393 // midst of cloning for a recurrence and have moved context ids off of a
394 // caller edge onto the clone but not yet off of the incoming caller
395 // (back) edge. If we don't look at those we miss the fact that this node
396 // still has context ids of interest.
397 return IsAllocation || CloneRecursiveContexts;
398 }
399
400 // Compute the context ids for this node from the union of its edge context
401 // ids.
402 DenseSet<uint32_t> getContextIds() const {
403 unsigned Count = 0;
404 // Compute the number of ids for reserve below. In general we only need to
405 // look at one set of edges, typically the callee edges, since other than
406 // allocations and in some cases during recursion cloning, all the context
407 // ids on the callers should also flow out via callee edges.
408 for (auto &Edge : CalleeEdges.empty() ? CallerEdges : CalleeEdges)
409 Count += Edge->getContextIds().size();
410 DenseSet<uint32_t> ContextIds;
411 ContextIds.reserve(Count);
413 CalleeEdges, useCallerEdgesForContextInfo()
414 ? CallerEdges
415 : std::vector<std::shared_ptr<ContextEdge>>());
416 for (const auto &Edge : Edges)
417 ContextIds.insert_range(Edge->getContextIds());
418 return ContextIds;
419 }
420
421 // Compute the allocation type for this node from the OR of its edge
422 // allocation types.
423 uint8_t computeAllocType() const {
424 uint8_t BothTypes =
428 CalleeEdges, useCallerEdgesForContextInfo()
429 ? CallerEdges
430 : std::vector<std::shared_ptr<ContextEdge>>());
431 for (const auto &Edge : Edges) {
432 AllocType |= Edge->AllocTypes;
433 // Bail early if alloc type reached both, no further refinement.
434 if (AllocType == BothTypes)
435 return AllocType;
436 }
437 return AllocType;
438 }
439
440 // The context ids set for this node is empty if its edge context ids are
441 // also all empty.
442 bool emptyContextIds() const {
444 CalleeEdges, useCallerEdgesForContextInfo()
445 ? CallerEdges
446 : std::vector<std::shared_ptr<ContextEdge>>());
447 for (const auto &Edge : Edges) {
448 if (!Edge->getContextIds().empty())
449 return false;
450 }
451 return true;
452 }
453
454 // List of clones of this ContextNode, initially empty.
455 std::vector<ContextNode *> Clones;
456
457 // If a clone, points to the original uncloned node.
458 ContextNode *CloneOf = nullptr;
459
460 ContextNode(bool IsAllocation) : IsAllocation(IsAllocation), Call() {}
461
462 ContextNode(bool IsAllocation, CallInfo C)
463 : IsAllocation(IsAllocation), Call(C) {}
464
465 void addClone(ContextNode *Clone) {
466 if (CloneOf) {
467 CloneOf->Clones.push_back(Clone);
468 Clone->CloneOf = CloneOf;
469 } else {
470 Clones.push_back(Clone);
471 assert(!Clone->CloneOf);
472 Clone->CloneOf = this;
473 }
474 }
475
476 ContextNode *getOrigNode() {
477 if (!CloneOf)
478 return this;
479 return CloneOf;
480 }
481
482 void addOrUpdateCallerEdge(ContextNode *Caller, AllocationType AllocType,
483 unsigned int ContextId);
484
485 ContextEdge *findEdgeFromCallee(const ContextNode *Callee);
486 ContextEdge *findEdgeFromCaller(const ContextNode *Caller);
487 void eraseCalleeEdge(const ContextEdge *Edge);
488 void eraseCallerEdge(const ContextEdge *Edge);
489
490 void setCall(CallInfo C) { Call = C; }
491
492 bool hasCall() const { return (bool)Call.call(); }
493
494 void printCall(raw_ostream &OS) const { Call.print(OS); }
495
496 // True if this node was effectively removed from the graph, in which case
497 // it should have an allocation type of None and empty context ids.
498 bool isRemoved() const {
499 // Typically if the callee edges are empty either the caller edges are
500 // also empty, or this is an allocation (leaf node). However, if we are
501 // allowing recursive callsites and contexts this will be violated for
502 // incompletely cloned recursive cycles.
504 (AllocTypes == (uint8_t)AllocationType::None) ==
505 emptyContextIds());
506 return AllocTypes == (uint8_t)AllocationType::None;
507 }
508
509 void dump() const;
510 void print(raw_ostream &OS) const;
511
512 friend raw_ostream &operator<<(raw_ostream &OS, const ContextNode &Node) {
513 Node.print(OS);
514 return OS;
515 }
516 };
517
518 /// Edge in the Callsite Context Graph from a ContextNode N to a caller or
519 /// callee.
520 struct ContextEdge {
521 ContextNode *Callee;
522 ContextNode *Caller;
523
524 // This will be formed by ORing together the AllocationType enum values
525 // for contexts including this edge.
526 uint8_t AllocTypes = 0;
527
528 // Set just before initiating cloning when cloning of recursive contexts is
529 // enabled. Used to defer cloning of backedges until we have done cloning of
530 // the callee node for non-backedge caller edges. This exposes cloning
531 // opportunities through the backedge of the cycle.
532 // TODO: Note that this is not updated during cloning, and it is unclear
533 // whether that would be needed.
534 bool IsBackedge = false;
535
536 // The set of IDs for contexts including this edge.
537 DenseSet<uint32_t> ContextIds;
538
539 ContextEdge(ContextNode *Callee, ContextNode *Caller, uint8_t AllocType,
540 DenseSet<uint32_t> ContextIds)
541 : Callee(Callee), Caller(Caller), AllocTypes(AllocType),
542 ContextIds(std::move(ContextIds)) {}
543
544 DenseSet<uint32_t> &getContextIds() { return ContextIds; }
545
546 // Helper to clear the fields of this edge when we are removing it from the
547 // graph.
548 inline void clear() {
549 ContextIds.clear();
550 AllocTypes = (uint8_t)AllocationType::None;
551 Caller = nullptr;
552 Callee = nullptr;
553 }
554
555 // Check if edge was removed from the graph. This is useful while iterating
556 // over a copy of edge lists when performing operations that mutate the
557 // graph in ways that might remove one of the edges.
558 inline bool isRemoved() const {
559 if (Callee || Caller)
560 return false;
561 // Any edges that have been removed from the graph but are still in a
562 // shared_ptr somewhere should have all fields null'ed out by clear()
563 // above.
564 assert(AllocTypes == (uint8_t)AllocationType::None);
565 assert(ContextIds.empty());
566 return true;
567 }
568
569 void dump() const;
570 void print(raw_ostream &OS) const;
571
572 friend raw_ostream &operator<<(raw_ostream &OS, const ContextEdge &Edge) {
573 Edge.print(OS);
574 return OS;
575 }
576 };
577
578 /// Helpers to remove edges that have allocation type None (due to not
579 /// carrying any context ids) after transformations.
580 void removeNoneTypeCalleeEdges(ContextNode *Node);
581 void removeNoneTypeCallerEdges(ContextNode *Node);
582 void
583 recursivelyRemoveNoneTypeCalleeEdges(ContextNode *Node,
585
586protected:
587 /// Get a list of nodes corresponding to the stack ids in the given callsite
588 /// context.
589 template <class NodeT, class IteratorT>
590 std::vector<uint64_t>
591 getStackIdsWithContextNodes(CallStack<NodeT, IteratorT> &CallsiteContext);
592
593 /// Adds nodes for the given allocation and any stack ids on its memprof MIB
594 /// metadata (or summary).
595 ContextNode *addAllocNode(CallInfo Call, const FuncTy *F);
596
597 /// Adds nodes for the given MIB stack ids.
598 template <class NodeT, class IteratorT>
599 void addStackNodesForMIB(
600 ContextNode *AllocNode, CallStack<NodeT, IteratorT> &StackContext,
602 ArrayRef<ContextTotalSize> ContextSizeInfo,
603 std::map<uint64_t, uint32_t> &TotalSizeToContextIdTopNCold);
604
605 /// Matches all callsite metadata (or summary) to the nodes created for
606 /// allocation memprof MIB metadata, synthesizing new nodes to reflect any
607 /// inlining performed on those callsite instructions.
608 void updateStackNodes();
609
610 /// Optionally fixup edges for the N largest cold contexts to better enable
611 /// cloning. This is particularly helpful if the context includes recursion
612 /// as well as inlining, resulting in a single stack node for multiple stack
613 /// ids in the context. With recursion it is particularly difficult to get the
614 /// edge updates correct as in the general case we have lost the original
615 /// stack id ordering for the context. Do more expensive fixup for the largest
616 /// contexts, controlled by MemProfTopNImportant and MemProfFixupImportant.
617 void fixupImportantContexts();
618
619 /// Update graph to conservatively handle any callsite stack nodes that target
620 /// multiple different callee target functions.
621 void handleCallsitesWithMultipleTargets();
622
623 /// Mark backedges via the standard DFS based backedge algorithm.
624 void markBackedges();
625
626 /// Merge clones generated during cloning for different allocations but that
627 /// are called by the same caller node, to ensure proper function assignment.
628 void mergeClones();
629
630 // Try to partition calls on the given node (already placed into the AllCalls
631 // array) by callee function, creating new copies of Node as needed to hold
632 // calls with different callees, and moving the callee edges appropriately.
633 // Returns true if partitioning was successful.
634 bool partitionCallsByCallee(
635 ContextNode *Node, ArrayRef<CallInfo> AllCalls,
636 std::vector<std::pair<CallInfo, ContextNode *>> &NewCallToNode);
637
638 /// Save lists of calls with MemProf metadata in each function, for faster
639 /// iteration.
640 MapVector<FuncTy *, std::vector<CallInfo>> FuncToCallsWithMetadata;
641
642 /// Map from callsite node to the enclosing caller function.
643 std::map<const ContextNode *, const FuncTy *> NodeToCallingFunc;
644
645 // When exporting to dot, and an allocation id is specified, contains the
646 // context ids on that allocation.
647 DenseSet<uint32_t> DotAllocContextIds;
648
649private:
650 using EdgeIter = typename std::vector<std::shared_ptr<ContextEdge>>::iterator;
651
652 // Structure to keep track of information for each call as we are matching
653 // non-allocation callsites onto context nodes created from the allocation
654 // call metadata / summary contexts.
655 struct CallContextInfo {
656 // The callsite we're trying to match.
657 CallTy Call;
658 // The callsites stack ids that have a context node in the graph.
659 std::vector<uint64_t> StackIds;
660 // The function containing this callsite.
661 const FuncTy *Func;
662 // Initially empty, if needed this will be updated to contain the context
663 // ids for use in a new context node created for this callsite.
664 DenseSet<uint32_t> ContextIds;
665 };
666
667 /// Helper to remove edge from graph, updating edge iterator if it is provided
668 /// (in which case CalleeIter indicates which edge list is being iterated).
669 /// This will also perform the necessary clearing of the ContextEdge members
670 /// to enable later checking if the edge has been removed (since we may have
671 /// other copies of the shared_ptr in existence, and in fact rely on this to
672 /// enable removal while iterating over a copy of a node's edge list).
673 void removeEdgeFromGraph(ContextEdge *Edge, EdgeIter *EI = nullptr,
674 bool CalleeIter = true);
675
676 /// Assigns the given Node to calls at or inlined into the location with
677 /// the Node's stack id, after post order traversing and processing its
678 /// caller nodes. Uses the call information recorded in the given
679 /// StackIdToMatchingCalls map, and creates new nodes for inlined sequences
680 /// as needed. Called by updateStackNodes which sets up the given
681 /// StackIdToMatchingCalls map.
682 void assignStackNodesPostOrder(
683 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
684 DenseMap<uint64_t, std::vector<CallContextInfo>> &StackIdToMatchingCalls,
685 DenseMap<CallInfo, CallInfo> &CallToMatchingCall,
686 const DenseSet<uint32_t> &ImportantContextIds);
687
688 /// Duplicates the given set of context ids, updating the provided
689 /// map from each original id with the newly generated context ids,
690 /// and returning the new duplicated id set.
691 DenseSet<uint32_t> duplicateContextIds(
692 const DenseSet<uint32_t> &StackSequenceContextIds,
693 DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds);
694
695 /// Propagates all duplicated context ids across the graph.
696 void propagateDuplicateContextIds(
697 const DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds);
698
699 /// Connect the NewNode to OrigNode's callees if TowardsCallee is true,
700 /// else to its callers. Also updates OrigNode's edges to remove any context
701 /// ids moved to the newly created edge.
702 void connectNewNode(ContextNode *NewNode, ContextNode *OrigNode,
703 bool TowardsCallee,
704 DenseSet<uint32_t> RemainingContextIds);
705
706 /// Get the stack id corresponding to the given Id or Index (for IR this will
707 /// return itself, for a summary index this will return the id recorded in the
708 /// index for that stack id index value).
709 uint64_t getStackId(uint64_t IdOrIndex) const {
710 return static_cast<const DerivedCCG *>(this)->getStackId(IdOrIndex);
711 }
712
713 /// Returns true if the given call targets the callee of the given edge, or if
714 /// we were able to identify the call chain through intermediate tail calls.
715 /// In the latter case new context nodes are added to the graph for the
716 /// identified tail calls, and their synthesized nodes are added to
717 /// TailCallToContextNodeMap. The EdgeIter is updated in the latter case for
718 /// the updated edges and to prepare it for an increment in the caller.
719 bool
720 calleesMatch(CallTy Call, EdgeIter &EI,
721 MapVector<CallInfo, ContextNode *> &TailCallToContextNodeMap);
722
723 // Return the callee function of the given call, or nullptr if it can't be
724 // determined
725 const FuncTy *getCalleeFunc(CallTy Call) {
726 return static_cast<DerivedCCG *>(this)->getCalleeFunc(Call);
727 }
728
729 /// Returns true if the given call targets the given function, or if we were
730 /// able to identify the call chain through intermediate tail calls (in which
731 /// case FoundCalleeChain will be populated).
732 bool calleeMatchesFunc(
733 CallTy Call, const FuncTy *Func, const FuncTy *CallerFunc,
734 std::vector<std::pair<CallTy, FuncTy *>> &FoundCalleeChain) {
735 return static_cast<DerivedCCG *>(this)->calleeMatchesFunc(
736 Call, Func, CallerFunc, FoundCalleeChain);
737 }
738
739 /// Returns true if both call instructions have the same callee.
740 bool sameCallee(CallTy Call1, CallTy Call2) {
741 return static_cast<DerivedCCG *>(this)->sameCallee(Call1, Call2);
742 }
743
744 /// Get a list of nodes corresponding to the stack ids in the given
745 /// callsite's context.
746 std::vector<uint64_t> getStackIdsWithContextNodesForCall(CallTy Call) {
747 return static_cast<DerivedCCG *>(this)->getStackIdsWithContextNodesForCall(
748 Call);
749 }
750
751 /// Get the last stack id in the context for callsite.
752 uint64_t getLastStackId(CallTy Call) {
753 return static_cast<DerivedCCG *>(this)->getLastStackId(Call);
754 }
755
756 /// Update the allocation call to record type of allocated memory.
757 void updateAllocationCall(CallInfo &Call, AllocationType AllocType) {
758 AllocType == AllocationType::Cold ? AllocTypeCold++ : AllocTypeNotCold++;
759 static_cast<DerivedCCG *>(this)->updateAllocationCall(Call, AllocType);
760 }
761
762 /// Get the AllocationType assigned to the given allocation instruction clone.
763 AllocationType getAllocationCallType(const CallInfo &Call) const {
764 return static_cast<const DerivedCCG *>(this)->getAllocationCallType(Call);
765 }
766
767 /// Update non-allocation call to invoke (possibly cloned) function
768 /// CalleeFunc.
769 void updateCall(CallInfo &CallerCall, FuncInfo CalleeFunc) {
770 static_cast<DerivedCCG *>(this)->updateCall(CallerCall, CalleeFunc);
771 }
772
773 /// Clone the given function for the given callsite, recording mapping of all
774 /// of the functions tracked calls to their new versions in the CallMap.
775 /// Assigns new clones to clone number CloneNo.
776 FuncInfo cloneFunctionForCallsite(
777 FuncInfo &Func, CallInfo &Call, DenseMap<CallInfo, CallInfo> &CallMap,
778 std::vector<CallInfo> &CallsWithMetadataInFunc, unsigned CloneNo) {
779 return static_cast<DerivedCCG *>(this)->cloneFunctionForCallsite(
780 Func, Call, CallMap, CallsWithMetadataInFunc, CloneNo);
781 }
782
783 /// Gets a label to use in the dot graph for the given call clone in the given
784 /// function.
785 std::string getLabel(const FuncTy *Func, const CallTy Call,
786 unsigned CloneNo) const {
787 return static_cast<const DerivedCCG *>(this)->getLabel(Func, Call, CloneNo);
788 }
789
790 // Create and return a new ContextNode.
791 ContextNode *createNewNode(bool IsAllocation, const FuncTy *F = nullptr,
792 CallInfo C = CallInfo()) {
793 NodeOwner.push_back(std::make_unique<ContextNode>(IsAllocation, C));
794 auto *NewNode = NodeOwner.back().get();
795 if (F)
796 NodeToCallingFunc[NewNode] = F;
797 NewNode->NodeId = NodeOwner.size();
798 return NewNode;
799 }
800
801 /// Helpers to find the node corresponding to the given call or stackid.
802 ContextNode *getNodeForInst(const CallInfo &C);
803 ContextNode *getNodeForAlloc(const CallInfo &C);
804 ContextNode *getNodeForStackId(uint64_t StackId);
805
806 /// Computes the alloc type corresponding to the given context ids, by
807 /// unioning their recorded alloc types.
808 uint8_t computeAllocType(DenseSet<uint32_t> &ContextIds) const;
809
810 /// Returns the allocation type of the intersection of the contexts of two
811 /// nodes (based on their provided context id sets), optimized for the case
812 /// when Node1Ids is smaller than Node2Ids.
813 uint8_t intersectAllocTypesImpl(const DenseSet<uint32_t> &Node1Ids,
814 const DenseSet<uint32_t> &Node2Ids) const;
815
816 /// Returns the allocation type of the intersection of the contexts of two
817 /// nodes (based on their provided context id sets).
818 uint8_t intersectAllocTypes(const DenseSet<uint32_t> &Node1Ids,
819 const DenseSet<uint32_t> &Node2Ids) const;
820
821 /// Create a clone of Edge's callee and move Edge to that new callee node,
822 /// performing the necessary context id and allocation type updates.
823 /// If ContextIdsToMove is non-empty, only that subset of Edge's ids are
824 /// moved to an edge to the new callee.
825 ContextNode *
826 moveEdgeToNewCalleeClone(const std::shared_ptr<ContextEdge> &Edge,
827 DenseSet<uint32_t> ContextIdsToMove = {});
828
829 /// Change the callee of Edge to existing callee clone NewCallee, performing
830 /// the necessary context id and allocation type updates.
831 /// If ContextIdsToMove is non-empty, only that subset of Edge's ids are
832 /// moved to an edge to the new callee.
833 void moveEdgeToExistingCalleeClone(const std::shared_ptr<ContextEdge> &Edge,
834 ContextNode *NewCallee,
835 bool NewClone = false,
836 DenseSet<uint32_t> ContextIdsToMove = {});
837
838 /// Change the caller of the edge at the given callee edge iterator to be
839 /// NewCaller, performing the necessary context id and allocation type
840 /// updates. This is similar to the above moveEdgeToExistingCalleeClone, but
841 /// a simplified version of it as we always move the given edge and all of its
842 /// context ids.
843 void moveCalleeEdgeToNewCaller(const std::shared_ptr<ContextEdge> &Edge,
844 ContextNode *NewCaller);
845
846 /// Recursive helper for marking backedges via DFS.
847 void markBackedges(ContextNode *Node, DenseSet<const ContextNode *> &Visited,
848 DenseSet<const ContextNode *> &CurrentStack);
849
850 /// Recursive helper for merging clones.
851 void
852 mergeClones(ContextNode *Node, DenseSet<const ContextNode *> &Visited,
853 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode);
854 /// Main worker for merging callee clones for a given node.
855 void mergeNodeCalleeClones(
856 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
857 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode);
858 /// Helper to find other callers of the given set of callee edges that can
859 /// share the same callee merge node.
860 void findOtherCallersToShareMerge(
861 ContextNode *Node, std::vector<std::shared_ptr<ContextEdge>> &CalleeEdges,
862 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode,
863 DenseSet<ContextNode *> &OtherCallersToShareMerge);
864
865 /// Recursively perform cloning on the graph for the given Node and its
866 /// callers, in order to uniquely identify the allocation behavior of an
867 /// allocation given its context. The context ids of the allocation being
868 /// processed are given in AllocContextIds.
869 void identifyClones(ContextNode *Node, DenseSet<const ContextNode *> &Visited,
870 const DenseSet<uint32_t> &AllocContextIds);
871
872 /// Map from each context ID to the AllocationType assigned to that context.
873 DenseMap<uint32_t, AllocationType> ContextIdToAllocationType;
874
875 /// Map from each contextID to the profiled full contexts and their total
876 /// sizes (there may be more than one due to context trimming),
877 /// optionally populated when requested (via MemProfReportHintedSizes or
878 /// MinClonedColdBytePercent).
879 DenseMap<uint32_t, std::vector<ContextTotalSize>> ContextIdToContextSizeInfos;
880
881 /// Identifies the context node created for a stack id when adding the MIB
882 /// contexts to the graph. This is used to locate the context nodes when
883 /// trying to assign the corresponding callsites with those stack ids to these
884 /// nodes.
885 DenseMap<uint64_t, ContextNode *> StackEntryIdToContextNodeMap;
886
887 /// Saves information for the contexts identified as important (the largest
888 /// cold contexts up to MemProfTopNImportant).
889 struct ImportantContextInfo {
890 // The original list of leaf first stack ids corresponding to this context.
891 std::vector<uint64_t> StackIds;
892 // Max length of stack ids corresponding to a single stack ContextNode for
893 // this context (i.e. the max length of a key in StackIdsToNode below).
894 unsigned MaxLength = 0;
895 // Mapping of slices of the stack ids to the corresponding ContextNode
896 // (there can be multiple stack ids due to inlining). Populated when
897 // updating stack nodes while matching them to the IR or summary.
898 std::map<std::vector<uint64_t>, ContextNode *> StackIdsToNode;
899 };
900
901 // Map of important full context ids to information about each.
902 DenseMap<uint32_t, ImportantContextInfo> ImportantContextIdInfo;
903
904 // For each important context id found in Node (if any), records the list of
905 // stack ids that corresponded to the given callsite Node. There can be more
906 // than one in the case of inlining.
907 void recordStackNode(std::vector<uint64_t> &StackIds, ContextNode *Node,
908 // We pass in the Node's context ids to avoid the
909 // overhead of computing them as the caller already has
910 // them in some cases.
911 const DenseSet<uint32_t> &NodeContextIds,
912 const DenseSet<uint32_t> &ImportantContextIds) {
914 assert(ImportantContextIds.empty());
915 return;
916 }
918 set_intersection(NodeContextIds, ImportantContextIds);
919 if (Ids.empty())
920 return;
921 auto Size = StackIds.size();
922 for (auto Id : Ids) {
923 auto &Entry = ImportantContextIdInfo[Id];
924 Entry.StackIdsToNode[StackIds] = Node;
925 // Keep track of the max to simplify later analysis.
926 if (Size > Entry.MaxLength)
927 Entry.MaxLength = Size;
928 }
929 }
930
931 /// Maps to track the calls to their corresponding nodes in the graph.
932 MapVector<CallInfo, ContextNode *> AllocationCallToContextNodeMap;
933 MapVector<CallInfo, ContextNode *> NonAllocationCallToContextNodeMap;
934
935 /// Owner of all ContextNode unique_ptrs.
936 std::vector<std::unique_ptr<ContextNode>> NodeOwner;
937
938 /// Perform sanity checks on graph when requested.
939 void check() const;
940
941 /// Keeps track of the last unique context id assigned.
942 unsigned int LastContextId = 0;
943};
944
945template <typename DerivedCCG, typename FuncTy, typename CallTy>
946using ContextNode =
947 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode;
948template <typename DerivedCCG, typename FuncTy, typename CallTy>
949using ContextEdge =
950 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge;
951template <typename DerivedCCG, typename FuncTy, typename CallTy>
952using FuncInfo =
953 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::FuncInfo;
954template <typename DerivedCCG, typename FuncTy, typename CallTy>
955using CallInfo =
956 typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::CallInfo;
957
958/// CRTP derived class for graphs built from IR (regular LTO).
959class ModuleCallsiteContextGraph
960 : public CallsiteContextGraph<ModuleCallsiteContextGraph, Function,
961 Instruction *> {
962public:
963 ModuleCallsiteContextGraph(
964 Module &M,
965 llvm::function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter);
966
967private:
968 friend CallsiteContextGraph<ModuleCallsiteContextGraph, Function,
969 Instruction *>;
970
971 uint64_t getStackId(uint64_t IdOrIndex) const;
972 const Function *getCalleeFunc(Instruction *Call);
973 bool calleeMatchesFunc(
974 Instruction *Call, const Function *Func, const Function *CallerFunc,
975 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain);
976 bool sameCallee(Instruction *Call1, Instruction *Call2);
977 bool findProfiledCalleeThroughTailCalls(
978 const Function *ProfiledCallee, Value *CurCallee, unsigned Depth,
979 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain,
980 bool &FoundMultipleCalleeChains);
981 uint64_t getLastStackId(Instruction *Call);
982 std::vector<uint64_t> getStackIdsWithContextNodesForCall(Instruction *Call);
983 void updateAllocationCall(CallInfo &Call, AllocationType AllocType);
984 AllocationType getAllocationCallType(const CallInfo &Call) const;
985 void updateCall(CallInfo &CallerCall, FuncInfo CalleeFunc);
986 CallsiteContextGraph<ModuleCallsiteContextGraph, Function,
987 Instruction *>::FuncInfo
988 cloneFunctionForCallsite(FuncInfo &Func, CallInfo &Call,
989 DenseMap<CallInfo, CallInfo> &CallMap,
990 std::vector<CallInfo> &CallsWithMetadataInFunc,
991 unsigned CloneNo);
992 std::string getLabel(const Function *Func, const Instruction *Call,
993 unsigned CloneNo) const;
994
995 const Module &Mod;
996 llvm::function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter;
997};
998
999/// Represents a call in the summary index graph, which can either be an
1000/// allocation or an interior callsite node in an allocation's context.
1001/// Holds a pointer to the corresponding data structure in the index.
1002struct IndexCall : public PointerUnion<CallsiteInfo *, AllocInfo *> {
1003 IndexCall() : PointerUnion() {}
1004 IndexCall(std::nullptr_t) : IndexCall() {}
1005 IndexCall(CallsiteInfo *StackNode) : PointerUnion(StackNode) {}
1006 IndexCall(AllocInfo *AllocNode) : PointerUnion(AllocNode) {}
1007 IndexCall(PointerUnion PT) : PointerUnion(PT) {}
1008
1009 IndexCall *operator->() { return this; }
1010
1011 void print(raw_ostream &OS) const {
1012 PointerUnion<CallsiteInfo *, AllocInfo *> Base = *this;
1014 OS << *AI;
1015 } else {
1017 assert(CI);
1018 OS << *CI;
1019 }
1020 }
1021};
1022} // namespace
1023
1024namespace llvm {
1025template <> struct simplify_type<IndexCall> {
1027 static SimpleType getSimplifiedValue(IndexCall &Val) { return Val; }
1028};
1029template <> struct simplify_type<const IndexCall> {
1031 static SimpleType getSimplifiedValue(const IndexCall &Val) { return Val; }
1032};
1033} // namespace llvm
1034
1035namespace {
1036/// CRTP derived class for graphs built from summary index (ThinLTO).
1037class IndexCallsiteContextGraph
1038 : public CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
1039 IndexCall> {
1040public:
1041 IndexCallsiteContextGraph(
1042 ModuleSummaryIndex &Index,
1043 llvm::function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
1044 isPrevailing);
1045
1046 ~IndexCallsiteContextGraph() {
1047 // Now that we are done with the graph it is safe to add the new
1048 // CallsiteInfo structs to the function summary vectors. The graph nodes
1049 // point into locations within these vectors, so we don't want to add them
1050 // any earlier.
1051 for (auto &I : FunctionCalleesToSynthesizedCallsiteInfos) {
1052 auto *FS = I.first;
1053 for (auto &Callsite : I.second)
1054 FS->addCallsite(*Callsite.second);
1055 }
1056 }
1057
1058private:
1059 friend CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
1060 IndexCall>;
1061
1062 uint64_t getStackId(uint64_t IdOrIndex) const;
1063 const FunctionSummary *getCalleeFunc(IndexCall &Call);
1064 bool calleeMatchesFunc(
1065 IndexCall &Call, const FunctionSummary *Func,
1066 const FunctionSummary *CallerFunc,
1067 std::vector<std::pair<IndexCall, FunctionSummary *>> &FoundCalleeChain);
1068 bool sameCallee(IndexCall &Call1, IndexCall &Call2);
1069 bool findProfiledCalleeThroughTailCalls(
1070 ValueInfo ProfiledCallee, ValueInfo CurCallee, unsigned Depth,
1071 std::vector<std::pair<IndexCall, FunctionSummary *>> &FoundCalleeChain,
1072 bool &FoundMultipleCalleeChains);
1073 uint64_t getLastStackId(IndexCall &Call);
1074 std::vector<uint64_t> getStackIdsWithContextNodesForCall(IndexCall &Call);
1075 void updateAllocationCall(CallInfo &Call, AllocationType AllocType);
1076 AllocationType getAllocationCallType(const CallInfo &Call) const;
1077 void updateCall(CallInfo &CallerCall, FuncInfo CalleeFunc);
1078 CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
1079 IndexCall>::FuncInfo
1080 cloneFunctionForCallsite(FuncInfo &Func, CallInfo &Call,
1081 DenseMap<CallInfo, CallInfo> &CallMap,
1082 std::vector<CallInfo> &CallsWithMetadataInFunc,
1083 unsigned CloneNo);
1084 std::string getLabel(const FunctionSummary *Func, const IndexCall &Call,
1085 unsigned CloneNo) const;
1086
1087 // Saves mapping from function summaries containing memprof records back to
1088 // its VI, for use in checking and debugging.
1089 std::map<const FunctionSummary *, ValueInfo> FSToVIMap;
1090
1091 const ModuleSummaryIndex &Index;
1092 llvm::function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
1093 isPrevailing;
1094
1095 // Saves/owns the callsite info structures synthesized for missing tail call
1096 // frames that we discover while building the graph.
1097 // It maps from the summary of the function making the tail call, to a map
1098 // of callee ValueInfo to corresponding synthesized callsite info.
1099 std::unordered_map<FunctionSummary *,
1100 std::map<ValueInfo, std::unique_ptr<CallsiteInfo>>>
1101 FunctionCalleesToSynthesizedCallsiteInfos;
1102};
1103} // namespace
1104
1105template <>
1106struct llvm::DenseMapInfo<CallsiteContextGraph<
1107 ModuleCallsiteContextGraph, Function, Instruction *>::CallInfo>
1109template <>
1110struct llvm::DenseMapInfo<CallsiteContextGraph<
1111 IndexCallsiteContextGraph, FunctionSummary, IndexCall>::CallInfo>
1112 : public DenseMapInfo<std::pair<IndexCall, unsigned>> {};
1113template <>
1114struct llvm::DenseMapInfo<IndexCall>
1115 : public DenseMapInfo<PointerUnion<CallsiteInfo *, AllocInfo *>> {};
1116
1117namespace {
1118
1119// Map the uint8_t alloc types (which may contain NotCold|Cold) to the alloc
1120// type we should actually use on the corresponding allocation.
1121// If we can't clone a node that has NotCold+Cold alloc type, we will fall
1122// back to using NotCold. So don't bother cloning to distinguish NotCold+Cold
1123// from NotCold.
1124AllocationType allocTypeToUse(uint8_t AllocTypes) {
1125 assert(AllocTypes != (uint8_t)AllocationType::None);
1126 if (AllocTypes ==
1129 else
1130 return (AllocationType)AllocTypes;
1131}
1132
1133// Helper to check if the alloc types for all edges recorded in the
1134// InAllocTypes vector match the alloc types for all edges in the Edges
1135// vector.
1136template <typename DerivedCCG, typename FuncTy, typename CallTy>
1137bool allocTypesMatch(
1138 const std::vector<uint8_t> &InAllocTypes,
1139 const std::vector<std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>>>
1140 &Edges) {
1141 // This should be called only when the InAllocTypes vector was computed for
1142 // this set of Edges. Make sure the sizes are the same.
1143 assert(InAllocTypes.size() == Edges.size());
1144 return std::equal(
1145 InAllocTypes.begin(), InAllocTypes.end(), Edges.begin(), Edges.end(),
1146 [](const uint8_t &l,
1147 const std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>> &r) {
1148 // Can share if one of the edges is None type - don't
1149 // care about the type along that edge as it doesn't
1150 // exist for those context ids.
1151 if (l == (uint8_t)AllocationType::None ||
1152 r->AllocTypes == (uint8_t)AllocationType::None)
1153 return true;
1154 return allocTypeToUse(l) == allocTypeToUse(r->AllocTypes);
1155 });
1156}
1157
1158// Helper to check if the alloc types for all edges recorded in the
1159// InAllocTypes vector match the alloc types for callee edges in the given
1160// clone. Because the InAllocTypes were computed from the original node's callee
1161// edges, and other cloning could have happened after this clone was created, we
1162// need to find the matching clone callee edge, which may or may not exist.
1163template <typename DerivedCCG, typename FuncTy, typename CallTy>
1164bool allocTypesMatchClone(
1165 const std::vector<uint8_t> &InAllocTypes,
1166 const ContextNode<DerivedCCG, FuncTy, CallTy> *Clone) {
1167 const ContextNode<DerivedCCG, FuncTy, CallTy> *Node = Clone->CloneOf;
1168 assert(Node);
1169 // InAllocTypes should have been computed for the original node's callee
1170 // edges.
1171 assert(InAllocTypes.size() == Node->CalleeEdges.size());
1172 // First create a map of the clone callee edge callees to the edge alloc type.
1174 EdgeCalleeMap;
1175 for (const auto &E : Clone->CalleeEdges) {
1176 assert(!EdgeCalleeMap.contains(E->Callee));
1177 EdgeCalleeMap[E->Callee] = E->AllocTypes;
1178 }
1179 // Next, walk the original node's callees, and look for the corresponding
1180 // clone edge to that callee.
1181 for (unsigned I = 0; I < Node->CalleeEdges.size(); I++) {
1182 auto Iter = EdgeCalleeMap.find(Node->CalleeEdges[I]->Callee);
1183 // Not found is ok, we will simply add an edge if we use this clone.
1184 if (Iter == EdgeCalleeMap.end())
1185 continue;
1186 // Can share if one of the edges is None type - don't
1187 // care about the type along that edge as it doesn't
1188 // exist for those context ids.
1189 if (InAllocTypes[I] == (uint8_t)AllocationType::None ||
1190 Iter->second == (uint8_t)AllocationType::None)
1191 continue;
1192 if (allocTypeToUse(Iter->second) != allocTypeToUse(InAllocTypes[I]))
1193 return false;
1194 }
1195 return true;
1196}
1197
1198} // end anonymous namespace
1199
1200template <typename DerivedCCG, typename FuncTy, typename CallTy>
1201typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1202CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getNodeForInst(
1203 const CallInfo &C) {
1204 ContextNode *Node = getNodeForAlloc(C);
1205 if (Node)
1206 return Node;
1207
1208 return NonAllocationCallToContextNodeMap.lookup(C);
1209}
1210
1211template <typename DerivedCCG, typename FuncTy, typename CallTy>
1212typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1213CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getNodeForAlloc(
1214 const CallInfo &C) {
1215 return AllocationCallToContextNodeMap.lookup(C);
1216}
1217
1218template <typename DerivedCCG, typename FuncTy, typename CallTy>
1219typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1220CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getNodeForStackId(
1221 uint64_t StackId) {
1222 auto StackEntryNode = StackEntryIdToContextNodeMap.find(StackId);
1223 if (StackEntryNode != StackEntryIdToContextNodeMap.end())
1224 return StackEntryNode->second;
1225 return nullptr;
1226}
1227
1228template <typename DerivedCCG, typename FuncTy, typename CallTy>
1229void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1230 addOrUpdateCallerEdge(ContextNode *Caller, AllocationType AllocType,
1231 unsigned int ContextId) {
1232 for (auto &Edge : CallerEdges) {
1233 if (Edge->Caller == Caller) {
1234 Edge->AllocTypes |= (uint8_t)AllocType;
1235 Edge->getContextIds().insert(ContextId);
1236 return;
1237 }
1238 }
1239 std::shared_ptr<ContextEdge> Edge = std::make_shared<ContextEdge>(
1240 this, Caller, (uint8_t)AllocType, DenseSet<uint32_t>({ContextId}));
1241 CallerEdges.push_back(Edge);
1242 Caller->CalleeEdges.push_back(Edge);
1243}
1244
1245template <typename DerivedCCG, typename FuncTy, typename CallTy>
1246void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::removeEdgeFromGraph(
1247 ContextEdge *Edge, EdgeIter *EI, bool CalleeIter) {
1248 assert(!EI || (*EI)->get() == Edge);
1249 assert(!Edge->isRemoved());
1250 // Save the Caller and Callee pointers so we can erase Edge from their edge
1251 // lists after clearing Edge below. We do the clearing first in case it is
1252 // destructed after removing from the edge lists (if those were the last
1253 // shared_ptr references to Edge).
1254 auto *Callee = Edge->Callee;
1255 auto *Caller = Edge->Caller;
1256
1257 // Make sure the edge fields are cleared out so we can properly detect
1258 // removed edges if Edge is not destructed because there is still a shared_ptr
1259 // reference.
1260 Edge->clear();
1261
1262#ifndef NDEBUG
1263 auto CalleeCallerCount = Callee->CallerEdges.size();
1264 auto CallerCalleeCount = Caller->CalleeEdges.size();
1265#endif
1266 if (!EI) {
1267 Callee->eraseCallerEdge(Edge);
1268 Caller->eraseCalleeEdge(Edge);
1269 } else if (CalleeIter) {
1270 Callee->eraseCallerEdge(Edge);
1271 *EI = Caller->CalleeEdges.erase(*EI);
1272 } else {
1273 Caller->eraseCalleeEdge(Edge);
1274 *EI = Callee->CallerEdges.erase(*EI);
1275 }
1276 assert(Callee->CallerEdges.size() < CalleeCallerCount);
1277 assert(Caller->CalleeEdges.size() < CallerCalleeCount);
1278}
1279
1280template <typename DerivedCCG, typename FuncTy, typename CallTy>
1281void CallsiteContextGraph<
1282 DerivedCCG, FuncTy, CallTy>::removeNoneTypeCalleeEdges(ContextNode *Node) {
1283 for (auto EI = Node->CalleeEdges.begin(); EI != Node->CalleeEdges.end();) {
1284 auto Edge = *EI;
1285 if (Edge->AllocTypes == (uint8_t)AllocationType::None) {
1286 assert(Edge->ContextIds.empty());
1287 removeEdgeFromGraph(Edge.get(), &EI, /*CalleeIter=*/true);
1288 } else
1289 ++EI;
1290 }
1291}
1292
1293template <typename DerivedCCG, typename FuncTy, typename CallTy>
1294void CallsiteContextGraph<
1295 DerivedCCG, FuncTy, CallTy>::removeNoneTypeCallerEdges(ContextNode *Node) {
1296 for (auto EI = Node->CallerEdges.begin(); EI != Node->CallerEdges.end();) {
1297 auto Edge = *EI;
1298 if (Edge->AllocTypes == (uint8_t)AllocationType::None) {
1299 assert(Edge->ContextIds.empty());
1300 Edge->Caller->eraseCalleeEdge(Edge.get());
1301 EI = Node->CallerEdges.erase(EI);
1302 } else
1303 ++EI;
1304 }
1305}
1306
1307template <typename DerivedCCG, typename FuncTy, typename CallTy>
1308typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge *
1309CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1310 findEdgeFromCallee(const ContextNode *Callee) {
1311 for (const auto &Edge : CalleeEdges)
1312 if (Edge->Callee == Callee)
1313 return Edge.get();
1314 return nullptr;
1315}
1316
1317template <typename DerivedCCG, typename FuncTy, typename CallTy>
1318typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge *
1319CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1320 findEdgeFromCaller(const ContextNode *Caller) {
1321 for (const auto &Edge : CallerEdges)
1322 if (Edge->Caller == Caller)
1323 return Edge.get();
1324 return nullptr;
1325}
1326
1327template <typename DerivedCCG, typename FuncTy, typename CallTy>
1328void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1329 eraseCalleeEdge(const ContextEdge *Edge) {
1330 auto EI = llvm::find_if(
1331 CalleeEdges, [Edge](const std::shared_ptr<ContextEdge> &CalleeEdge) {
1332 return CalleeEdge.get() == Edge;
1333 });
1334 assert(EI != CalleeEdges.end());
1335 CalleeEdges.erase(EI);
1336}
1337
1338template <typename DerivedCCG, typename FuncTy, typename CallTy>
1339void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::
1340 eraseCallerEdge(const ContextEdge *Edge) {
1341 auto EI = llvm::find_if(
1342 CallerEdges, [Edge](const std::shared_ptr<ContextEdge> &CallerEdge) {
1343 return CallerEdge.get() == Edge;
1344 });
1345 assert(EI != CallerEdges.end());
1346 CallerEdges.erase(EI);
1347}
1348
1349template <typename DerivedCCG, typename FuncTy, typename CallTy>
1350uint8_t CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::computeAllocType(
1351 DenseSet<uint32_t> &ContextIds) const {
1352 uint8_t BothTypes =
1353 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
1354 uint8_t AllocType = (uint8_t)AllocationType::None;
1355 for (auto Id : ContextIds) {
1356 AllocType |= (uint8_t)ContextIdToAllocationType.at(Id);
1357 // Bail early if alloc type reached both, no further refinement.
1358 if (AllocType == BothTypes)
1359 return AllocType;
1360 }
1361 return AllocType;
1362}
1363
1364template <typename DerivedCCG, typename FuncTy, typename CallTy>
1365uint8_t
1366CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::intersectAllocTypesImpl(
1367 const DenseSet<uint32_t> &Node1Ids,
1368 const DenseSet<uint32_t> &Node2Ids) const {
1369 uint8_t BothTypes =
1370 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
1371 uint8_t AllocType = (uint8_t)AllocationType::None;
1372 for (auto Id : Node1Ids) {
1373 if (!Node2Ids.count(Id))
1374 continue;
1375 AllocType |= (uint8_t)ContextIdToAllocationType.at(Id);
1376 // Bail early if alloc type reached both, no further refinement.
1377 if (AllocType == BothTypes)
1378 return AllocType;
1379 }
1380 return AllocType;
1381}
1382
1383template <typename DerivedCCG, typename FuncTy, typename CallTy>
1384uint8_t CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::intersectAllocTypes(
1385 const DenseSet<uint32_t> &Node1Ids,
1386 const DenseSet<uint32_t> &Node2Ids) const {
1387 if (Node1Ids.size() < Node2Ids.size())
1388 return intersectAllocTypesImpl(Node1Ids, Node2Ids);
1389 else
1390 return intersectAllocTypesImpl(Node2Ids, Node1Ids);
1391}
1392
1393template <typename DerivedCCG, typename FuncTy, typename CallTy>
1394typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
1395CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::addAllocNode(
1396 CallInfo Call, const FuncTy *F) {
1397 assert(!getNodeForAlloc(Call));
1398 ContextNode *AllocNode = createNewNode(/*IsAllocation=*/true, F, Call);
1399 AllocationCallToContextNodeMap[Call] = AllocNode;
1400 // Use LastContextId as a uniq id for MIB allocation nodes.
1401 AllocNode->OrigStackOrAllocId = LastContextId;
1402 // Alloc type should be updated as we add in the MIBs. We should assert
1403 // afterwards that it is not still None.
1404 AllocNode->AllocTypes = (uint8_t)AllocationType::None;
1405
1406 return AllocNode;
1407}
1408
1409static std::string getAllocTypeString(uint8_t AllocTypes) {
1410 if (!AllocTypes)
1411 return "None";
1412 std::string Str;
1413 if (AllocTypes & (uint8_t)AllocationType::NotCold)
1414 Str += "NotCold";
1415 if (AllocTypes & (uint8_t)AllocationType::Cold)
1416 Str += "Cold";
1417 return Str;
1418}
1419
1420template <typename DerivedCCG, typename FuncTy, typename CallTy>
1421template <class NodeT, class IteratorT>
1422void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::addStackNodesForMIB(
1423 ContextNode *AllocNode, CallStack<NodeT, IteratorT> &StackContext,
1424 CallStack<NodeT, IteratorT> &CallsiteContext, AllocationType AllocType,
1425 ArrayRef<ContextTotalSize> ContextSizeInfo,
1426 std::map<uint64_t, uint32_t> &TotalSizeToContextIdTopNCold) {
1427 // Treating the hot alloc type as NotCold before the disambiguation for "hot"
1428 // is done.
1429 if (AllocType == AllocationType::Hot)
1430 AllocType = AllocationType::NotCold;
1431
1432 ContextIdToAllocationType[++LastContextId] = AllocType;
1433
1434 bool IsImportant = false;
1435 if (!ContextSizeInfo.empty()) {
1436 auto &Entry = ContextIdToContextSizeInfos[LastContextId];
1437 // If this is a cold allocation, and we are collecting non-zero largest
1438 // contexts, see if this is a candidate.
1439 if (AllocType == AllocationType::Cold && MemProfTopNImportant > 0) {
1440 uint64_t TotalCold = 0;
1441 for (auto &CSI : ContextSizeInfo)
1442 TotalCold += CSI.TotalSize;
1443 // Record this context if either we haven't found the first top-n largest
1444 // yet, or if it is larger than the smallest already recorded.
1445 if (TotalSizeToContextIdTopNCold.size() < MemProfTopNImportant ||
1446 // Since TotalSizeToContextIdTopNCold is a std::map, it is implicitly
1447 // sorted in ascending size of its key which is the size.
1448 TotalCold > TotalSizeToContextIdTopNCold.begin()->first) {
1449 if (TotalSizeToContextIdTopNCold.size() == MemProfTopNImportant) {
1450 // Remove old one and its associated entries.
1451 auto IdToRemove = TotalSizeToContextIdTopNCold.begin()->second;
1452 TotalSizeToContextIdTopNCold.erase(
1453 TotalSizeToContextIdTopNCold.begin());
1454 assert(ImportantContextIdInfo.count(IdToRemove));
1455 ImportantContextIdInfo.erase(IdToRemove);
1456 }
1457 TotalSizeToContextIdTopNCold[TotalCold] = LastContextId;
1458 IsImportant = true;
1459 }
1460 }
1461 Entry.insert(Entry.begin(), ContextSizeInfo.begin(), ContextSizeInfo.end());
1462 }
1463
1464 // Update alloc type and context ids for this MIB.
1465 AllocNode->AllocTypes |= (uint8_t)AllocType;
1466
1467 // Now add or update nodes for each stack id in alloc's context.
1468 // Later when processing the stack ids on non-alloc callsites we will adjust
1469 // for any inlining in the context.
1470 ContextNode *PrevNode = AllocNode;
1471 // Look for recursion (direct recursion should have been collapsed by
1472 // module summary analysis, here we should just be detecting mutual
1473 // recursion). Mark these nodes so we don't try to clone.
1474 SmallSet<uint64_t, 8> StackIdSet;
1475 // Skip any on the allocation call (inlining).
1476 for (auto ContextIter = StackContext.beginAfterSharedPrefix(CallsiteContext);
1477 ContextIter != StackContext.end(); ++ContextIter) {
1478 auto StackId = getStackId(*ContextIter);
1479 if (IsImportant)
1480 ImportantContextIdInfo[LastContextId].StackIds.push_back(StackId);
1481 ContextNode *StackNode = getNodeForStackId(StackId);
1482 if (!StackNode) {
1483 StackNode = createNewNode(/*IsAllocation=*/false);
1484 StackEntryIdToContextNodeMap[StackId] = StackNode;
1485 StackNode->OrigStackOrAllocId = StackId;
1486 }
1487 // Marking a node recursive will prevent its cloning completely, even for
1488 // non-recursive contexts flowing through it.
1490 auto Ins = StackIdSet.insert(StackId);
1491 if (!Ins.second)
1492 StackNode->Recursive = true;
1493 }
1494 StackNode->AllocTypes |= (uint8_t)AllocType;
1495 PrevNode->addOrUpdateCallerEdge(StackNode, AllocType, LastContextId);
1496 PrevNode = StackNode;
1497 }
1498}
1499
1500template <typename DerivedCCG, typename FuncTy, typename CallTy>
1501DenseSet<uint32_t>
1502CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::duplicateContextIds(
1503 const DenseSet<uint32_t> &StackSequenceContextIds,
1504 DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds) {
1505 DenseSet<uint32_t> NewContextIds;
1506 for (auto OldId : StackSequenceContextIds) {
1507 NewContextIds.insert(++LastContextId);
1508 OldToNewContextIds[OldId].insert(LastContextId);
1509 assert(ContextIdToAllocationType.count(OldId));
1510 // The new context has the same allocation type and size info as original.
1511 ContextIdToAllocationType[LastContextId] = ContextIdToAllocationType[OldId];
1512 auto CSI = ContextIdToContextSizeInfos.find(OldId);
1513 if (CSI != ContextIdToContextSizeInfos.end())
1514 ContextIdToContextSizeInfos[LastContextId] = CSI->second;
1515 if (DotAllocContextIds.contains(OldId))
1516 DotAllocContextIds.insert(LastContextId);
1517 }
1518 return NewContextIds;
1519}
1520
1521template <typename DerivedCCG, typename FuncTy, typename CallTy>
1522void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
1523 propagateDuplicateContextIds(
1524 const DenseMap<uint32_t, DenseSet<uint32_t>> &OldToNewContextIds) {
1525 // Build a set of duplicated context ids corresponding to the input id set.
1526 auto GetNewIds = [&OldToNewContextIds](const DenseSet<uint32_t> &ContextIds) {
1527 DenseSet<uint32_t> NewIds;
1528 for (auto Id : ContextIds)
1529 if (auto NewId = OldToNewContextIds.find(Id);
1530 NewId != OldToNewContextIds.end())
1531 NewIds.insert_range(NewId->second);
1532 return NewIds;
1533 };
1534
1535 // Recursively update context ids sets along caller edges.
1536 auto UpdateCallers = [&](ContextNode *Node,
1537 DenseSet<const ContextEdge *> &Visited,
1538 auto &&UpdateCallers) -> void {
1539 for (const auto &Edge : Node->CallerEdges) {
1540 auto Inserted = Visited.insert(Edge.get());
1541 if (!Inserted.second)
1542 continue;
1543 ContextNode *NextNode = Edge->Caller;
1544 DenseSet<uint32_t> NewIdsToAdd = GetNewIds(Edge->getContextIds());
1545 // Only need to recursively iterate to NextNode via this caller edge if
1546 // it resulted in any added ids to NextNode.
1547 if (!NewIdsToAdd.empty()) {
1548 Edge->getContextIds().insert_range(NewIdsToAdd);
1549 UpdateCallers(NextNode, Visited, UpdateCallers);
1550 }
1551 }
1552 };
1553
1554 DenseSet<const ContextEdge *> Visited;
1555 for (auto &Entry : AllocationCallToContextNodeMap) {
1556 auto *Node = Entry.second;
1557 UpdateCallers(Node, Visited, UpdateCallers);
1558 }
1559}
1560
1561template <typename DerivedCCG, typename FuncTy, typename CallTy>
1562void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::connectNewNode(
1563 ContextNode *NewNode, ContextNode *OrigNode, bool TowardsCallee,
1564 // This must be passed by value to make a copy since it will be adjusted
1565 // as ids are moved.
1566 DenseSet<uint32_t> RemainingContextIds) {
1567 auto &OrigEdges =
1568 TowardsCallee ? OrigNode->CalleeEdges : OrigNode->CallerEdges;
1569 DenseSet<uint32_t> RecursiveContextIds;
1570 DenseSet<uint32_t> AllCallerContextIds;
1572 // Identify which context ids are recursive which is needed to properly
1573 // update the RemainingContextIds set. The relevant recursive context ids
1574 // are those that are in multiple edges.
1575 for (auto &CE : OrigEdges) {
1576 AllCallerContextIds.reserve(CE->getContextIds().size());
1577 for (auto Id : CE->getContextIds())
1578 if (!AllCallerContextIds.insert(Id).second)
1579 RecursiveContextIds.insert(Id);
1580 }
1581 }
1582 // Increment iterator in loop so that we can remove edges as needed.
1583 for (auto EI = OrigEdges.begin(); EI != OrigEdges.end();) {
1584 auto Edge = *EI;
1585 DenseSet<uint32_t> NewEdgeContextIds;
1586 DenseSet<uint32_t> NotFoundContextIds;
1587 // Remove any matching context ids from Edge, return set that were found and
1588 // removed, these are the new edge's context ids. Also update the remaining
1589 // (not found ids).
1590 set_subtract(Edge->getContextIds(), RemainingContextIds, NewEdgeContextIds,
1591 NotFoundContextIds);
1592 // Update the remaining context ids set for the later edges. This is a
1593 // compile time optimization.
1594 if (RecursiveContextIds.empty()) {
1595 // No recursive ids, so all of the previously remaining context ids that
1596 // were not seen on this edge are the new remaining set.
1597 RemainingContextIds.swap(NotFoundContextIds);
1598 } else {
1599 // Keep the recursive ids in the remaining set as we expect to see those
1600 // on another edge. We can remove the non-recursive remaining ids that
1601 // were seen on this edge, however. We already have the set of remaining
1602 // ids that were on this edge (in NewEdgeContextIds). Figure out which are
1603 // non-recursive and only remove those. Note that despite the higher
1604 // overhead of updating the remaining context ids set when recursion
1605 // handling is enabled, it was found to be at worst performance neutral
1606 // and in one case a clear win.
1607 DenseSet<uint32_t> NonRecursiveRemainingCurEdgeIds =
1608 set_difference(NewEdgeContextIds, RecursiveContextIds);
1609 set_subtract(RemainingContextIds, NonRecursiveRemainingCurEdgeIds);
1610 }
1611 // If no matching context ids for this edge, skip it.
1612 if (NewEdgeContextIds.empty()) {
1613 ++EI;
1614 continue;
1615 }
1616 if (TowardsCallee) {
1617 uint8_t NewAllocType = computeAllocType(NewEdgeContextIds);
1618 auto NewEdge = std::make_shared<ContextEdge>(
1619 Edge->Callee, NewNode, NewAllocType, std::move(NewEdgeContextIds));
1620 NewNode->CalleeEdges.push_back(NewEdge);
1621 NewEdge->Callee->CallerEdges.push_back(NewEdge);
1622 } else {
1623 uint8_t NewAllocType = computeAllocType(NewEdgeContextIds);
1624 auto NewEdge = std::make_shared<ContextEdge>(
1625 NewNode, Edge->Caller, NewAllocType, std::move(NewEdgeContextIds));
1626 NewNode->CallerEdges.push_back(NewEdge);
1627 NewEdge->Caller->CalleeEdges.push_back(NewEdge);
1628 }
1629 // Remove old edge if context ids empty.
1630 if (Edge->getContextIds().empty()) {
1631 removeEdgeFromGraph(Edge.get(), &EI, TowardsCallee);
1632 continue;
1633 }
1634 ++EI;
1635 }
1636}
1637
1638template <typename DerivedCCG, typename FuncTy, typename CallTy>
1639static void checkEdge(
1640 const std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>> &Edge) {
1641 // Confirm that alloc type is not None and that we have at least one context
1642 // id.
1643 assert(Edge->AllocTypes != (uint8_t)AllocationType::None);
1644 assert(!Edge->ContextIds.empty());
1645}
1646
1647template <typename DerivedCCG, typename FuncTy, typename CallTy>
1648static void checkNode(const ContextNode<DerivedCCG, FuncTy, CallTy> *Node,
1649 bool CheckEdges = true) {
1650 if (Node->isRemoved())
1651 return;
1652#ifndef NDEBUG
1653 // Compute node's context ids once for use in asserts.
1654 auto NodeContextIds = Node->getContextIds();
1655#endif
1656 // Node's context ids should be the union of both its callee and caller edge
1657 // context ids.
1658 if (Node->CallerEdges.size()) {
1659 DenseSet<uint32_t> CallerEdgeContextIds(
1660 Node->CallerEdges.front()->ContextIds);
1661 for (const auto &Edge : llvm::drop_begin(Node->CallerEdges)) {
1662 if (CheckEdges)
1664 set_union(CallerEdgeContextIds, Edge->ContextIds);
1665 }
1666 // Node can have more context ids than callers if some contexts terminate at
1667 // node and some are longer. If we are allowing recursive callsites and
1668 // contexts this will be violated for incompletely cloned recursive cycles,
1669 // so skip the checking in that case.
1671 NodeContextIds == CallerEdgeContextIds ||
1672 set_is_subset(CallerEdgeContextIds, NodeContextIds));
1673 }
1674 if (Node->CalleeEdges.size()) {
1675 DenseSet<uint32_t> CalleeEdgeContextIds(
1676 Node->CalleeEdges.front()->ContextIds);
1677 for (const auto &Edge : llvm::drop_begin(Node->CalleeEdges)) {
1678 if (CheckEdges)
1680 set_union(CalleeEdgeContextIds, Edge->getContextIds());
1681 }
1682 // If we are allowing recursive callsites and contexts this will be violated
1683 // for incompletely cloned recursive cycles, so skip the checking in that
1684 // case.
1686 NodeContextIds == CalleeEdgeContextIds);
1687 }
1688 // FIXME: Since this checking is only invoked under an option, we should
1689 // change the error checking from using assert to something that will trigger
1690 // an error on a release build.
1691#ifndef NDEBUG
1692 // Make sure we don't end up with duplicate edges between the same caller and
1693 // callee.
1695 for (const auto &E : Node->CalleeEdges)
1696 NodeSet.insert(E->Callee);
1697 assert(NodeSet.size() == Node->CalleeEdges.size());
1698#endif
1699}
1700
1701template <typename DerivedCCG, typename FuncTy, typename CallTy>
1702void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
1703 assignStackNodesPostOrder(ContextNode *Node,
1704 DenseSet<const ContextNode *> &Visited,
1705 DenseMap<uint64_t, std::vector<CallContextInfo>>
1706 &StackIdToMatchingCalls,
1707 DenseMap<CallInfo, CallInfo> &CallToMatchingCall,
1708 const DenseSet<uint32_t> &ImportantContextIds) {
1709 auto Inserted = Visited.insert(Node);
1710 if (!Inserted.second)
1711 return;
1712 // Post order traversal. Iterate over a copy since we may add nodes and
1713 // therefore new callers during the recursive call, invalidating any
1714 // iterator over the original edge vector. We don't need to process these
1715 // new nodes as they were already processed on creation.
1716 auto CallerEdges = Node->CallerEdges;
1717 for (auto &Edge : CallerEdges) {
1718 // Skip any that have been removed during the recursion.
1719 if (Edge->isRemoved()) {
1720 assert(!is_contained(Node->CallerEdges, Edge));
1721 continue;
1722 }
1723 assignStackNodesPostOrder(Edge->Caller, Visited, StackIdToMatchingCalls,
1724 CallToMatchingCall, ImportantContextIds);
1725 }
1726
1727 // If this node's stack id is in the map, update the graph to contain new
1728 // nodes representing any inlining at interior callsites. Note we move the
1729 // associated context ids over to the new nodes.
1730
1731 // Ignore this node if it is for an allocation or we didn't record any
1732 // stack id lists ending at it.
1733 if (Node->IsAllocation ||
1734 !StackIdToMatchingCalls.count(Node->OrigStackOrAllocId))
1735 return;
1736
1737 auto &Calls = StackIdToMatchingCalls[Node->OrigStackOrAllocId];
1738 // Handle the simple case first. A single call with a single stack id.
1739 // In this case there is no need to create any new context nodes, simply
1740 // assign the context node for stack id to this Call.
1741 if (Calls.size() == 1) {
1742 auto &[Call, Ids, Func, SavedContextIds] = Calls[0];
1743 if (Ids.size() == 1) {
1744 assert(SavedContextIds.empty());
1745 // It should be this Node
1746 assert(Node == getNodeForStackId(Ids[0]));
1747 if (Node->Recursive)
1748 return;
1749 Node->setCall(Call);
1750 NonAllocationCallToContextNodeMap[Call] = Node;
1751 NodeToCallingFunc[Node] = Func;
1752 recordStackNode(Ids, Node, Node->getContextIds(), ImportantContextIds);
1753 return;
1754 }
1755 }
1756
1757#ifndef NDEBUG
1758 // Find the node for the last stack id, which should be the same
1759 // across all calls recorded for this id, and is this node's id.
1760 uint64_t LastId = Node->OrigStackOrAllocId;
1761 ContextNode *LastNode = getNodeForStackId(LastId);
1762 // We should only have kept stack ids that had nodes.
1763 assert(LastNode);
1764 assert(LastNode == Node);
1765#else
1766 ContextNode *LastNode = Node;
1767#endif
1768
1769 // Compute the last node's context ids once, as it is shared by all calls in
1770 // this entry.
1771 DenseSet<uint32_t> LastNodeContextIds = LastNode->getContextIds();
1772
1773 [[maybe_unused]] bool PrevIterCreatedNode = false;
1774 bool CreatedNode = false;
1775 for (unsigned I = 0; I < Calls.size();
1776 I++, PrevIterCreatedNode = CreatedNode) {
1777 CreatedNode = false;
1778 auto &[Call, Ids, Func, SavedContextIds] = Calls[I];
1779 // Skip any for which we didn't assign any ids, these don't get a node in
1780 // the graph.
1781 if (SavedContextIds.empty()) {
1782 // If this call has a matching call (located in the same function and
1783 // having the same stack ids), simply add it to the context node created
1784 // for its matching call earlier. These can be treated the same through
1785 // cloning and get updated at the same time.
1786 if (!CallToMatchingCall.contains(Call))
1787 continue;
1788 auto MatchingCall = CallToMatchingCall[Call];
1789 if (!NonAllocationCallToContextNodeMap.contains(MatchingCall)) {
1790 // This should only happen if we had a prior iteration, and it didn't
1791 // create a node because of the below recomputation of context ids
1792 // finding none remaining and continuing early.
1793 assert(I > 0 && !PrevIterCreatedNode);
1794 continue;
1795 }
1796 NonAllocationCallToContextNodeMap[MatchingCall]->MatchingCalls.push_back(
1797 Call);
1798 continue;
1799 }
1800
1801 assert(LastId == Ids.back());
1802
1803 // Recompute the context ids for this stack id sequence (the
1804 // intersection of the context ids of the corresponding nodes).
1805 // Start with the ids we saved in the map for this call, which could be
1806 // duplicated context ids. We have to recompute as we might have overlap
1807 // overlap between the saved context ids for different last nodes, and
1808 // removed them already during the post order traversal.
1809 set_intersect(SavedContextIds, LastNodeContextIds);
1810 ContextNode *PrevNode = LastNode;
1811 bool Skip = false;
1812 // Iterate backwards through the stack Ids, starting after the last Id
1813 // in the list, which was handled once outside for all Calls.
1814 for (auto IdIter = Ids.rbegin() + 1; IdIter != Ids.rend(); IdIter++) {
1815 auto Id = *IdIter;
1816 ContextNode *CurNode = getNodeForStackId(Id);
1817 // We should only have kept stack ids that had nodes and weren't
1818 // recursive.
1819 assert(CurNode);
1820 assert(!CurNode->Recursive);
1821
1822 auto *Edge = CurNode->findEdgeFromCaller(PrevNode);
1823 if (!Edge) {
1824 Skip = true;
1825 break;
1826 }
1827 PrevNode = CurNode;
1828
1829 // Update the context ids, which is the intersection of the ids along
1830 // all edges in the sequence.
1831 set_intersect(SavedContextIds, Edge->getContextIds());
1832
1833 // If we now have no context ids for clone, skip this call.
1834 if (SavedContextIds.empty()) {
1835 Skip = true;
1836 break;
1837 }
1838 }
1839 if (Skip)
1840 continue;
1841
1842 // Create new context node.
1843 ContextNode *NewNode = createNewNode(/*IsAllocation=*/false, Func, Call);
1844 NonAllocationCallToContextNodeMap[Call] = NewNode;
1845 CreatedNode = true;
1846 NewNode->AllocTypes = computeAllocType(SavedContextIds);
1847
1848 ContextNode *FirstNode = getNodeForStackId(Ids[0]);
1849 assert(FirstNode);
1850
1851 // Connect to callees of innermost stack frame in inlined call chain.
1852 // This updates context ids for FirstNode's callee's to reflect those
1853 // moved to NewNode.
1854 connectNewNode(NewNode, FirstNode, /*TowardsCallee=*/true, SavedContextIds);
1855
1856 // Connect to callers of outermost stack frame in inlined call chain.
1857 // This updates context ids for FirstNode's caller's to reflect those
1858 // moved to NewNode.
1859 connectNewNode(NewNode, LastNode, /*TowardsCallee=*/false, SavedContextIds);
1860
1861 // Now we need to remove context ids from edges/nodes between First and
1862 // Last Node.
1863 PrevNode = nullptr;
1864 for (auto Id : Ids) {
1865 ContextNode *CurNode = getNodeForStackId(Id);
1866 // We should only have kept stack ids that had nodes.
1867 assert(CurNode);
1868
1869 // Remove the context ids moved to NewNode from CurNode, and the
1870 // edge from the prior node.
1871 if (PrevNode) {
1872 auto *PrevEdge = CurNode->findEdgeFromCallee(PrevNode);
1873 // If the sequence contained recursion, we might have already removed
1874 // some edges during the connectNewNode calls above.
1875 if (!PrevEdge) {
1876 PrevNode = CurNode;
1877 continue;
1878 }
1879 set_subtract(PrevEdge->getContextIds(), SavedContextIds);
1880 if (PrevEdge->getContextIds().empty())
1881 removeEdgeFromGraph(PrevEdge);
1882 }
1883 // Since we update the edges from leaf to tail, only look at the callee
1884 // edges. This isn't an alloc node, so if there are no callee edges, the
1885 // alloc type is None.
1886 CurNode->AllocTypes = CurNode->CalleeEdges.empty()
1887 ? (uint8_t)AllocationType::None
1888 : CurNode->computeAllocType();
1889 PrevNode = CurNode;
1890 }
1891
1892 recordStackNode(Ids, NewNode, SavedContextIds, ImportantContextIds);
1893
1894 if (VerifyNodes) {
1895 checkNode<DerivedCCG, FuncTy, CallTy>(NewNode, /*CheckEdges=*/true);
1896 for (auto Id : Ids) {
1897 ContextNode *CurNode = getNodeForStackId(Id);
1898 // We should only have kept stack ids that had nodes.
1899 assert(CurNode);
1900 checkNode<DerivedCCG, FuncTy, CallTy>(CurNode, /*CheckEdges=*/true);
1901 }
1902 }
1903 }
1904}
1905
1906template <typename DerivedCCG, typename FuncTy, typename CallTy>
1907void CallsiteContextGraph<DerivedCCG, FuncTy,
1908 CallTy>::fixupImportantContexts() {
1909 if (ImportantContextIdInfo.empty())
1910 return;
1911
1912 // Update statistics as we are done building this map at this point.
1913 NumImportantContextIds = ImportantContextIdInfo.size();
1914
1916 return;
1917
1918 if (ExportToDot)
1919 exportToDot("beforestackfixup");
1920
1921 // For each context we identified as important, walk through the saved context
1922 // stack ids in order from leaf upwards, and make sure all edges are correct.
1923 // These can be difficult to get right when updating the graph while mapping
1924 // nodes onto summary or IR, especially when there is recursion. In
1925 // particular, when we have created new nodes to reflect inlining, it is
1926 // sometimes impossible to know exactly how to update the edges in the face of
1927 // recursion, as we have lost the original ordering of the stack ids in the
1928 // contexts.
1929 // TODO: Consider only doing this if we detect the context has recursive
1930 // cycles.
1931 //
1932 // I.e. assume we have a context with stack ids like: {A B A C A D E}
1933 // and let's say A was inlined into B, C, and D. The original graph will have
1934 // multiple recursive cycles through A. When we match the original context
1935 // nodes onto the IR or summary, we will merge {A B} into one context node,
1936 // {A C} onto another, and {A D} onto another. Looking at the stack sequence
1937 // above, we should end up with a non-cyclic set of edges like:
1938 // {AB} <- {AC} <- {AD} <- E. However, because we normally have lost the
1939 // original ordering, we won't get the edges correct initially (it's
1940 // impossible without the original ordering). Here we do the fixup (add and
1941 // removing edges where necessary) for this context. In the
1942 // ImportantContextInfo struct in this case we should have a MaxLength = 2,
1943 // and map entries for {A B}, {A C}, {A D}, and {E}.
1944 for (auto &[CurContextId, Info] : ImportantContextIdInfo) {
1945 if (Info.StackIdsToNode.empty())
1946 continue;
1947 bool Changed = false;
1948 ContextNode *PrevNode = nullptr;
1949 ContextNode *CurNode = nullptr;
1950 DenseSet<const ContextEdge *> VisitedEdges;
1951 ArrayRef<uint64_t> AllStackIds(Info.StackIds);
1952 // Try to identify what callsite ContextNode maps to which slice of the
1953 // context's ordered stack ids.
1954 for (unsigned I = 0; I < AllStackIds.size(); I++, PrevNode = CurNode) {
1955 // We will do this greedily, trying up to MaxLength stack ids in a row, to
1956 // see if we recorded a context node for that sequence.
1957 auto Len = Info.MaxLength;
1958 auto LenToEnd = AllStackIds.size() - I;
1959 if (Len > LenToEnd)
1960 Len = LenToEnd;
1961 CurNode = nullptr;
1962 // Try to find a recorded context node starting with the longest length
1963 // recorded, and on down until we check for just a single stack node.
1964 for (; Len > 0; Len--) {
1965 // Get the slice of the original stack id sequence to check.
1966 auto CheckStackIds = AllStackIds.slice(I, Len);
1967 auto EntryIt = Info.StackIdsToNode.find(CheckStackIds);
1968 if (EntryIt == Info.StackIdsToNode.end())
1969 continue;
1970 CurNode = EntryIt->second;
1971 // Skip forward so we don't try to look for the ones we just matched.
1972 // We increment by Len - 1, because the outer for loop will increment I.
1973 I += Len - 1;
1974 break;
1975 }
1976 // Give up if we couldn't find a node. Since we need to clone from the
1977 // leaf allocation upwards, no sense in doing anymore fixup further up
1978 // the context if we couldn't match part of the original stack context
1979 // onto a callsite node.
1980 if (!CurNode)
1981 break;
1982 // No edges to fix up until we have a pair of nodes that should be
1983 // adjacent in the graph.
1984 if (!PrevNode)
1985 continue;
1986 // See if we already have a call edge from CurNode to PrevNode.
1987 auto *CurEdge = PrevNode->findEdgeFromCaller(CurNode);
1988 if (CurEdge) {
1989 // We already have an edge. Make sure it contains this context id.
1990 if (CurEdge->getContextIds().insert(CurContextId).second) {
1991 NumFixupEdgeIdsInserted++;
1992 Changed = true;
1993 }
1994 } else {
1995 // No edge exists - add one.
1996 NumFixupEdgesAdded++;
1997 DenseSet<uint32_t> ContextIds({CurContextId});
1998 auto AllocType = computeAllocType(ContextIds);
1999 auto NewEdge = std::make_shared<ContextEdge>(
2000 PrevNode, CurNode, AllocType, std::move(ContextIds));
2001 PrevNode->CallerEdges.push_back(NewEdge);
2002 CurNode->CalleeEdges.push_back(NewEdge);
2003 // Save the new edge for the below handling.
2004 CurEdge = NewEdge.get();
2005 Changed = true;
2006 }
2007 VisitedEdges.insert(CurEdge);
2008 // Now remove this context id from any other caller edges calling
2009 // PrevNode.
2010 for (auto &Edge : PrevNode->CallerEdges) {
2011 // Skip the edge updating/created above and edges we have already
2012 // visited (due to recursion).
2013 if (Edge.get() != CurEdge && !VisitedEdges.contains(Edge.get()))
2014 Edge->getContextIds().erase(CurContextId);
2015 }
2016 }
2017 if (Changed)
2018 NumFixedContexts++;
2019 }
2020}
2021
2022template <typename DerivedCCG, typename FuncTy, typename CallTy>
2023void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::updateStackNodes() {
2024 // Map of stack id to all calls with that as the last (outermost caller)
2025 // callsite id that has a context node (some might not due to pruning
2026 // performed during matching of the allocation profile contexts).
2027 // The CallContextInfo contains the Call and a list of its stack ids with
2028 // ContextNodes, the function containing Call, and the set of context ids
2029 // the analysis will eventually identify for use in any new node created
2030 // for that callsite.
2031 DenseMap<uint64_t, std::vector<CallContextInfo>> StackIdToMatchingCalls;
2032 for (auto &[Func, CallsWithMetadata] : FuncToCallsWithMetadata) {
2033 for (auto &Call : CallsWithMetadata) {
2034 // Ignore allocations, already handled.
2035 if (AllocationCallToContextNodeMap.count(Call))
2036 continue;
2037 auto StackIdsWithContextNodes =
2038 getStackIdsWithContextNodesForCall(Call.call());
2039 // If there were no nodes created for MIBs on allocs (maybe this was in
2040 // the unambiguous part of the MIB stack that was pruned), ignore.
2041 if (StackIdsWithContextNodes.empty())
2042 continue;
2043 // Otherwise, record this Call along with the list of ids for the last
2044 // (outermost caller) stack id with a node.
2045 StackIdToMatchingCalls[StackIdsWithContextNodes.back()].push_back(
2046 {Call.call(), StackIdsWithContextNodes, Func, {}});
2047 }
2048 }
2049
2050 // First make a pass through all stack ids that correspond to a call,
2051 // as identified in the above loop. Compute the context ids corresponding to
2052 // each of these calls when they correspond to multiple stack ids due to
2053 // due to inlining. Perform any duplication of context ids required when
2054 // there is more than one call with the same stack ids. Their (possibly newly
2055 // duplicated) context ids are saved in the StackIdToMatchingCalls map.
2056 DenseMap<uint32_t, DenseSet<uint32_t>> OldToNewContextIds;
2057 // Save a map from each call to any that are found to match it. I.e. located
2058 // in the same function and have the same (possibly pruned) stack ids. We use
2059 // this to avoid creating extra graph nodes as they can be treated the same.
2060 DenseMap<CallInfo, CallInfo> CallToMatchingCall;
2061 for (auto &It : StackIdToMatchingCalls) {
2062 auto &Calls = It.getSecond();
2063 // Skip single calls with a single stack id. These don't need a new node.
2064 if (Calls.size() == 1) {
2065 auto &Ids = Calls[0].StackIds;
2066 if (Ids.size() == 1)
2067 continue;
2068 }
2069 // In order to do the best and maximal matching of inlined calls to context
2070 // node sequences we will sort the vectors of stack ids in descending order
2071 // of length, and within each length, lexicographically by stack id. The
2072 // latter is so that we can specially handle calls that have identical stack
2073 // id sequences (either due to cloning or artificially because of the MIB
2074 // context pruning). Those with the same Ids are then sorted by function to
2075 // facilitate efficiently mapping them to the same context node.
2076 // Because the functions are pointers, to ensure a stable sort first assign
2077 // each function pointer to its first index in the Calls array, and then use
2078 // that to sort by.
2079 DenseMap<const FuncTy *, unsigned> FuncToIndex;
2080 for (const auto &[Idx, CallCtxInfo] : enumerate(Calls))
2081 FuncToIndex.insert({CallCtxInfo.Func, Idx});
2083 Calls,
2084 [&FuncToIndex](const CallContextInfo &A, const CallContextInfo &B) {
2085 return A.StackIds.size() > B.StackIds.size() ||
2086 (A.StackIds.size() == B.StackIds.size() &&
2087 (A.StackIds < B.StackIds ||
2088 (A.StackIds == B.StackIds &&
2089 FuncToIndex[A.Func] < FuncToIndex[B.Func])));
2090 });
2091
2092 // Find the node for the last stack id, which should be the same
2093 // across all calls recorded for this id, and is the id for this
2094 // entry in the StackIdToMatchingCalls map.
2095 uint64_t LastId = It.getFirst();
2096 ContextNode *LastNode = getNodeForStackId(LastId);
2097 // We should only have kept stack ids that had nodes.
2098 assert(LastNode);
2099
2100 if (LastNode->Recursive)
2101 continue;
2102
2103 // Initialize the context ids with the last node's. We will subsequently
2104 // refine the context ids by computing the intersection along all edges.
2105 DenseSet<uint32_t> LastNodeContextIds = LastNode->getContextIds();
2106 assert(!LastNodeContextIds.empty());
2107
2108#ifndef NDEBUG
2109 // Save the set of functions seen for a particular set of the same stack
2110 // ids. This is used to ensure that they have been correctly sorted to be
2111 // adjacent in the Calls list, since we rely on that to efficiently place
2112 // all such matching calls onto the same context node.
2113 DenseSet<const FuncTy *> MatchingIdsFuncSet;
2114#endif
2115
2116 for (unsigned I = 0; I < Calls.size(); I++) {
2117 auto &[Call, Ids, Func, SavedContextIds] = Calls[I];
2118 assert(SavedContextIds.empty());
2119 assert(LastId == Ids.back());
2120
2121#ifndef NDEBUG
2122 // If this call has a different set of ids than the last one, clear the
2123 // set used to ensure they are sorted properly.
2124 if (I > 0 && Ids != Calls[I - 1].StackIds)
2125 MatchingIdsFuncSet.clear();
2126#endif
2127
2128 // First compute the context ids for this stack id sequence (the
2129 // intersection of the context ids of the corresponding nodes).
2130 // Start with the remaining saved ids for the last node.
2131 assert(!LastNodeContextIds.empty());
2132 DenseSet<uint32_t> StackSequenceContextIds = LastNodeContextIds;
2133
2134 ContextNode *PrevNode = LastNode;
2135 ContextNode *CurNode = LastNode;
2136 bool Skip = false;
2137
2138 // Iterate backwards through the stack Ids, starting after the last Id
2139 // in the list, which was handled once outside for all Calls.
2140 for (auto IdIter = Ids.rbegin() + 1; IdIter != Ids.rend(); IdIter++) {
2141 auto Id = *IdIter;
2142 CurNode = getNodeForStackId(Id);
2143 // We should only have kept stack ids that had nodes.
2144 assert(CurNode);
2145
2146 if (CurNode->Recursive) {
2147 Skip = true;
2148 break;
2149 }
2150
2151 auto *Edge = CurNode->findEdgeFromCaller(PrevNode);
2152 // If there is no edge then the nodes belong to different MIB contexts,
2153 // and we should skip this inlined context sequence. For example, this
2154 // particular inlined context may include stack ids A->B, and we may
2155 // indeed have nodes for both A and B, but it is possible that they were
2156 // never profiled in sequence in a single MIB for any allocation (i.e.
2157 // we might have profiled an allocation that involves the callsite A,
2158 // but through a different one of its callee callsites, and we might
2159 // have profiled an allocation that involves callsite B, but reached
2160 // from a different caller callsite).
2161 if (!Edge) {
2162 Skip = true;
2163 break;
2164 }
2165 PrevNode = CurNode;
2166
2167 // Update the context ids, which is the intersection of the ids along
2168 // all edges in the sequence.
2169 set_intersect(StackSequenceContextIds, Edge->getContextIds());
2170
2171 // If we now have no context ids for clone, skip this call.
2172 if (StackSequenceContextIds.empty()) {
2173 Skip = true;
2174 break;
2175 }
2176 }
2177 if (Skip)
2178 continue;
2179
2180 // If some of this call's stack ids did not have corresponding nodes (due
2181 // to pruning), don't include any context ids for contexts that extend
2182 // beyond these nodes. Otherwise we would be matching part of unrelated /
2183 // not fully matching stack contexts. To do this, subtract any context ids
2184 // found in caller nodes of the last node found above.
2185 if (Ids.back() != getLastStackId(Call)) {
2186 for (const auto &PE : LastNode->CallerEdges) {
2187 set_subtract(StackSequenceContextIds, PE->getContextIds());
2188 if (StackSequenceContextIds.empty())
2189 break;
2190 }
2191 // If we now have no context ids for clone, skip this call.
2192 if (StackSequenceContextIds.empty())
2193 continue;
2194 }
2195
2196#ifndef NDEBUG
2197 // If the prior call had the same stack ids this set would not be empty.
2198 // Check if we already have a call that "matches" because it is located
2199 // in the same function. If the Calls list was sorted properly we should
2200 // not encounter this situation as all such entries should be adjacent
2201 // and processed in bulk further below.
2202 assert(!MatchingIdsFuncSet.contains(Func));
2203
2204 MatchingIdsFuncSet.insert(Func);
2205#endif
2206
2207 // Check if the next set of stack ids is the same (since the Calls vector
2208 // of tuples is sorted by the stack ids we can just look at the next one).
2209 // If so, save them in the CallToMatchingCall map so that they get
2210 // assigned to the same context node, and skip them.
2211 bool DuplicateContextIds = false;
2212 for (unsigned J = I + 1; J < Calls.size(); J++) {
2213 auto &CallCtxInfo = Calls[J];
2214 auto &NextIds = CallCtxInfo.StackIds;
2215 if (NextIds != Ids)
2216 break;
2217 auto *NextFunc = CallCtxInfo.Func;
2218 if (NextFunc != Func) {
2219 // We have another Call with the same ids but that cannot share this
2220 // node, must duplicate ids for it.
2221 DuplicateContextIds = true;
2222 break;
2223 }
2224 auto &NextCall = CallCtxInfo.Call;
2225 CallToMatchingCall[NextCall] = Call;
2226 // Update I so that it gets incremented correctly to skip this call.
2227 I = J;
2228 }
2229
2230 // If we don't have duplicate context ids, then we can assign all the
2231 // context ids computed for the original node sequence to this call.
2232 // If there are duplicate calls with the same stack ids then we synthesize
2233 // new context ids that are duplicates of the originals. These are
2234 // assigned to SavedContextIds, which is a reference into the map entry
2235 // for this call, allowing us to access these ids later on.
2236 OldToNewContextIds.reserve(OldToNewContextIds.size() +
2237 StackSequenceContextIds.size());
2238 SavedContextIds =
2239 DuplicateContextIds
2240 ? duplicateContextIds(StackSequenceContextIds, OldToNewContextIds)
2241 : StackSequenceContextIds;
2242 assert(!SavedContextIds.empty());
2243
2244 if (!DuplicateContextIds) {
2245 // Update saved last node's context ids to remove those that are
2246 // assigned to other calls, so that it is ready for the next call at
2247 // this stack id.
2248 set_subtract(LastNodeContextIds, StackSequenceContextIds);
2249 if (LastNodeContextIds.empty())
2250 break;
2251 }
2252 }
2253 }
2254
2255 // Propagate the duplicate context ids over the graph.
2256 propagateDuplicateContextIds(OldToNewContextIds);
2257
2258 if (VerifyCCG)
2259 check();
2260
2261 // Now perform a post-order traversal over the graph, starting with the
2262 // allocation nodes, essentially processing nodes from callers to callees.
2263 // For any that contains an id in the map, update the graph to contain new
2264 // nodes representing any inlining at interior callsites. Note we move the
2265 // associated context ids over to the new nodes.
2266 DenseSet<const ContextNode *> Visited;
2267 DenseSet<uint32_t> ImportantContextIds(llvm::from_range,
2268 ImportantContextIdInfo.keys());
2269 for (auto &Entry : AllocationCallToContextNodeMap)
2270 assignStackNodesPostOrder(Entry.second, Visited, StackIdToMatchingCalls,
2271 CallToMatchingCall, ImportantContextIds);
2272
2273 fixupImportantContexts();
2274
2275 if (VerifyCCG)
2276 check();
2277}
2278
2279uint64_t ModuleCallsiteContextGraph::getLastStackId(Instruction *Call) {
2280 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(
2281 Call->getMetadata(LLVMContext::MD_callsite));
2282 return CallsiteContext.back();
2283}
2284
2285uint64_t IndexCallsiteContextGraph::getLastStackId(IndexCall &Call) {
2287 CallStack<CallsiteInfo, SmallVector<unsigned>::const_iterator>
2288 CallsiteContext(dyn_cast_if_present<CallsiteInfo *>(Call));
2289 // Need to convert index into stack id.
2290 return Index.getStackIdAtIndex(CallsiteContext.back());
2291}
2292
2293static const std::string MemProfCloneSuffix = ".memprof.";
2294
2295static std::string getMemProfFuncName(Twine Base, unsigned CloneNo) {
2296 // We use CloneNo == 0 to refer to the original version, which doesn't get
2297 // renamed with a suffix.
2298 if (!CloneNo)
2299 return Base.str();
2300 return (Base + MemProfCloneSuffix + Twine(CloneNo)).str();
2301}
2302
2303static bool isMemProfClone(const Function &F) {
2304 return F.getName().contains(MemProfCloneSuffix);
2305}
2306
2307// Return the clone number of the given function by extracting it from the
2308// memprof suffix. Assumes the caller has already confirmed it is a memprof
2309// clone.
2310static unsigned getMemProfCloneNum(const Function &F) {
2312 auto Pos = F.getName().find_last_of('.');
2313 assert(Pos > 0);
2314 unsigned CloneNo;
2315 bool Err = F.getName().drop_front(Pos + 1).getAsInteger(10, CloneNo);
2316 assert(!Err);
2317 (void)Err;
2318 return CloneNo;
2319}
2320
2321std::string ModuleCallsiteContextGraph::getLabel(const Function *Func,
2322 const Instruction *Call,
2323 unsigned CloneNo) const {
2324 return (Twine(Call->getFunction()->getName()) + " -> " +
2325 cast<CallBase>(Call)->getCalledFunction()->getName())
2326 .str();
2327}
2328
2329std::string IndexCallsiteContextGraph::getLabel(const FunctionSummary *Func,
2330 const IndexCall &Call,
2331 unsigned CloneNo) const {
2332 auto VI = FSToVIMap.find(Func);
2333 assert(VI != FSToVIMap.end());
2334 std::string CallerName = getMemProfFuncName(VI->second.name(), CloneNo);
2336 return CallerName + " -> alloc";
2337 else {
2338 auto *Callsite = dyn_cast_if_present<CallsiteInfo *>(Call);
2339 return CallerName + " -> " +
2340 getMemProfFuncName(Callsite->Callee.name(),
2341 Callsite->Clones[CloneNo]);
2342 }
2343}
2344
2345std::vector<uint64_t>
2346ModuleCallsiteContextGraph::getStackIdsWithContextNodesForCall(
2347 Instruction *Call) {
2348 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(
2349 Call->getMetadata(LLVMContext::MD_callsite));
2350 return getStackIdsWithContextNodes<MDNode, MDNode::op_iterator>(
2351 CallsiteContext);
2352}
2353
2354std::vector<uint64_t>
2355IndexCallsiteContextGraph::getStackIdsWithContextNodesForCall(IndexCall &Call) {
2357 CallStack<CallsiteInfo, SmallVector<unsigned>::const_iterator>
2358 CallsiteContext(dyn_cast_if_present<CallsiteInfo *>(Call));
2359 return getStackIdsWithContextNodes<CallsiteInfo,
2360 SmallVector<unsigned>::const_iterator>(
2361 CallsiteContext);
2362}
2363
2364template <typename DerivedCCG, typename FuncTy, typename CallTy>
2365template <class NodeT, class IteratorT>
2366std::vector<uint64_t>
2367CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::getStackIdsWithContextNodes(
2368 CallStack<NodeT, IteratorT> &CallsiteContext) {
2369 std::vector<uint64_t> StackIds;
2370 for (auto IdOrIndex : CallsiteContext) {
2371 auto StackId = getStackId(IdOrIndex);
2372 ContextNode *Node = getNodeForStackId(StackId);
2373 if (!Node)
2374 break;
2375 StackIds.push_back(StackId);
2376 }
2377 return StackIds;
2378}
2379
2380ModuleCallsiteContextGraph::ModuleCallsiteContextGraph(
2381 Module &M,
2382 llvm::function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter)
2383 : Mod(M), OREGetter(OREGetter) {
2384 // Map for keeping track of the largest cold contexts up to the number given
2385 // by MemProfTopNImportant. Must be a std::map (not DenseMap) because keys
2386 // must be sorted.
2387 std::map<uint64_t, uint32_t> TotalSizeToContextIdTopNCold;
2388 for (auto &F : M) {
2389 std::vector<CallInfo> CallsWithMetadata;
2390 for (auto &BB : F) {
2391 for (auto &I : BB) {
2392 if (!isa<CallBase>(I))
2393 continue;
2394 if (auto *MemProfMD = I.getMetadata(LLVMContext::MD_memprof)) {
2395 CallsWithMetadata.push_back(&I);
2396 auto *AllocNode = addAllocNode(&I, &F);
2397 auto *CallsiteMD = I.getMetadata(LLVMContext::MD_callsite);
2398 assert(CallsiteMD);
2399 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(CallsiteMD);
2400 // Add all of the MIBs and their stack nodes.
2401 for (auto &MDOp : MemProfMD->operands()) {
2402 auto *MIBMD = cast<const MDNode>(MDOp);
2403 std::vector<ContextTotalSize> ContextSizeInfo;
2404 // Collect the context size information if it exists.
2405 if (MIBMD->getNumOperands() > 2) {
2406 for (unsigned I = 2; I < MIBMD->getNumOperands(); I++) {
2407 MDNode *ContextSizePair =
2408 dyn_cast<MDNode>(MIBMD->getOperand(I));
2409 assert(ContextSizePair->getNumOperands() == 2);
2411 ContextSizePair->getOperand(0))
2412 ->getZExtValue();
2414 ContextSizePair->getOperand(1))
2415 ->getZExtValue();
2416 ContextSizeInfo.push_back({FullStackId, TotalSize});
2417 }
2418 }
2422 addStackNodesForMIB<MDNode, MDNode::op_iterator>(
2423 AllocNode, StackContext, CallsiteContext,
2424 getMIBAllocType(MIBMD), ContextSizeInfo,
2425 TotalSizeToContextIdTopNCold);
2426 }
2427 // If exporting the graph to dot and an allocation id of interest was
2428 // specified, record all the context ids for this allocation node.
2429 if (ExportToDot && AllocNode->OrigStackOrAllocId == AllocIdForDot)
2430 DotAllocContextIds = AllocNode->getContextIds();
2431 assert(AllocNode->AllocTypes != (uint8_t)AllocationType::None);
2432 // Memprof and callsite metadata on memory allocations no longer
2433 // needed.
2434 I.setMetadata(LLVMContext::MD_memprof, nullptr);
2435 I.setMetadata(LLVMContext::MD_callsite, nullptr);
2436 }
2437 // For callsite metadata, add to list for this function for later use.
2438 else if (I.getMetadata(LLVMContext::MD_callsite)) {
2439 CallsWithMetadata.push_back(&I);
2440 }
2441 }
2442 }
2443 if (!CallsWithMetadata.empty())
2444 FuncToCallsWithMetadata[&F] = CallsWithMetadata;
2445 }
2446
2447 if (DumpCCG) {
2448 dbgs() << "CCG before updating call stack chains:\n";
2449 dbgs() << *this;
2450 }
2451
2452 if (ExportToDot)
2453 exportToDot("prestackupdate");
2454
2455 updateStackNodes();
2456
2457 if (ExportToDot)
2458 exportToDot("poststackupdate");
2459
2460 handleCallsitesWithMultipleTargets();
2461
2462 markBackedges();
2463
2464 // Strip off remaining callsite metadata, no longer needed.
2465 for (auto &FuncEntry : FuncToCallsWithMetadata)
2466 for (auto &Call : FuncEntry.second)
2467 Call.call()->setMetadata(LLVMContext::MD_callsite, nullptr);
2468}
2469
2470IndexCallsiteContextGraph::IndexCallsiteContextGraph(
2471 ModuleSummaryIndex &Index,
2473 isPrevailing)
2474 : Index(Index), isPrevailing(isPrevailing) {
2475 // Map for keeping track of the largest cold contexts up to the number given
2476 // by MemProfTopNImportant. Must be a std::map (not DenseMap) because keys
2477 // must be sorted.
2478 std::map<uint64_t, uint32_t> TotalSizeToContextIdTopNCold;
2479 for (auto &I : Index) {
2480 auto VI = Index.getValueInfo(I);
2481 for (auto &S : VI.getSummaryList()) {
2482 // We should only add the prevailing nodes. Otherwise we may try to clone
2483 // in a weak copy that won't be linked (and may be different than the
2484 // prevailing version).
2485 // We only keep the memprof summary on the prevailing copy now when
2486 // building the combined index, as a space optimization, however don't
2487 // rely on this optimization. The linker doesn't resolve local linkage
2488 // values so don't check whether those are prevailing.
2489 if (!GlobalValue::isLocalLinkage(S->linkage()) &&
2490 !isPrevailing(VI.getGUID(), S.get()))
2491 continue;
2492 auto *FS = dyn_cast<FunctionSummary>(S.get());
2493 if (!FS)
2494 continue;
2495 std::vector<CallInfo> CallsWithMetadata;
2496 if (!FS->allocs().empty()) {
2497 for (auto &AN : FS->mutableAllocs()) {
2498 // This can happen because of recursion elimination handling that
2499 // currently exists in ModuleSummaryAnalysis. Skip these for now.
2500 // We still added them to the summary because we need to be able to
2501 // correlate properly in applyImport in the backends.
2502 if (AN.MIBs.empty())
2503 continue;
2504 IndexCall AllocCall(&AN);
2505 CallsWithMetadata.push_back(AllocCall);
2506 auto *AllocNode = addAllocNode(AllocCall, FS);
2507 // Pass an empty CallStack to the CallsiteContext (second)
2508 // parameter, since for ThinLTO we already collapsed out the inlined
2509 // stack ids on the allocation call during ModuleSummaryAnalysis.
2511 EmptyContext;
2512 unsigned I = 0;
2514 AN.ContextSizeInfos.size() == AN.MIBs.size());
2515 // Now add all of the MIBs and their stack nodes.
2516 for (auto &MIB : AN.MIBs) {
2518 StackContext(&MIB);
2519 std::vector<ContextTotalSize> ContextSizeInfo;
2520 if (!AN.ContextSizeInfos.empty()) {
2521 for (auto [FullStackId, TotalSize] : AN.ContextSizeInfos[I])
2522 ContextSizeInfo.push_back({FullStackId, TotalSize});
2523 }
2524 addStackNodesForMIB<MIBInfo, SmallVector<unsigned>::const_iterator>(
2525 AllocNode, StackContext, EmptyContext, MIB.AllocType,
2526 ContextSizeInfo, TotalSizeToContextIdTopNCold);
2527 I++;
2528 }
2529 // If exporting the graph to dot and an allocation id of interest was
2530 // specified, record all the context ids for this allocation node.
2531 if (ExportToDot && AllocNode->OrigStackOrAllocId == AllocIdForDot)
2532 DotAllocContextIds = AllocNode->getContextIds();
2533 assert(AllocNode->AllocTypes != (uint8_t)AllocationType::None);
2534 // Initialize version 0 on the summary alloc node to the current alloc
2535 // type, unless it has both types in which case make it default, so
2536 // that in the case where we aren't able to clone the original version
2537 // always ends up with the default allocation behavior.
2538 AN.Versions[0] = (uint8_t)allocTypeToUse(AllocNode->AllocTypes);
2539 }
2540 }
2541 // For callsite metadata, add to list for this function for later use.
2542 if (!FS->callsites().empty())
2543 for (auto &SN : FS->mutableCallsites()) {
2544 IndexCall StackNodeCall(&SN);
2545 CallsWithMetadata.push_back(StackNodeCall);
2546 }
2547
2548 if (!CallsWithMetadata.empty())
2549 FuncToCallsWithMetadata[FS] = CallsWithMetadata;
2550
2551 if (!FS->allocs().empty() || !FS->callsites().empty())
2552 FSToVIMap[FS] = VI;
2553 }
2554 }
2555
2556 if (DumpCCG) {
2557 dbgs() << "CCG before updating call stack chains:\n";
2558 dbgs() << *this;
2559 }
2560
2561 if (ExportToDot)
2562 exportToDot("prestackupdate");
2563
2564 updateStackNodes();
2565
2566 if (ExportToDot)
2567 exportToDot("poststackupdate");
2568
2569 handleCallsitesWithMultipleTargets();
2570
2571 markBackedges();
2572}
2573
2574template <typename DerivedCCG, typename FuncTy, typename CallTy>
2575void CallsiteContextGraph<DerivedCCG, FuncTy,
2576 CallTy>::handleCallsitesWithMultipleTargets() {
2577 // Look for and workaround callsites that call multiple functions.
2578 // This can happen for indirect calls, which needs better handling, and in
2579 // more rare cases (e.g. macro expansion).
2580 // TODO: To fix this for indirect calls we will want to perform speculative
2581 // devirtualization using either the normal PGO info with ICP, or using the
2582 // information in the profiled MemProf contexts. We can do this prior to
2583 // this transformation for regular LTO, and for ThinLTO we can simulate that
2584 // effect in the summary and perform the actual speculative devirtualization
2585 // while cloning in the ThinLTO backend.
2586
2587 // Keep track of the new nodes synthesized for discovered tail calls missing
2588 // from the profiled contexts.
2589 MapVector<CallInfo, ContextNode *> TailCallToContextNodeMap;
2590
2591 std::vector<std::pair<CallInfo, ContextNode *>> NewCallToNode;
2592 for (auto &Entry : NonAllocationCallToContextNodeMap) {
2593 auto *Node = Entry.second;
2594 assert(Node->Clones.empty());
2595 // Check all node callees and see if in the same function.
2596 // We need to check all of the calls recorded in this Node, because in some
2597 // cases we may have had multiple calls with the same debug info calling
2598 // different callees. This can happen, for example, when an object is
2599 // constructed in the paramter list - the destructor call of the object has
2600 // the same debug info (line/col) as the call the object was passed to.
2601 // Here we will prune any that don't match all callee nodes.
2602 std::vector<CallInfo> AllCalls;
2603 AllCalls.reserve(Node->MatchingCalls.size() + 1);
2604 AllCalls.push_back(Node->Call);
2605 llvm::append_range(AllCalls, Node->MatchingCalls);
2606
2607 // First see if we can partition the calls by callee function, creating new
2608 // nodes to host each set of calls calling the same callees. This is
2609 // necessary for support indirect calls with ThinLTO, for which we
2610 // synthesized CallsiteInfo records for each target. They will all have the
2611 // same callsite stack ids and would be sharing a context node at this
2612 // point. We need to perform separate cloning for each, which will be
2613 // applied along with speculative devirtualization in the ThinLTO backends
2614 // as needed. Note this does not currently support looking through tail
2615 // calls, it is unclear if we need that for indirect call targets.
2616 // First partition calls by callee func. Map indexed by func, value is
2617 // struct with list of matching calls, assigned node.
2618 if (partitionCallsByCallee(Node, AllCalls, NewCallToNode))
2619 continue;
2620
2621 auto It = AllCalls.begin();
2622 // Iterate through the calls until we find the first that matches.
2623 for (; It != AllCalls.end(); ++It) {
2624 auto ThisCall = *It;
2625 bool Match = true;
2626 for (auto EI = Node->CalleeEdges.begin(); EI != Node->CalleeEdges.end();
2627 ++EI) {
2628 auto Edge = *EI;
2629 if (!Edge->Callee->hasCall())
2630 continue;
2631 assert(NodeToCallingFunc.count(Edge->Callee));
2632 // Check if the called function matches that of the callee node.
2633 if (!calleesMatch(ThisCall.call(), EI, TailCallToContextNodeMap)) {
2634 Match = false;
2635 break;
2636 }
2637 }
2638 // Found a call that matches the callee nodes, we can quit now.
2639 if (Match) {
2640 // If the first match is not the primary call on the Node, update it
2641 // now. We will update the list of matching calls further below.
2642 if (Node->Call != ThisCall) {
2643 Node->setCall(ThisCall);
2644 // We need to update the NonAllocationCallToContextNodeMap, but don't
2645 // want to do this during iteration over that map, so save the calls
2646 // that need updated entries.
2647 NewCallToNode.push_back({ThisCall, Node});
2648 }
2649 break;
2650 }
2651 }
2652 // We will update this list below (or leave it cleared if there was no
2653 // match found above).
2654 Node->MatchingCalls.clear();
2655 // If we hit the end of the AllCalls vector, no call matching the callee
2656 // nodes was found, clear the call information in the node.
2657 if (It == AllCalls.end()) {
2658 RemovedEdgesWithMismatchedCallees++;
2659 // Work around by setting Node to have a null call, so it gets
2660 // skipped during cloning. Otherwise assignFunctions will assert
2661 // because its data structures are not designed to handle this case.
2662 Node->setCall(CallInfo());
2663 continue;
2664 }
2665 // Now add back any matching calls that call the same function as the
2666 // matching primary call on Node.
2667 for (++It; It != AllCalls.end(); ++It) {
2668 auto ThisCall = *It;
2669 if (!sameCallee(Node->Call.call(), ThisCall.call()))
2670 continue;
2671 Node->MatchingCalls.push_back(ThisCall);
2672 }
2673 }
2674
2675 // Remove all mismatched nodes identified in the above loop from the node map
2676 // (checking whether they have a null call which is set above). For a
2677 // MapVector like NonAllocationCallToContextNodeMap it is much more efficient
2678 // to do the removal via remove_if than by individually erasing entries above.
2679 // Also remove any entries if we updated the node's primary call above.
2680 NonAllocationCallToContextNodeMap.remove_if([](const auto &it) {
2681 return !it.second->hasCall() || it.second->Call != it.first;
2682 });
2683
2684 // Add entries for any new primary calls recorded above.
2685 for (auto &[Call, Node] : NewCallToNode)
2686 NonAllocationCallToContextNodeMap[Call] = Node;
2687
2688 // Add the new nodes after the above loop so that the iteration is not
2689 // invalidated.
2690 for (auto &[Call, Node] : TailCallToContextNodeMap)
2691 NonAllocationCallToContextNodeMap[Call] = Node;
2692}
2693
2694template <typename DerivedCCG, typename FuncTy, typename CallTy>
2695bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::partitionCallsByCallee(
2696 ContextNode *Node, ArrayRef<CallInfo> AllCalls,
2697 std::vector<std::pair<CallInfo, ContextNode *>> &NewCallToNode) {
2698 // Struct to keep track of all the calls having the same callee function,
2699 // and the node we eventually assign to them. Eventually we will record the
2700 // context node assigned to this group of calls.
2701 struct CallsWithSameCallee {
2702 std::vector<CallInfo> Calls;
2703 ContextNode *Node = nullptr;
2704 };
2705
2706 // First partition calls by callee function. Build map from each function
2707 // to the list of matching calls.
2709 for (auto ThisCall : AllCalls) {
2710 auto *F = getCalleeFunc(ThisCall.call());
2711 if (F)
2712 CalleeFuncToCallInfo[F].Calls.push_back(ThisCall);
2713 }
2714
2715 // Next, walk through all callee edges. For each callee node, get its
2716 // containing function and see if it was recorded in the above map (meaning we
2717 // have at least one matching call). Build another map from each callee node
2718 // with a matching call to the structure instance created above containing all
2719 // the calls.
2721 for (const auto &Edge : Node->CalleeEdges) {
2722 if (!Edge->Callee->hasCall())
2723 continue;
2724 const FuncTy *ProfiledCalleeFunc = NodeToCallingFunc[Edge->Callee];
2725 if (CalleeFuncToCallInfo.contains(ProfiledCalleeFunc))
2726 CalleeNodeToCallInfo[Edge->Callee] =
2727 &CalleeFuncToCallInfo[ProfiledCalleeFunc];
2728 }
2729
2730 // If there are entries in the second map, then there were no matching
2731 // calls/callees, nothing to do here. Return so we can go to the handling that
2732 // looks through tail calls.
2733 if (CalleeNodeToCallInfo.empty())
2734 return false;
2735
2736 // Walk through all callee edges again. Any and all callee edges that didn't
2737 // match any calls (callee not in the CalleeNodeToCallInfo map) are moved to a
2738 // new caller node (UnmatchedCalleesNode) which gets a null call so that it is
2739 // ignored during cloning. If it is in the map, then we use the node recorded
2740 // in that entry (creating it if needed), and move the callee edge to it.
2741 // The first callee will use the original node instead of creating a new one.
2742 // Note that any of the original calls on this node (in AllCalls) that didn't
2743 // have a callee function automatically get dropped from the node as part of
2744 // this process.
2745 ContextNode *UnmatchedCalleesNode = nullptr;
2746 // Track whether we already assigned original node to a callee.
2747 bool UsedOrigNode = false;
2748 assert(NodeToCallingFunc[Node]);
2749 // Iterate over a copy of Node's callee edges, since we may need to remove
2750 // edges in moveCalleeEdgeToNewCaller, and this simplifies the handling and
2751 // makes it less error-prone.
2752 auto CalleeEdges = Node->CalleeEdges;
2753 for (auto &Edge : CalleeEdges) {
2754 if (!Edge->Callee->hasCall())
2755 continue;
2756
2757 // Will be updated below to point to whatever (caller) node this callee edge
2758 // should be moved to.
2759 ContextNode *CallerNodeToUse = nullptr;
2760
2761 // Handle the case where there were no matching calls first. Move this
2762 // callee edge to the UnmatchedCalleesNode, creating it if needed.
2763 if (!CalleeNodeToCallInfo.contains(Edge->Callee)) {
2764 if (!UnmatchedCalleesNode)
2765 UnmatchedCalleesNode =
2766 createNewNode(/*IsAllocation=*/false, NodeToCallingFunc[Node]);
2767 CallerNodeToUse = UnmatchedCalleesNode;
2768 } else {
2769 // Look up the information recorded for this callee node, and use the
2770 // recorded caller node (creating it if needed).
2771 auto *Info = CalleeNodeToCallInfo[Edge->Callee];
2772 if (!Info->Node) {
2773 // If we haven't assigned any callees to the original node use it.
2774 if (!UsedOrigNode) {
2775 Info->Node = Node;
2776 // Clear the set of matching calls which will be updated below.
2777 Node->MatchingCalls.clear();
2778 UsedOrigNode = true;
2779 } else
2780 Info->Node =
2781 createNewNode(/*IsAllocation=*/false, NodeToCallingFunc[Node]);
2782 assert(!Info->Calls.empty());
2783 // The first call becomes the primary call for this caller node, and the
2784 // rest go in the matching calls list.
2785 Info->Node->setCall(Info->Calls.front());
2786 llvm::append_range(Info->Node->MatchingCalls,
2787 llvm::drop_begin(Info->Calls));
2788 // Save the primary call to node correspondence so that we can update
2789 // the NonAllocationCallToContextNodeMap, which is being iterated in the
2790 // caller of this function.
2791 NewCallToNode.push_back({Info->Node->Call, Info->Node});
2792 }
2793 CallerNodeToUse = Info->Node;
2794 }
2795
2796 // Don't need to move edge if we are using the original node;
2797 if (CallerNodeToUse == Node)
2798 continue;
2799
2800 moveCalleeEdgeToNewCaller(Edge, CallerNodeToUse);
2801 }
2802 // Now that we are done moving edges, clean up any caller edges that ended
2803 // up with no type or context ids. During moveCalleeEdgeToNewCaller all
2804 // caller edges from Node are replicated onto the new callers, and it
2805 // simplifies the handling to leave them until we have moved all
2806 // edges/context ids.
2807 for (auto &I : CalleeNodeToCallInfo)
2808 removeNoneTypeCallerEdges(I.second->Node);
2809 if (UnmatchedCalleesNode)
2810 removeNoneTypeCallerEdges(UnmatchedCalleesNode);
2811 removeNoneTypeCallerEdges(Node);
2812
2813 return true;
2814}
2815
2816uint64_t ModuleCallsiteContextGraph::getStackId(uint64_t IdOrIndex) const {
2817 // In the Module (IR) case this is already the Id.
2818 return IdOrIndex;
2819}
2820
2821uint64_t IndexCallsiteContextGraph::getStackId(uint64_t IdOrIndex) const {
2822 // In the Index case this is an index into the stack id list in the summary
2823 // index, convert it to an Id.
2824 return Index.getStackIdAtIndex(IdOrIndex);
2825}
2826
2827template <typename DerivedCCG, typename FuncTy, typename CallTy>
2828bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::calleesMatch(
2829 CallTy Call, EdgeIter &EI,
2830 MapVector<CallInfo, ContextNode *> &TailCallToContextNodeMap) {
2831 auto Edge = *EI;
2832 const FuncTy *ProfiledCalleeFunc = NodeToCallingFunc[Edge->Callee];
2833 const FuncTy *CallerFunc = NodeToCallingFunc[Edge->Caller];
2834 // Will be populated in order of callee to caller if we find a chain of tail
2835 // calls between the profiled caller and callee.
2836 std::vector<std::pair<CallTy, FuncTy *>> FoundCalleeChain;
2837 if (!calleeMatchesFunc(Call, ProfiledCalleeFunc, CallerFunc,
2838 FoundCalleeChain))
2839 return false;
2840
2841 // The usual case where the profiled callee matches that of the IR/summary.
2842 if (FoundCalleeChain.empty())
2843 return true;
2844
2845 auto AddEdge = [Edge, &EI](ContextNode *Caller, ContextNode *Callee) {
2846 auto *CurEdge = Callee->findEdgeFromCaller(Caller);
2847 // If there is already an edge between these nodes, simply update it and
2848 // return.
2849 if (CurEdge) {
2850 CurEdge->ContextIds.insert_range(Edge->ContextIds);
2851 CurEdge->AllocTypes |= Edge->AllocTypes;
2852 return;
2853 }
2854 // Otherwise, create a new edge and insert it into the caller and callee
2855 // lists.
2856 auto NewEdge = std::make_shared<ContextEdge>(
2857 Callee, Caller, Edge->AllocTypes, Edge->ContextIds);
2858 Callee->CallerEdges.push_back(NewEdge);
2859 if (Caller == Edge->Caller) {
2860 // If we are inserting the new edge into the current edge's caller, insert
2861 // the new edge before the current iterator position, and then increment
2862 // back to the current edge.
2863 EI = Caller->CalleeEdges.insert(EI, NewEdge);
2864 ++EI;
2865 assert(*EI == Edge &&
2866 "Iterator position not restored after insert and increment");
2867 } else
2868 Caller->CalleeEdges.push_back(NewEdge);
2869 };
2870
2871 // Create new nodes for each found callee and connect in between the profiled
2872 // caller and callee.
2873 auto *CurCalleeNode = Edge->Callee;
2874 for (auto &[NewCall, Func] : FoundCalleeChain) {
2875 ContextNode *NewNode = nullptr;
2876 // First check if we have already synthesized a node for this tail call.
2877 if (TailCallToContextNodeMap.count(NewCall)) {
2878 NewNode = TailCallToContextNodeMap[NewCall];
2879 NewNode->AllocTypes |= Edge->AllocTypes;
2880 } else {
2881 FuncToCallsWithMetadata[Func].push_back({NewCall});
2882 // Create Node and record node info.
2883 NewNode = createNewNode(/*IsAllocation=*/false, Func, NewCall);
2884 TailCallToContextNodeMap[NewCall] = NewNode;
2885 NewNode->AllocTypes = Edge->AllocTypes;
2886 }
2887
2888 // Hook up node to its callee node
2889 AddEdge(NewNode, CurCalleeNode);
2890
2891 CurCalleeNode = NewNode;
2892 }
2893
2894 // Hook up edge's original caller to new callee node.
2895 AddEdge(Edge->Caller, CurCalleeNode);
2896
2897#ifndef NDEBUG
2898 // Save this because Edge's fields get cleared below when removed.
2899 auto *Caller = Edge->Caller;
2900#endif
2901
2902 // Remove old edge
2903 removeEdgeFromGraph(Edge.get(), &EI, /*CalleeIter=*/true);
2904
2905 // To simplify the increment of EI in the caller, subtract one from EI.
2906 // In the final AddEdge call we would have either added a new callee edge,
2907 // to Edge->Caller, or found an existing one. Either way we are guaranteed
2908 // that there is at least one callee edge.
2909 assert(!Caller->CalleeEdges.empty());
2910 --EI;
2911
2912 return true;
2913}
2914
2915bool ModuleCallsiteContextGraph::findProfiledCalleeThroughTailCalls(
2916 const Function *ProfiledCallee, Value *CurCallee, unsigned Depth,
2917 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain,
2918 bool &FoundMultipleCalleeChains) {
2919 // Stop recursive search if we have already explored the maximum specified
2920 // depth.
2922 return false;
2923
2924 auto SaveCallsiteInfo = [&](Instruction *Callsite, Function *F) {
2925 FoundCalleeChain.push_back({Callsite, F});
2926 };
2927
2928 auto *CalleeFunc = dyn_cast<Function>(CurCallee);
2929 if (!CalleeFunc) {
2930 auto *Alias = dyn_cast<GlobalAlias>(CurCallee);
2931 assert(Alias);
2932 CalleeFunc = dyn_cast<Function>(Alias->getAliasee());
2933 assert(CalleeFunc);
2934 }
2935
2936 // Look for tail calls in this function, and check if they either call the
2937 // profiled callee directly, or indirectly (via a recursive search).
2938 // Only succeed if there is a single unique tail call chain found between the
2939 // profiled caller and callee, otherwise we could perform incorrect cloning.
2940 bool FoundSingleCalleeChain = false;
2941 for (auto &BB : *CalleeFunc) {
2942 for (auto &I : BB) {
2943 auto *CB = dyn_cast<CallBase>(&I);
2944 if (!CB || !CB->isTailCall())
2945 continue;
2946 auto *CalledValue = CB->getCalledOperand();
2947 auto *CalledFunction = CB->getCalledFunction();
2948 if (CalledValue && !CalledFunction) {
2949 CalledValue = CalledValue->stripPointerCasts();
2950 // Stripping pointer casts can reveal a called function.
2951 CalledFunction = dyn_cast<Function>(CalledValue);
2952 }
2953 // Check if this is an alias to a function. If so, get the
2954 // called aliasee for the checks below.
2955 if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
2956 assert(!CalledFunction &&
2957 "Expected null called function in callsite for alias");
2958 CalledFunction = dyn_cast<Function>(GA->getAliaseeObject());
2959 }
2960 if (!CalledFunction)
2961 continue;
2962 if (CalledFunction == ProfiledCallee) {
2963 if (FoundSingleCalleeChain) {
2964 FoundMultipleCalleeChains = true;
2965 return false;
2966 }
2967 FoundSingleCalleeChain = true;
2968 FoundProfiledCalleeCount++;
2969 FoundProfiledCalleeDepth += Depth;
2970 if (Depth > FoundProfiledCalleeMaxDepth)
2971 FoundProfiledCalleeMaxDepth = Depth;
2972 SaveCallsiteInfo(&I, CalleeFunc);
2973 } else if (findProfiledCalleeThroughTailCalls(
2974 ProfiledCallee, CalledFunction, Depth + 1,
2975 FoundCalleeChain, FoundMultipleCalleeChains)) {
2976 // findProfiledCalleeThroughTailCalls should not have returned
2977 // true if FoundMultipleCalleeChains.
2978 assert(!FoundMultipleCalleeChains);
2979 if (FoundSingleCalleeChain) {
2980 FoundMultipleCalleeChains = true;
2981 return false;
2982 }
2983 FoundSingleCalleeChain = true;
2984 SaveCallsiteInfo(&I, CalleeFunc);
2985 } else if (FoundMultipleCalleeChains)
2986 return false;
2987 }
2988 }
2989
2990 return FoundSingleCalleeChain;
2991}
2992
2993const Function *ModuleCallsiteContextGraph::getCalleeFunc(Instruction *Call) {
2994 auto *CB = dyn_cast<CallBase>(Call);
2995 if (!CB->getCalledOperand() || CB->isIndirectCall())
2996 return nullptr;
2997 auto *CalleeVal = CB->getCalledOperand()->stripPointerCasts();
2998 auto *Alias = dyn_cast<GlobalAlias>(CalleeVal);
2999 if (Alias)
3000 return dyn_cast<Function>(Alias->getAliasee());
3001 return dyn_cast<Function>(CalleeVal);
3002}
3003
3004bool ModuleCallsiteContextGraph::calleeMatchesFunc(
3005 Instruction *Call, const Function *Func, const Function *CallerFunc,
3006 std::vector<std::pair<Instruction *, Function *>> &FoundCalleeChain) {
3007 auto *CB = dyn_cast<CallBase>(Call);
3008 if (!CB->getCalledOperand() || CB->isIndirectCall())
3009 return false;
3010 auto *CalleeVal = CB->getCalledOperand()->stripPointerCasts();
3011 auto *CalleeFunc = dyn_cast<Function>(CalleeVal);
3012 if (CalleeFunc == Func)
3013 return true;
3014 auto *Alias = dyn_cast<GlobalAlias>(CalleeVal);
3015 if (Alias && Alias->getAliasee() == Func)
3016 return true;
3017
3018 // Recursively search for the profiled callee through tail calls starting with
3019 // the actual Callee. The discovered tail call chain is saved in
3020 // FoundCalleeChain, and we will fixup the graph to include these callsites
3021 // after returning.
3022 // FIXME: We will currently redo the same recursive walk if we find the same
3023 // mismatched callee from another callsite. We can improve this with more
3024 // bookkeeping of the created chain of new nodes for each mismatch.
3025 unsigned Depth = 1;
3026 bool FoundMultipleCalleeChains = false;
3027 if (!findProfiledCalleeThroughTailCalls(Func, CalleeVal, Depth,
3028 FoundCalleeChain,
3029 FoundMultipleCalleeChains)) {
3030 LLVM_DEBUG(dbgs() << "Not found through unique tail call chain: "
3031 << Func->getName() << " from " << CallerFunc->getName()
3032 << " that actually called " << CalleeVal->getName()
3033 << (FoundMultipleCalleeChains
3034 ? " (found multiple possible chains)"
3035 : "")
3036 << "\n");
3037 if (FoundMultipleCalleeChains)
3038 FoundProfiledCalleeNonUniquelyCount++;
3039 return false;
3040 }
3041
3042 return true;
3043}
3044
3045bool ModuleCallsiteContextGraph::sameCallee(Instruction *Call1,
3046 Instruction *Call2) {
3047 auto *CB1 = cast<CallBase>(Call1);
3048 if (!CB1->getCalledOperand() || CB1->isIndirectCall())
3049 return false;
3050 auto *CalleeVal1 = CB1->getCalledOperand()->stripPointerCasts();
3051 auto *CalleeFunc1 = dyn_cast<Function>(CalleeVal1);
3052 auto *CB2 = cast<CallBase>(Call2);
3053 if (!CB2->getCalledOperand() || CB2->isIndirectCall())
3054 return false;
3055 auto *CalleeVal2 = CB2->getCalledOperand()->stripPointerCasts();
3056 auto *CalleeFunc2 = dyn_cast<Function>(CalleeVal2);
3057 return CalleeFunc1 == CalleeFunc2;
3058}
3059
3060bool IndexCallsiteContextGraph::findProfiledCalleeThroughTailCalls(
3061 ValueInfo ProfiledCallee, ValueInfo CurCallee, unsigned Depth,
3062 std::vector<std::pair<IndexCall, FunctionSummary *>> &FoundCalleeChain,
3063 bool &FoundMultipleCalleeChains) {
3064 // Stop recursive search if we have already explored the maximum specified
3065 // depth.
3067 return false;
3068
3069 auto CreateAndSaveCallsiteInfo = [&](ValueInfo Callee, FunctionSummary *FS) {
3070 // Make a CallsiteInfo for each discovered callee, if one hasn't already
3071 // been synthesized.
3072 if (!FunctionCalleesToSynthesizedCallsiteInfos.count(FS) ||
3073 !FunctionCalleesToSynthesizedCallsiteInfos[FS].count(Callee))
3074 // StackIds is empty (we don't have debug info available in the index for
3075 // these callsites)
3076 FunctionCalleesToSynthesizedCallsiteInfos[FS][Callee] =
3077 std::make_unique<CallsiteInfo>(Callee, SmallVector<unsigned>());
3078 CallsiteInfo *NewCallsiteInfo =
3079 FunctionCalleesToSynthesizedCallsiteInfos[FS][Callee].get();
3080 FoundCalleeChain.push_back({NewCallsiteInfo, FS});
3081 };
3082
3083 // Look for tail calls in this function, and check if they either call the
3084 // profiled callee directly, or indirectly (via a recursive search).
3085 // Only succeed if there is a single unique tail call chain found between the
3086 // profiled caller and callee, otherwise we could perform incorrect cloning.
3087 bool FoundSingleCalleeChain = false;
3088 for (auto &S : CurCallee.getSummaryList()) {
3089 if (!GlobalValue::isLocalLinkage(S->linkage()) &&
3090 !isPrevailing(CurCallee.getGUID(), S.get()))
3091 continue;
3092 auto *FS = dyn_cast<FunctionSummary>(S->getBaseObject());
3093 if (!FS)
3094 continue;
3095 auto FSVI = CurCallee;
3096 auto *AS = dyn_cast<AliasSummary>(S.get());
3097 if (AS)
3098 FSVI = AS->getAliaseeVI();
3099 for (auto &CallEdge : FS->calls()) {
3100 if (!CallEdge.second.hasTailCall())
3101 continue;
3102 if (CallEdge.first == ProfiledCallee) {
3103 if (FoundSingleCalleeChain) {
3104 FoundMultipleCalleeChains = true;
3105 return false;
3106 }
3107 FoundSingleCalleeChain = true;
3108 FoundProfiledCalleeCount++;
3109 FoundProfiledCalleeDepth += Depth;
3110 if (Depth > FoundProfiledCalleeMaxDepth)
3111 FoundProfiledCalleeMaxDepth = Depth;
3112 CreateAndSaveCallsiteInfo(CallEdge.first, FS);
3113 // Add FS to FSToVIMap in case it isn't already there.
3114 assert(!FSToVIMap.count(FS) || FSToVIMap[FS] == FSVI);
3115 FSToVIMap[FS] = FSVI;
3116 } else if (findProfiledCalleeThroughTailCalls(
3117 ProfiledCallee, CallEdge.first, Depth + 1,
3118 FoundCalleeChain, FoundMultipleCalleeChains)) {
3119 // findProfiledCalleeThroughTailCalls should not have returned
3120 // true if FoundMultipleCalleeChains.
3121 assert(!FoundMultipleCalleeChains);
3122 if (FoundSingleCalleeChain) {
3123 FoundMultipleCalleeChains = true;
3124 return false;
3125 }
3126 FoundSingleCalleeChain = true;
3127 CreateAndSaveCallsiteInfo(CallEdge.first, FS);
3128 // Add FS to FSToVIMap in case it isn't already there.
3129 assert(!FSToVIMap.count(FS) || FSToVIMap[FS] == FSVI);
3130 FSToVIMap[FS] = FSVI;
3131 } else if (FoundMultipleCalleeChains)
3132 return false;
3133 }
3134 }
3135
3136 return FoundSingleCalleeChain;
3137}
3138
3139const FunctionSummary *
3140IndexCallsiteContextGraph::getCalleeFunc(IndexCall &Call) {
3141 ValueInfo Callee = dyn_cast_if_present<CallsiteInfo *>(Call)->Callee;
3142 if (Callee.getSummaryList().empty())
3143 return nullptr;
3144 return dyn_cast<FunctionSummary>(Callee.getSummaryList()[0]->getBaseObject());
3145}
3146
3147bool IndexCallsiteContextGraph::calleeMatchesFunc(
3148 IndexCall &Call, const FunctionSummary *Func,
3149 const FunctionSummary *CallerFunc,
3150 std::vector<std::pair<IndexCall, FunctionSummary *>> &FoundCalleeChain) {
3151 ValueInfo Callee = dyn_cast_if_present<CallsiteInfo *>(Call)->Callee;
3152 // If there is no summary list then this is a call to an externally defined
3153 // symbol.
3154 AliasSummary *Alias =
3155 Callee.getSummaryList().empty()
3156 ? nullptr
3157 : dyn_cast<AliasSummary>(Callee.getSummaryList()[0].get());
3158 assert(FSToVIMap.count(Func));
3159 auto FuncVI = FSToVIMap[Func];
3160 if (Callee == FuncVI ||
3161 // If callee is an alias, check the aliasee, since only function
3162 // summary base objects will contain the stack node summaries and thus
3163 // get a context node.
3164 (Alias && Alias->getAliaseeVI() == FuncVI))
3165 return true;
3166
3167 // Recursively search for the profiled callee through tail calls starting with
3168 // the actual Callee. The discovered tail call chain is saved in
3169 // FoundCalleeChain, and we will fixup the graph to include these callsites
3170 // after returning.
3171 // FIXME: We will currently redo the same recursive walk if we find the same
3172 // mismatched callee from another callsite. We can improve this with more
3173 // bookkeeping of the created chain of new nodes for each mismatch.
3174 unsigned Depth = 1;
3175 bool FoundMultipleCalleeChains = false;
3176 if (!findProfiledCalleeThroughTailCalls(
3177 FuncVI, Callee, Depth, FoundCalleeChain, FoundMultipleCalleeChains)) {
3178 LLVM_DEBUG(dbgs() << "Not found through unique tail call chain: " << FuncVI
3179 << " from " << FSToVIMap[CallerFunc]
3180 << " that actually called " << Callee
3181 << (FoundMultipleCalleeChains
3182 ? " (found multiple possible chains)"
3183 : "")
3184 << "\n");
3185 if (FoundMultipleCalleeChains)
3186 FoundProfiledCalleeNonUniquelyCount++;
3187 return false;
3188 }
3189
3190 return true;
3191}
3192
3193bool IndexCallsiteContextGraph::sameCallee(IndexCall &Call1, IndexCall &Call2) {
3194 ValueInfo Callee1 = dyn_cast_if_present<CallsiteInfo *>(Call1)->Callee;
3195 ValueInfo Callee2 = dyn_cast_if_present<CallsiteInfo *>(Call2)->Callee;
3196 return Callee1 == Callee2;
3197}
3198
3199template <typename DerivedCCG, typename FuncTy, typename CallTy>
3200void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::dump()
3201 const {
3202 print(dbgs());
3203 dbgs() << "\n";
3204}
3205
3206template <typename DerivedCCG, typename FuncTy, typename CallTy>
3207void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode::print(
3208 raw_ostream &OS) const {
3209 OS << "Node " << this << "\n";
3210 OS << "\t";
3211 printCall(OS);
3212 if (Recursive)
3213 OS << " (recursive)";
3214 OS << "\n";
3215 if (!MatchingCalls.empty()) {
3216 OS << "\tMatchingCalls:\n";
3217 for (auto &MatchingCall : MatchingCalls) {
3218 OS << "\t";
3219 MatchingCall.print(OS);
3220 OS << "\n";
3221 }
3222 }
3223 OS << "\tNodeId: " << NodeId << "\n";
3224 OS << "\tAllocTypes: " << getAllocTypeString(AllocTypes) << "\n";
3225 OS << "\tContextIds:";
3226 // Make a copy of the computed context ids that we can sort for stability.
3227 auto ContextIds = getContextIds();
3228 std::vector<uint32_t> SortedIds(ContextIds.begin(), ContextIds.end());
3229 std::sort(SortedIds.begin(), SortedIds.end());
3230 for (auto Id : SortedIds)
3231 OS << " " << Id;
3232 OS << "\n";
3233 OS << "\tCalleeEdges:\n";
3234 for (auto &Edge : CalleeEdges)
3235 OS << "\t\t" << *Edge << " (Callee NodeId: " << Edge->Callee->NodeId
3236 << ")\n";
3237 OS << "\tCallerEdges:\n";
3238 for (auto &Edge : CallerEdges)
3239 OS << "\t\t" << *Edge << " (Caller NodeId: " << Edge->Caller->NodeId
3240 << ")\n";
3241 if (!Clones.empty()) {
3242 OS << "\tClones: ";
3243 bool First = true;
3244 for (auto *C : Clones) {
3245 if (!First)
3246 OS << ", ";
3247 First = false;
3248 OS << C << " NodeId: " << C->NodeId;
3249 }
3250 OS << "\n";
3251 } else if (CloneOf) {
3252 OS << "\tClone of " << CloneOf << " NodeId: " << CloneOf->NodeId << "\n";
3253 }
3254}
3255
3256template <typename DerivedCCG, typename FuncTy, typename CallTy>
3257void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge::dump()
3258 const {
3259 print(dbgs());
3260 dbgs() << "\n";
3261}
3262
3263template <typename DerivedCCG, typename FuncTy, typename CallTy>
3264void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextEdge::print(
3265 raw_ostream &OS) const {
3266 OS << "Edge from Callee " << Callee << " to Caller: " << Caller
3267 << (IsBackedge ? " (BE)" : "")
3268 << " AllocTypes: " << getAllocTypeString(AllocTypes);
3269 OS << " ContextIds:";
3270 std::vector<uint32_t> SortedIds(ContextIds.begin(), ContextIds.end());
3271 std::sort(SortedIds.begin(), SortedIds.end());
3272 for (auto Id : SortedIds)
3273 OS << " " << Id;
3274}
3275
3276template <typename DerivedCCG, typename FuncTy, typename CallTy>
3277void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::dump() const {
3278 print(dbgs());
3279}
3280
3281template <typename DerivedCCG, typename FuncTy, typename CallTy>
3282void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::print(
3283 raw_ostream &OS) const {
3284 OS << "Callsite Context Graph:\n";
3285 using GraphType = const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
3286 for (const auto Node : nodes<GraphType>(this)) {
3287 if (Node->isRemoved())
3288 continue;
3289 Node->print(OS);
3290 OS << "\n";
3291 }
3292}
3293
3294template <typename DerivedCCG, typename FuncTy, typename CallTy>
3295void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::printTotalSizes(
3296 raw_ostream &OS) const {
3297 using GraphType = const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
3298 for (const auto Node : nodes<GraphType>(this)) {
3299 if (Node->isRemoved())
3300 continue;
3301 if (!Node->IsAllocation)
3302 continue;
3303 DenseSet<uint32_t> ContextIds = Node->getContextIds();
3304 auto AllocTypeFromCall = getAllocationCallType(Node->Call);
3305 std::vector<uint32_t> SortedIds(ContextIds.begin(), ContextIds.end());
3306 std::sort(SortedIds.begin(), SortedIds.end());
3307 for (auto Id : SortedIds) {
3308 auto TypeI = ContextIdToAllocationType.find(Id);
3309 assert(TypeI != ContextIdToAllocationType.end());
3310 auto CSI = ContextIdToContextSizeInfos.find(Id);
3311 if (CSI != ContextIdToContextSizeInfos.end()) {
3312 for (auto &Info : CSI->second) {
3313 OS << "MemProf hinting: "
3314 << getAllocTypeString((uint8_t)TypeI->second)
3315 << " full allocation context " << Info.FullStackId
3316 << " with total size " << Info.TotalSize << " is "
3317 << getAllocTypeString(Node->AllocTypes) << " after cloning";
3318 if (allocTypeToUse(Node->AllocTypes) != AllocTypeFromCall)
3319 OS << " marked " << getAllocTypeString((uint8_t)AllocTypeFromCall)
3320 << " due to cold byte percent";
3321 // Print the internal context id to aid debugging and visualization.
3322 OS << " (context id " << Id << ")";
3323 OS << "\n";
3324 }
3325 }
3326 }
3327 }
3328}
3329
3330template <typename DerivedCCG, typename FuncTy, typename CallTy>
3331void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::check() const {
3332 using GraphType = const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
3333 for (const auto Node : nodes<GraphType>(this)) {
3334 checkNode<DerivedCCG, FuncTy, CallTy>(Node, /*CheckEdges=*/false);
3335 for (auto &Edge : Node->CallerEdges)
3337 }
3338}
3339
3340template <typename DerivedCCG, typename FuncTy, typename CallTy>
3341struct GraphTraits<const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *> {
3342 using GraphType = const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
3343 using NodeRef = const ContextNode<DerivedCCG, FuncTy, CallTy> *;
3344
3345 using NodePtrTy = std::unique_ptr<ContextNode<DerivedCCG, FuncTy, CallTy>>;
3346 static NodeRef getNode(const NodePtrTy &P) { return P.get(); }
3347
3350 decltype(&getNode)>;
3351
3353 return nodes_iterator(G->NodeOwner.begin(), &getNode);
3354 }
3355
3357 return nodes_iterator(G->NodeOwner.end(), &getNode);
3358 }
3359
3361 return G->NodeOwner.begin()->get();
3362 }
3363
3364 using EdgePtrTy = std::shared_ptr<ContextEdge<DerivedCCG, FuncTy, CallTy>>;
3365 static const ContextNode<DerivedCCG, FuncTy, CallTy> *
3367 return P->Callee;
3368 }
3369
3371 mapped_iterator<typename std::vector<std::shared_ptr<ContextEdge<
3372 DerivedCCG, FuncTy, CallTy>>>::const_iterator,
3373 decltype(&GetCallee)>;
3374
3376 return ChildIteratorType(N->CalleeEdges.begin(), &GetCallee);
3377 }
3378
3380 return ChildIteratorType(N->CalleeEdges.end(), &GetCallee);
3381 }
3382};
3383
3384template <typename DerivedCCG, typename FuncTy, typename CallTy>
3385struct DOTGraphTraits<const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *>
3386 : public DefaultDOTGraphTraits {
3387 DOTGraphTraits(bool IsSimple = false) : DefaultDOTGraphTraits(IsSimple) {
3388 // If the user requested the full graph to be exported, but provided an
3389 // allocation id, or if the user gave a context id and requested more than
3390 // just a specific context to be exported, note that highlighting is
3391 // enabled.
3392 DoHighlight =
3393 (AllocIdForDot.getNumOccurrences() && DotGraphScope == DotScope::All) ||
3394 (ContextIdForDot.getNumOccurrences() &&
3396 }
3397
3398 using GraphType = const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *;
3400 using NodeRef = typename GTraits::NodeRef;
3401 using ChildIteratorType = typename GTraits::ChildIteratorType;
3402
3403 static std::string getNodeLabel(NodeRef Node, GraphType G) {
3404 std::string LabelString =
3405 (Twine("OrigId: ") + (Node->IsAllocation ? "Alloc" : "") +
3406 Twine(Node->OrigStackOrAllocId) + " NodeId: " + Twine(Node->NodeId))
3407 .str();
3408 LabelString += "\n";
3409 if (Node->hasCall()) {
3410 auto Func = G->NodeToCallingFunc.find(Node);
3411 assert(Func != G->NodeToCallingFunc.end());
3412 LabelString +=
3413 G->getLabel(Func->second, Node->Call.call(), Node->Call.cloneNo());
3414 } else {
3415 LabelString += "null call";
3416 if (Node->Recursive)
3417 LabelString += " (recursive)";
3418 else
3419 LabelString += " (external)";
3420 }
3421 return LabelString;
3422 }
3423
3425 auto ContextIds = Node->getContextIds();
3426 // If highlighting enabled, see if this node contains any of the context ids
3427 // of interest. If so, it will use a different color and a larger fontsize
3428 // (which makes the node larger as well).
3429 bool Highlight = false;
3430 if (DoHighlight) {
3431 assert(ContextIdForDot.getNumOccurrences() ||
3432 AllocIdForDot.getNumOccurrences());
3433 if (ContextIdForDot.getNumOccurrences())
3434 Highlight = ContextIds.contains(ContextIdForDot);
3435 else
3436 Highlight = set_intersects(ContextIds, G->DotAllocContextIds);
3437 }
3438 std::string AttributeString = (Twine("tooltip=\"") + getNodeId(Node) + " " +
3439 getContextIds(ContextIds) + "\"")
3440 .str();
3441 // Default fontsize is 14
3442 if (Highlight)
3443 AttributeString += ",fontsize=\"30\"";
3444 AttributeString +=
3445 (Twine(",fillcolor=\"") + getColor(Node->AllocTypes, Highlight) + "\"")
3446 .str();
3447 if (Node->CloneOf) {
3448 AttributeString += ",color=\"blue\"";
3449 AttributeString += ",style=\"filled,bold,dashed\"";
3450 } else
3451 AttributeString += ",style=\"filled\"";
3452 return AttributeString;
3453 }
3454
3455 static std::string getEdgeAttributes(NodeRef, ChildIteratorType ChildIter,
3456 GraphType G) {
3457 auto &Edge = *(ChildIter.getCurrent());
3458 // If highlighting enabled, see if this edge contains any of the context ids
3459 // of interest. If so, it will use a different color and a heavier arrow
3460 // size and weight (the larger weight makes the highlighted path
3461 // straighter).
3462 bool Highlight = false;
3463 if (DoHighlight) {
3464 assert(ContextIdForDot.getNumOccurrences() ||
3465 AllocIdForDot.getNumOccurrences());
3466 if (ContextIdForDot.getNumOccurrences())
3467 Highlight = Edge->ContextIds.contains(ContextIdForDot);
3468 else
3469 Highlight = set_intersects(Edge->ContextIds, G->DotAllocContextIds);
3470 }
3471 auto Color = getColor(Edge->AllocTypes, Highlight);
3472 std::string AttributeString =
3473 (Twine("tooltip=\"") + getContextIds(Edge->ContextIds) + "\"" +
3474 // fillcolor is the arrow head and color is the line
3475 Twine(",fillcolor=\"") + Color + "\"" + Twine(",color=\"") + Color +
3476 "\"")
3477 .str();
3478 if (Edge->IsBackedge)
3479 AttributeString += ",style=\"dotted\"";
3480 // Default penwidth and weight are both 1.
3481 if (Highlight)
3482 AttributeString += ",penwidth=\"2.0\",weight=\"2\"";
3483 return AttributeString;
3484 }
3485
3486 // Since the NodeOwners list includes nodes that are no longer connected to
3487 // the graph, skip them here.
3489 if (Node->isRemoved())
3490 return true;
3491 // If a scope smaller than the full graph was requested, see if this node
3492 // contains any of the context ids of interest.
3494 return !set_intersects(Node->getContextIds(), G->DotAllocContextIds);
3496 return !Node->getContextIds().contains(ContextIdForDot);
3497 return false;
3498 }
3499
3500private:
3501 static std::string getContextIds(const DenseSet<uint32_t> &ContextIds) {
3502 std::string IdString = "ContextIds:";
3503 if (ContextIds.size() < 100) {
3504 std::vector<uint32_t> SortedIds(ContextIds.begin(), ContextIds.end());
3505 std::sort(SortedIds.begin(), SortedIds.end());
3506 for (auto Id : SortedIds)
3507 IdString += (" " + Twine(Id)).str();
3508 } else {
3509 IdString += (" (" + Twine(ContextIds.size()) + " ids)").str();
3510 }
3511 return IdString;
3512 }
3513
3514 static std::string getColor(uint8_t AllocTypes, bool Highlight) {
3515 // If DoHighlight is not enabled, we want to use the highlight colors for
3516 // NotCold and Cold, and the non-highlight color for NotCold+Cold. This is
3517 // both compatible with the color scheme before highlighting was supported,
3518 // and for the NotCold+Cold color the non-highlight color is a bit more
3519 // readable.
3520 if (AllocTypes == (uint8_t)AllocationType::NotCold)
3521 // Color "brown1" actually looks like a lighter red.
3522 return !DoHighlight || Highlight ? "brown1" : "lightpink";
3523 if (AllocTypes == (uint8_t)AllocationType::Cold)
3524 return !DoHighlight || Highlight ? "cyan" : "lightskyblue";
3525 if (AllocTypes ==
3526 ((uint8_t)AllocationType::NotCold | (uint8_t)AllocationType::Cold))
3527 return Highlight ? "magenta" : "mediumorchid1";
3528 return "gray";
3529 }
3530
3531 static std::string getNodeId(NodeRef Node) {
3532 std::stringstream SStream;
3533 SStream << std::hex << "N0x" << (unsigned long long)Node;
3534 std::string Result = SStream.str();
3535 return Result;
3536 }
3537
3538 // True if we should highlight a specific context or allocation's contexts in
3539 // the emitted graph.
3540 static bool DoHighlight;
3541};
3542
3543template <typename DerivedCCG, typename FuncTy, typename CallTy>
3544bool DOTGraphTraits<
3545 const CallsiteContextGraph<DerivedCCG, FuncTy, CallTy> *>::DoHighlight =
3546 false;
3547
3548template <typename DerivedCCG, typename FuncTy, typename CallTy>
3549void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::exportToDot(
3550 std::string Label) const {
3551 WriteGraph(this, "", false, Label,
3552 DotFilePathPrefix + "ccg." + Label + ".dot");
3553}
3554
3555template <typename DerivedCCG, typename FuncTy, typename CallTy>
3556typename CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::ContextNode *
3557CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::moveEdgeToNewCalleeClone(
3558 const std::shared_ptr<ContextEdge> &Edge,
3559 DenseSet<uint32_t> ContextIdsToMove) {
3560 ContextNode *Node = Edge->Callee;
3561 assert(NodeToCallingFunc.count(Node));
3562 ContextNode *Clone =
3563 createNewNode(Node->IsAllocation, NodeToCallingFunc[Node], Node->Call);
3564 Node->addClone(Clone);
3565 Clone->MatchingCalls = Node->MatchingCalls;
3566 moveEdgeToExistingCalleeClone(Edge, Clone, /*NewClone=*/true,
3567 ContextIdsToMove);
3568 return Clone;
3569}
3570
3571template <typename DerivedCCG, typename FuncTy, typename CallTy>
3572void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
3573 moveEdgeToExistingCalleeClone(const std::shared_ptr<ContextEdge> &Edge,
3574 ContextNode *NewCallee, bool NewClone,
3575 DenseSet<uint32_t> ContextIdsToMove) {
3576 // NewCallee and Edge's current callee must be clones of the same original
3577 // node (Edge's current callee may be the original node too).
3578 assert(NewCallee->getOrigNode() == Edge->Callee->getOrigNode());
3579
3580 bool EdgeIsRecursive = Edge->Callee == Edge->Caller;
3581
3582 ContextNode *OldCallee = Edge->Callee;
3583
3584 // We might already have an edge to the new callee from earlier cloning for a
3585 // different allocation. If one exists we will reuse it.
3586 auto ExistingEdgeToNewCallee = NewCallee->findEdgeFromCaller(Edge->Caller);
3587
3588 // Callers will pass an empty ContextIdsToMove set when they want to move the
3589 // edge. Copy in Edge's ids for simplicity.
3590 if (ContextIdsToMove.empty())
3591 ContextIdsToMove = Edge->getContextIds();
3592
3593 // If we are moving all of Edge's ids, then just move the whole Edge.
3594 // Otherwise only move the specified subset, to a new edge if needed.
3595 if (Edge->getContextIds().size() == ContextIdsToMove.size()) {
3596 // First, update the alloc types on New Callee from Edge.
3597 // Do this before we potentially clear Edge's fields below!
3598 NewCallee->AllocTypes |= Edge->AllocTypes;
3599 // Moving the whole Edge.
3600 if (ExistingEdgeToNewCallee) {
3601 // Since we already have an edge to NewCallee, simply move the ids
3602 // onto it, and remove the existing Edge.
3603 ExistingEdgeToNewCallee->getContextIds().insert_range(ContextIdsToMove);
3604 ExistingEdgeToNewCallee->AllocTypes |= Edge->AllocTypes;
3605 assert(Edge->ContextIds == ContextIdsToMove);
3606 removeEdgeFromGraph(Edge.get());
3607 } else {
3608 // Otherwise just reconnect Edge to NewCallee.
3609 Edge->Callee = NewCallee;
3610 NewCallee->CallerEdges.push_back(Edge);
3611 // Remove it from callee where it was previously connected.
3612 OldCallee->eraseCallerEdge(Edge.get());
3613 // Don't need to update Edge's context ids since we are simply
3614 // reconnecting it.
3615 }
3616 } else {
3617 // Only moving a subset of Edge's ids.
3618 // Compute the alloc type of the subset of ids being moved.
3619 auto CallerEdgeAllocType = computeAllocType(ContextIdsToMove);
3620 if (ExistingEdgeToNewCallee) {
3621 // Since we already have an edge to NewCallee, simply move the ids
3622 // onto it.
3623 ExistingEdgeToNewCallee->getContextIds().insert_range(ContextIdsToMove);
3624 ExistingEdgeToNewCallee->AllocTypes |= CallerEdgeAllocType;
3625 } else {
3626 // Otherwise, create a new edge to NewCallee for the ids being moved.
3627 auto NewEdge = std::make_shared<ContextEdge>(
3628 NewCallee, Edge->Caller, CallerEdgeAllocType, ContextIdsToMove);
3629 Edge->Caller->CalleeEdges.push_back(NewEdge);
3630 NewCallee->CallerEdges.push_back(NewEdge);
3631 }
3632 // In either case, need to update the alloc types on NewCallee, and remove
3633 // those ids and update the alloc type on the original Edge.
3634 NewCallee->AllocTypes |= CallerEdgeAllocType;
3635 set_subtract(Edge->ContextIds, ContextIdsToMove);
3636 Edge->AllocTypes = computeAllocType(Edge->ContextIds);
3637 }
3638 // Now walk the old callee node's callee edges and move Edge's context ids
3639 // over to the corresponding edge into the clone (which is created here if
3640 // this is a newly created clone).
3641 for (auto &OldCalleeEdge : OldCallee->CalleeEdges) {
3642 ContextNode *CalleeToUse = OldCalleeEdge->Callee;
3643 // If this is a direct recursion edge, use NewCallee (the clone) as the
3644 // callee as well, so that any edge updated/created here is also direct
3645 // recursive.
3646 if (CalleeToUse == OldCallee) {
3647 // If this is a recursive edge, see if we already moved a recursive edge
3648 // (which would have to have been this one) - if we were only moving a
3649 // subset of context ids it would still be on OldCallee.
3650 if (EdgeIsRecursive) {
3651 assert(OldCalleeEdge == Edge);
3652 continue;
3653 }
3654 CalleeToUse = NewCallee;
3655 }
3656 // The context ids moving to the new callee are the subset of this edge's
3657 // context ids and the context ids on the caller edge being moved.
3658 DenseSet<uint32_t> EdgeContextIdsToMove =
3659 set_intersection(OldCalleeEdge->getContextIds(), ContextIdsToMove);
3660 set_subtract(OldCalleeEdge->getContextIds(), EdgeContextIdsToMove);
3661 OldCalleeEdge->AllocTypes =
3662 computeAllocType(OldCalleeEdge->getContextIds());
3663 if (!NewClone) {
3664 // Update context ids / alloc type on corresponding edge to NewCallee.
3665 // There is a chance this may not exist if we are reusing an existing
3666 // clone, specifically during function assignment, where we would have
3667 // removed none type edges after creating the clone. If we can't find
3668 // a corresponding edge there, fall through to the cloning below.
3669 if (auto *NewCalleeEdge = NewCallee->findEdgeFromCallee(CalleeToUse)) {
3670 NewCalleeEdge->getContextIds().insert_range(EdgeContextIdsToMove);
3671 NewCalleeEdge->AllocTypes |= computeAllocType(EdgeContextIdsToMove);
3672 continue;
3673 }
3674 }
3675 auto NewEdge = std::make_shared<ContextEdge>(
3676 CalleeToUse, NewCallee, computeAllocType(EdgeContextIdsToMove),
3677 EdgeContextIdsToMove);
3678 NewCallee->CalleeEdges.push_back(NewEdge);
3679 NewEdge->Callee->CallerEdges.push_back(NewEdge);
3680 }
3681 // Recompute the node alloc type now that its callee edges have been
3682 // updated (since we will compute from those edges).
3683 OldCallee->AllocTypes = OldCallee->computeAllocType();
3684 // OldCallee alloc type should be None iff its context id set is now empty.
3685 assert((OldCallee->AllocTypes == (uint8_t)AllocationType::None) ==
3686 OldCallee->emptyContextIds());
3687 if (VerifyCCG) {
3688 checkNode<DerivedCCG, FuncTy, CallTy>(OldCallee, /*CheckEdges=*/false);
3689 checkNode<DerivedCCG, FuncTy, CallTy>(NewCallee, /*CheckEdges=*/false);
3690 for (const auto &OldCalleeEdge : OldCallee->CalleeEdges)
3691 checkNode<DerivedCCG, FuncTy, CallTy>(OldCalleeEdge->Callee,
3692 /*CheckEdges=*/false);
3693 for (const auto &NewCalleeEdge : NewCallee->CalleeEdges)
3694 checkNode<DerivedCCG, FuncTy, CallTy>(NewCalleeEdge->Callee,
3695 /*CheckEdges=*/false);
3696 }
3697}
3698
3699template <typename DerivedCCG, typename FuncTy, typename CallTy>
3700void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
3701 moveCalleeEdgeToNewCaller(const std::shared_ptr<ContextEdge> &Edge,
3702 ContextNode *NewCaller) {
3703 auto *OldCallee = Edge->Callee;
3704 auto *NewCallee = OldCallee;
3705 // If this edge was direct recursive, make any new/updated edge also direct
3706 // recursive to NewCaller.
3707 bool Recursive = Edge->Caller == Edge->Callee;
3708 if (Recursive)
3709 NewCallee = NewCaller;
3710
3711 ContextNode *OldCaller = Edge->Caller;
3712 OldCaller->eraseCalleeEdge(Edge.get());
3713
3714 // We might already have an edge to the new caller. If one exists we will
3715 // reuse it.
3716 auto ExistingEdgeToNewCaller = NewCaller->findEdgeFromCallee(NewCallee);
3717
3718 if (ExistingEdgeToNewCaller) {
3719 // Since we already have an edge to NewCaller, simply move the ids
3720 // onto it, and remove the existing Edge.
3721 ExistingEdgeToNewCaller->getContextIds().insert_range(
3722 Edge->getContextIds());
3723 ExistingEdgeToNewCaller->AllocTypes |= Edge->AllocTypes;
3724 Edge->ContextIds.clear();
3725 Edge->AllocTypes = (uint8_t)AllocationType::None;
3726 OldCallee->eraseCallerEdge(Edge.get());
3727 } else {
3728 // Otherwise just reconnect Edge to NewCaller.
3729 Edge->Caller = NewCaller;
3730 NewCaller->CalleeEdges.push_back(Edge);
3731 if (Recursive) {
3732 assert(NewCallee == NewCaller);
3733 // In the case of (direct) recursive edges, we update the callee as well
3734 // so that it becomes recursive on the new caller.
3735 Edge->Callee = NewCallee;
3736 NewCallee->CallerEdges.push_back(Edge);
3737 OldCallee->eraseCallerEdge(Edge.get());
3738 }
3739 // Don't need to update Edge's context ids since we are simply
3740 // reconnecting it.
3741 }
3742 // In either case, need to update the alloc types on New Caller.
3743 NewCaller->AllocTypes |= Edge->AllocTypes;
3744
3745 // Now walk the old caller node's caller edges and move Edge's context ids
3746 // over to the corresponding edge into the node (which is created here if
3747 // this is a newly created node). We can tell whether this is a newly created
3748 // node by seeing if it has any caller edges yet.
3749#ifndef NDEBUG
3750 bool IsNewNode = NewCaller->CallerEdges.empty();
3751#endif
3752 // If we just moved a direct recursive edge, presumably its context ids should
3753 // also flow out of OldCaller via some other non-recursive callee edge. We
3754 // don't want to remove the recursive context ids from other caller edges yet,
3755 // otherwise the context ids get into an inconsistent state on OldCaller.
3756 // We will update these context ids on the non-recursive caller edge when and
3757 // if they are updated on the non-recursive callee.
3758 if (!Recursive) {
3759 for (auto &OldCallerEdge : OldCaller->CallerEdges) {
3760 auto OldCallerCaller = OldCallerEdge->Caller;
3761 // The context ids moving to the new caller are the subset of this edge's
3762 // context ids and the context ids on the callee edge being moved.
3763 DenseSet<uint32_t> EdgeContextIdsToMove = set_intersection(
3764 OldCallerEdge->getContextIds(), Edge->getContextIds());
3765 if (OldCaller == OldCallerCaller) {
3766 OldCallerCaller = NewCaller;
3767 // Don't actually move this one. The caller will move it directly via a
3768 // call to this function with this as the Edge if it is appropriate to
3769 // move to a diff node that has a matching callee (itself).
3770 continue;
3771 }
3772 set_subtract(OldCallerEdge->getContextIds(), EdgeContextIdsToMove);
3773 OldCallerEdge->AllocTypes =
3774 computeAllocType(OldCallerEdge->getContextIds());
3775 // In this function we expect that any pre-existing node already has edges
3776 // from the same callers as the old node. That should be true in the
3777 // current use case, where we will remove None-type edges after copying
3778 // over all caller edges from the callee.
3779 auto *ExistingCallerEdge = NewCaller->findEdgeFromCaller(OldCallerCaller);
3780 // Since we would have skipped caller edges when moving a direct recursive
3781 // edge, this may not hold true when recursive handling enabled.
3782 assert(IsNewNode || ExistingCallerEdge || AllowRecursiveCallsites);
3783 if (ExistingCallerEdge) {
3784 ExistingCallerEdge->getContextIds().insert_range(EdgeContextIdsToMove);
3785 ExistingCallerEdge->AllocTypes |=
3786 computeAllocType(EdgeContextIdsToMove);
3787 continue;
3788 }
3789 auto NewEdge = std::make_shared<ContextEdge>(
3790 NewCaller, OldCallerCaller, computeAllocType(EdgeContextIdsToMove),
3791 EdgeContextIdsToMove);
3792 NewCaller->CallerEdges.push_back(NewEdge);
3793 NewEdge->Caller->CalleeEdges.push_back(NewEdge);
3794 }
3795 }
3796 // Recompute the node alloc type now that its caller edges have been
3797 // updated (since we will compute from those edges).
3798 OldCaller->AllocTypes = OldCaller->computeAllocType();
3799 // OldCaller alloc type should be None iff its context id set is now empty.
3800 assert((OldCaller->AllocTypes == (uint8_t)AllocationType::None) ==
3801 OldCaller->emptyContextIds());
3802 if (VerifyCCG) {
3803 checkNode<DerivedCCG, FuncTy, CallTy>(OldCaller, /*CheckEdges=*/false);
3804 checkNode<DerivedCCG, FuncTy, CallTy>(NewCaller, /*CheckEdges=*/false);
3805 for (const auto &OldCallerEdge : OldCaller->CallerEdges)
3806 checkNode<DerivedCCG, FuncTy, CallTy>(OldCallerEdge->Caller,
3807 /*CheckEdges=*/false);
3808 for (const auto &NewCallerEdge : NewCaller->CallerEdges)
3809 checkNode<DerivedCCG, FuncTy, CallTy>(NewCallerEdge->Caller,
3810 /*CheckEdges=*/false);
3811 }
3812}
3813
3814template <typename DerivedCCG, typename FuncTy, typename CallTy>
3815void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
3816 recursivelyRemoveNoneTypeCalleeEdges(
3817 ContextNode *Node, DenseSet<const ContextNode *> &Visited) {
3818 auto Inserted = Visited.insert(Node);
3819 if (!Inserted.second)
3820 return;
3821
3822 removeNoneTypeCalleeEdges(Node);
3823
3824 for (auto *Clone : Node->Clones)
3825 recursivelyRemoveNoneTypeCalleeEdges(Clone, Visited);
3826
3827 // The recursive call may remove some of this Node's caller edges.
3828 // Iterate over a copy and skip any that were removed.
3829 auto CallerEdges = Node->CallerEdges;
3830 for (auto &Edge : CallerEdges) {
3831 // Skip any that have been removed by an earlier recursive call.
3832 if (Edge->isRemoved()) {
3833 assert(!is_contained(Node->CallerEdges, Edge));
3834 continue;
3835 }
3836 recursivelyRemoveNoneTypeCalleeEdges(Edge->Caller, Visited);
3837 }
3838}
3839
3840// This is the standard DFS based backedge discovery algorithm.
3841template <typename DerivedCCG, typename FuncTy, typename CallTy>
3842void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::markBackedges() {
3843 // If we are cloning recursive contexts, find and mark backedges from all root
3844 // callers, using the typical DFS based backedge analysis.
3846 return;
3847 DenseSet<const ContextNode *> Visited;
3848 DenseSet<const ContextNode *> CurrentStack;
3849 for (auto &Entry : NonAllocationCallToContextNodeMap) {
3850 auto *Node = Entry.second;
3851 if (Node->isRemoved())
3852 continue;
3853 // It is a root if it doesn't have callers.
3854 if (!Node->CallerEdges.empty())
3855 continue;
3856 markBackedges(Node, Visited, CurrentStack);
3857 assert(CurrentStack.empty());
3858 }
3859}
3860
3861// Recursive helper for above markBackedges method.
3862template <typename DerivedCCG, typename FuncTy, typename CallTy>
3863void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::markBackedges(
3864 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
3865 DenseSet<const ContextNode *> &CurrentStack) {
3866 auto I = Visited.insert(Node);
3867 // We should only call this for unvisited nodes.
3868 assert(I.second);
3869 (void)I;
3870 for (auto &CalleeEdge : Node->CalleeEdges) {
3871 auto *Callee = CalleeEdge->Callee;
3872 if (Visited.count(Callee)) {
3873 // Since this was already visited we need to check if it is currently on
3874 // the recursive stack in which case it is a backedge.
3875 if (CurrentStack.count(Callee))
3876 CalleeEdge->IsBackedge = true;
3877 continue;
3878 }
3879 CurrentStack.insert(Callee);
3880 markBackedges(Callee, Visited, CurrentStack);
3881 CurrentStack.erase(Callee);
3882 }
3883}
3884
3885template <typename DerivedCCG, typename FuncTy, typename CallTy>
3886void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::identifyClones() {
3887 DenseSet<const ContextNode *> Visited;
3888 for (auto &Entry : AllocationCallToContextNodeMap) {
3889 Visited.clear();
3890 identifyClones(Entry.second, Visited, Entry.second->getContextIds());
3891 }
3892 Visited.clear();
3893 for (auto &Entry : AllocationCallToContextNodeMap)
3894 recursivelyRemoveNoneTypeCalleeEdges(Entry.second, Visited);
3895 if (VerifyCCG)
3896 check();
3897}
3898
3899// helper function to check an AllocType is cold or notcold or both.
3906
3907template <typename DerivedCCG, typename FuncTy, typename CallTy>
3908void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::identifyClones(
3909 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
3910 const DenseSet<uint32_t> &AllocContextIds) {
3911 if (VerifyNodes)
3912 checkNode<DerivedCCG, FuncTy, CallTy>(Node, /*CheckEdges=*/false);
3913 assert(!Node->CloneOf);
3914
3915 // If Node as a null call, then either it wasn't found in the module (regular
3916 // LTO) or summary index (ThinLTO), or there were other conditions blocking
3917 // cloning (e.g. recursion, calls multiple targets, etc).
3918 // Do this here so that we don't try to recursively clone callers below, which
3919 // isn't useful at least for this node.
3920 if (!Node->hasCall())
3921 return;
3922
3923 // No need to look at any callers if allocation type already unambiguous.
3924 if (hasSingleAllocType(Node->AllocTypes))
3925 return;
3926
3927#ifndef NDEBUG
3928 auto Insert =
3929#endif
3930 Visited.insert(Node);
3931 // We should not have visited this node yet.
3932 assert(Insert.second);
3933 // The recursive call to identifyClones may delete the current edge from the
3934 // CallerEdges vector. Make a copy and iterate on that, simpler than passing
3935 // in an iterator and having recursive call erase from it. Other edges may
3936 // also get removed during the recursion, which will have null Callee and
3937 // Caller pointers (and are deleted later), so we skip those below.
3938 {
3939 auto CallerEdges = Node->CallerEdges;
3940 for (auto &Edge : CallerEdges) {
3941 // Skip any that have been removed by an earlier recursive call.
3942 if (Edge->isRemoved()) {
3943 assert(!is_contained(Node->CallerEdges, Edge));
3944 continue;
3945 }
3946 // Defer backedges. See comments further below where these edges are
3947 // handled during the cloning of this Node.
3948 if (Edge->IsBackedge) {
3949 // We should only mark these if cloning recursive contexts, where we
3950 // need to do this deferral.
3952 continue;
3953 }
3954 // Ignore any caller we previously visited via another edge.
3955 if (!Visited.count(Edge->Caller) && !Edge->Caller->CloneOf) {
3956 identifyClones(Edge->Caller, Visited, AllocContextIds);
3957 }
3958 }
3959 }
3960
3961 // Check if we reached an unambiguous call or have have only a single caller.
3962 if (hasSingleAllocType(Node->AllocTypes) || Node->CallerEdges.size() <= 1)
3963 return;
3964
3965 // We need to clone.
3966
3967 // Try to keep the original version as alloc type NotCold. This will make
3968 // cases with indirect calls or any other situation with an unknown call to
3969 // the original function get the default behavior. We do this by sorting the
3970 // CallerEdges of the Node we will clone by alloc type.
3971 //
3972 // Give NotCold edge the lowest sort priority so those edges are at the end of
3973 // the caller edges vector, and stay on the original version (since the below
3974 // code clones greedily until it finds all remaining edges have the same type
3975 // and leaves the remaining ones on the original Node).
3976 //
3977 // We shouldn't actually have any None type edges, so the sorting priority for
3978 // that is arbitrary, and we assert in that case below.
3979 const unsigned AllocTypeCloningPriority[] = {/*None*/ 3, /*NotCold*/ 4,
3980 /*Cold*/ 1,
3981 /*NotColdCold*/ 2};
3982 llvm::stable_sort(Node->CallerEdges,
3983 [&](const std::shared_ptr<ContextEdge> &A,
3984 const std::shared_ptr<ContextEdge> &B) {
3985 // Nodes with non-empty context ids should be sorted
3986 // before those with empty context ids.
3987 if (A->ContextIds.empty())
3988 // Either B ContextIds are non-empty (in which case we
3989 // should return false because B < A), or B ContextIds
3990 // are empty, in which case they are equal, and we
3991 // should maintain the original relative ordering.
3992 return false;
3993 if (B->ContextIds.empty())
3994 return true;
3995
3996 if (A->AllocTypes == B->AllocTypes)
3997 // Use the first context id for each edge as a
3998 // tie-breaker.
3999 return *A->ContextIds.begin() < *B->ContextIds.begin();
4000 return AllocTypeCloningPriority[A->AllocTypes] <
4001 AllocTypeCloningPriority[B->AllocTypes];
4002 });
4003
4004 assert(Node->AllocTypes != (uint8_t)AllocationType::None);
4005
4006 DenseSet<uint32_t> RecursiveContextIds;
4008 // If we are allowing recursive callsites, but have also disabled recursive
4009 // contexts, look for context ids that show up in multiple caller edges.
4011 DenseSet<uint32_t> AllCallerContextIds;
4012 for (auto &CE : Node->CallerEdges) {
4013 // Resize to the largest set of caller context ids, since we know the
4014 // final set will be at least that large.
4015 AllCallerContextIds.reserve(CE->getContextIds().size());
4016 for (auto Id : CE->getContextIds())
4017 if (!AllCallerContextIds.insert(Id).second)
4018 RecursiveContextIds.insert(Id);
4019 }
4020 }
4021
4022 // Iterate until we find no more opportunities for disambiguating the alloc
4023 // types via cloning. In most cases this loop will terminate once the Node
4024 // has a single allocation type, in which case no more cloning is needed.
4025 // Iterate over a copy of Node's caller edges, since we may need to remove
4026 // edges in the moveEdgeTo* methods, and this simplifies the handling and
4027 // makes it less error-prone.
4028 auto CallerEdges = Node->CallerEdges;
4029 for (auto &CallerEdge : CallerEdges) {
4030 // Skip any that have been removed by an earlier recursive call.
4031 if (CallerEdge->isRemoved()) {
4032 assert(!is_contained(Node->CallerEdges, CallerEdge));
4033 continue;
4034 }
4035 assert(CallerEdge->Callee == Node);
4036
4037 // See if cloning the prior caller edge left this node with a single alloc
4038 // type or a single caller. In that case no more cloning of Node is needed.
4039 if (hasSingleAllocType(Node->AllocTypes) || Node->CallerEdges.size() <= 1)
4040 break;
4041
4042 // If the caller was not successfully matched to a call in the IR/summary,
4043 // there is no point in trying to clone for it as we can't update that call.
4044 if (!CallerEdge->Caller->hasCall())
4045 continue;
4046
4047 // Only need to process the ids along this edge pertaining to the given
4048 // allocation.
4049 auto CallerEdgeContextsForAlloc =
4050 set_intersection(CallerEdge->getContextIds(), AllocContextIds);
4051 if (!RecursiveContextIds.empty())
4052 CallerEdgeContextsForAlloc =
4053 set_difference(CallerEdgeContextsForAlloc, RecursiveContextIds);
4054 if (CallerEdgeContextsForAlloc.empty())
4055 continue;
4056
4057 auto CallerAllocTypeForAlloc = computeAllocType(CallerEdgeContextsForAlloc);
4058
4059 // Compute the node callee edge alloc types corresponding to the context ids
4060 // for this caller edge.
4061 std::vector<uint8_t> CalleeEdgeAllocTypesForCallerEdge;
4062 CalleeEdgeAllocTypesForCallerEdge.reserve(Node->CalleeEdges.size());
4063 for (auto &CalleeEdge : Node->CalleeEdges)
4064 CalleeEdgeAllocTypesForCallerEdge.push_back(intersectAllocTypes(
4065 CalleeEdge->getContextIds(), CallerEdgeContextsForAlloc));
4066
4067 // Don't clone if doing so will not disambiguate any alloc types amongst
4068 // caller edges (including the callee edges that would be cloned).
4069 // Otherwise we will simply move all edges to the clone.
4070 //
4071 // First check if by cloning we will disambiguate the caller allocation
4072 // type from node's allocation type. Query allocTypeToUse so that we don't
4073 // bother cloning to distinguish NotCold+Cold from NotCold. Note that
4074 // neither of these should be None type.
4075 //
4076 // Then check if by cloning node at least one of the callee edges will be
4077 // disambiguated by splitting out different context ids.
4078 //
4079 // However, always do the cloning if this is a backedge, in which case we
4080 // have not yet cloned along this caller edge.
4081 assert(CallerEdge->AllocTypes != (uint8_t)AllocationType::None);
4082 assert(Node->AllocTypes != (uint8_t)AllocationType::None);
4083 if (!CallerEdge->IsBackedge &&
4084 allocTypeToUse(CallerAllocTypeForAlloc) ==
4085 allocTypeToUse(Node->AllocTypes) &&
4086 allocTypesMatch<DerivedCCG, FuncTy, CallTy>(
4087 CalleeEdgeAllocTypesForCallerEdge, Node->CalleeEdges)) {
4088 continue;
4089 }
4090
4091 if (CallerEdge->IsBackedge) {
4092 // We should only mark these if cloning recursive contexts, where we
4093 // need to do this deferral.
4095 DeferredBackedges++;
4096 }
4097
4098 // If this is a backedge, we now do recursive cloning starting from its
4099 // caller since we may have moved unambiguous caller contexts to a clone
4100 // of this Node in a previous iteration of the current loop, giving more
4101 // opportunity for cloning through the backedge. Because we sorted the
4102 // caller edges earlier so that cold caller edges are first, we would have
4103 // visited and cloned this node for any unamibiguously cold non-recursive
4104 // callers before any ambiguous backedge callers. Note that we don't do this
4105 // if the caller is already cloned or visited during cloning (e.g. via a
4106 // different context path from the allocation).
4107 // TODO: Can we do better in the case where the caller was already visited?
4108 if (CallerEdge->IsBackedge && !CallerEdge->Caller->CloneOf &&
4109 !Visited.count(CallerEdge->Caller)) {
4110 const auto OrigIdCount = CallerEdge->getContextIds().size();
4111 // Now do the recursive cloning of this backedge's caller, which was
4112 // deferred earlier.
4113 identifyClones(CallerEdge->Caller, Visited, CallerEdgeContextsForAlloc);
4114 removeNoneTypeCalleeEdges(CallerEdge->Caller);
4115 // See if the recursive call to identifyClones moved the context ids to a
4116 // new edge from this node to a clone of caller, and switch to looking at
4117 // that new edge so that we clone Node for the new caller clone.
4118 bool UpdatedEdge = false;
4119 if (OrigIdCount > CallerEdge->getContextIds().size()) {
4120 for (auto E : Node->CallerEdges) {
4121 // Only interested in clones of the current edges caller.
4122 if (E->Caller->CloneOf != CallerEdge->Caller)
4123 continue;
4124 // See if this edge contains any of the context ids originally on the
4125 // current caller edge.
4126 auto CallerEdgeContextsForAllocNew =
4127 set_intersection(CallerEdgeContextsForAlloc, E->getContextIds());
4128 if (CallerEdgeContextsForAllocNew.empty())
4129 continue;
4130 // Make sure we don't pick a previously existing caller edge of this
4131 // Node, which would be processed on a different iteration of the
4132 // outer loop over the saved CallerEdges.
4133 if (llvm::is_contained(CallerEdges, E))
4134 continue;
4135 // The CallerAllocTypeForAlloc and CalleeEdgeAllocTypesForCallerEdge
4136 // are updated further below for all cases where we just invoked
4137 // identifyClones recursively.
4138 CallerEdgeContextsForAlloc.swap(CallerEdgeContextsForAllocNew);
4139 CallerEdge = E;
4140 UpdatedEdge = true;
4141 break;
4142 }
4143 }
4144 // If cloning removed this edge (and we didn't update it to a new edge
4145 // above), we're done with this edge. It's possible we moved all of the
4146 // context ids to an existing clone, in which case there's no need to do
4147 // further processing for them.
4148 if (CallerEdge->isRemoved())
4149 continue;
4150
4151 // Now we need to update the information used for the cloning decisions
4152 // further below, as we may have modified edges and their context ids.
4153
4154 // Note if we changed the CallerEdge above we would have already updated
4155 // the context ids.
4156 if (!UpdatedEdge) {
4157 CallerEdgeContextsForAlloc = set_intersection(
4158 CallerEdgeContextsForAlloc, CallerEdge->getContextIds());
4159 if (CallerEdgeContextsForAlloc.empty())
4160 continue;
4161 }
4162 // Update the other information that depends on the edges and on the now
4163 // updated CallerEdgeContextsForAlloc.
4164 CallerAllocTypeForAlloc = computeAllocType(CallerEdgeContextsForAlloc);
4165 CalleeEdgeAllocTypesForCallerEdge.clear();
4166 for (auto &CalleeEdge : Node->CalleeEdges) {
4167 CalleeEdgeAllocTypesForCallerEdge.push_back(intersectAllocTypes(
4168 CalleeEdge->getContextIds(), CallerEdgeContextsForAlloc));
4169 }
4170 }
4171
4172 // First see if we can use an existing clone. Check each clone and its
4173 // callee edges for matching alloc types.
4174 ContextNode *Clone = nullptr;
4175 for (auto *CurClone : Node->Clones) {
4176 if (allocTypeToUse(CurClone->AllocTypes) !=
4177 allocTypeToUse(CallerAllocTypeForAlloc))
4178 continue;
4179
4180 bool BothSingleAlloc = hasSingleAllocType(CurClone->AllocTypes) &&
4181 hasSingleAllocType(CallerAllocTypeForAlloc);
4182 // The above check should mean that if both have single alloc types that
4183 // they should be equal.
4184 assert(!BothSingleAlloc ||
4185 CurClone->AllocTypes == CallerAllocTypeForAlloc);
4186
4187 // If either both have a single alloc type (which are the same), or if the
4188 // clone's callee edges have the same alloc types as those for the current
4189 // allocation on Node's callee edges (CalleeEdgeAllocTypesForCallerEdge),
4190 // then we can reuse this clone.
4191 if (BothSingleAlloc || allocTypesMatchClone<DerivedCCG, FuncTy, CallTy>(
4192 CalleeEdgeAllocTypesForCallerEdge, CurClone)) {
4193 Clone = CurClone;
4194 break;
4195 }
4196 }
4197
4198 // The edge iterator is adjusted when we move the CallerEdge to the clone.
4199 if (Clone)
4200 moveEdgeToExistingCalleeClone(CallerEdge, Clone, /*NewClone=*/false,
4201 CallerEdgeContextsForAlloc);
4202 else
4203 Clone = moveEdgeToNewCalleeClone(CallerEdge, CallerEdgeContextsForAlloc);
4204
4205 // Sanity check that no alloc types on clone or its edges are None.
4206 assert(Clone->AllocTypes != (uint8_t)AllocationType::None);
4207 }
4208
4209 // We should still have some context ids on the original Node.
4210 assert(!Node->emptyContextIds());
4211
4212 // Sanity check that no alloc types on node or edges are None.
4213 assert(Node->AllocTypes != (uint8_t)AllocationType::None);
4214
4215 if (VerifyNodes)
4216 checkNode<DerivedCCG, FuncTy, CallTy>(Node, /*CheckEdges=*/false);
4217}
4218
4219void ModuleCallsiteContextGraph::updateAllocationCall(
4220 CallInfo &Call, AllocationType AllocType) {
4221 std::string AllocTypeString = getAllocTypeAttributeString(AllocType);
4223 auto A = llvm::Attribute::get(Call.call()->getFunction()->getContext(),
4224 "memprof", AllocTypeString);
4225 cast<CallBase>(Call.call())->addFnAttr(A);
4226 OREGetter(Call.call()->getFunction())
4227 .emit(OptimizationRemark(DEBUG_TYPE, "MemprofAttribute", Call.call())
4228 << ore::NV("AllocationCall", Call.call()) << " in clone "
4229 << ore::NV("Caller", Call.call()->getFunction())
4230 << " marked with memprof allocation attribute "
4231 << ore::NV("Attribute", AllocTypeString));
4232}
4233
4234void IndexCallsiteContextGraph::updateAllocationCall(CallInfo &Call,
4236 auto *AI = cast<AllocInfo *>(Call.call());
4237 assert(AI);
4238 assert(AI->Versions.size() > Call.cloneNo());
4239 AI->Versions[Call.cloneNo()] = (uint8_t)AllocType;
4240}
4241
4243ModuleCallsiteContextGraph::getAllocationCallType(const CallInfo &Call) const {
4244 const auto *CB = cast<CallBase>(Call.call());
4245 if (!CB->getAttributes().hasFnAttr("memprof"))
4246 return AllocationType::None;
4247 return CB->getAttributes().getFnAttr("memprof").getValueAsString() == "cold"
4248 ? AllocationType::Cold
4249 : AllocationType::NotCold;
4250}
4251
4253IndexCallsiteContextGraph::getAllocationCallType(const CallInfo &Call) const {
4254 const auto *AI = cast<AllocInfo *>(Call.call());
4255 assert(AI->Versions.size() > Call.cloneNo());
4256 return (AllocationType)AI->Versions[Call.cloneNo()];
4257}
4258
4259void ModuleCallsiteContextGraph::updateCall(CallInfo &CallerCall,
4260 FuncInfo CalleeFunc) {
4261 auto *CurF = getCalleeFunc(CallerCall.call());
4262 auto NewCalleeCloneNo = CalleeFunc.cloneNo();
4263 if (isMemProfClone(*CurF)) {
4264 // If we already assigned this callsite to call a specific non-default
4265 // clone (i.e. not the original function which is clone 0), ensure that we
4266 // aren't trying to now update it to call a different clone, which is
4267 // indicative of a bug in the graph or function assignment.
4268 auto CurCalleeCloneNo = getMemProfCloneNum(*CurF);
4269 if (CurCalleeCloneNo != NewCalleeCloneNo) {
4270 LLVM_DEBUG(dbgs() << "Mismatch in call clone assignment: was "
4271 << CurCalleeCloneNo << " now " << NewCalleeCloneNo
4272 << "\n");
4273 MismatchedCloneAssignments++;
4274 }
4275 }
4276 if (NewCalleeCloneNo > 0)
4277 cast<CallBase>(CallerCall.call())->setCalledFunction(CalleeFunc.func());
4278 OREGetter(CallerCall.call()->getFunction())
4279 .emit(OptimizationRemark(DEBUG_TYPE, "MemprofCall", CallerCall.call())
4280 << ore::NV("Call", CallerCall.call()) << " in clone "
4281 << ore::NV("Caller", CallerCall.call()->getFunction())
4282 << " assigned to call function clone "
4283 << ore::NV("Callee", CalleeFunc.func()));
4284}
4285
4286void IndexCallsiteContextGraph::updateCall(CallInfo &CallerCall,
4287 FuncInfo CalleeFunc) {
4288 auto *CI = cast<CallsiteInfo *>(CallerCall.call());
4289 assert(CI &&
4290 "Caller cannot be an allocation which should not have profiled calls");
4291 assert(CI->Clones.size() > CallerCall.cloneNo());
4292 auto NewCalleeCloneNo = CalleeFunc.cloneNo();
4293 auto &CurCalleeCloneNo = CI->Clones[CallerCall.cloneNo()];
4294 // If we already assigned this callsite to call a specific non-default
4295 // clone (i.e. not the original function which is clone 0), ensure that we
4296 // aren't trying to now update it to call a different clone, which is
4297 // indicative of a bug in the graph or function assignment.
4298 if (CurCalleeCloneNo != 0 && CurCalleeCloneNo != NewCalleeCloneNo) {
4299 LLVM_DEBUG(dbgs() << "Mismatch in call clone assignment: was "
4300 << CurCalleeCloneNo << " now " << NewCalleeCloneNo
4301 << "\n");
4302 MismatchedCloneAssignments++;
4303 }
4304 CurCalleeCloneNo = NewCalleeCloneNo;
4305}
4306
4307// Update the debug information attached to NewFunc to use the clone Name. Note
4308// this needs to be done for both any existing DISubprogram for the definition,
4309// as well as any separate declaration DISubprogram.
4311 assert(Name == NewFunc->getName());
4312 auto *SP = NewFunc->getSubprogram();
4313 if (!SP)
4314 return;
4315 auto *MDName = MDString::get(NewFunc->getParent()->getContext(), Name);
4316 SP->replaceLinkageName(MDName);
4317 DISubprogram *Decl = SP->getDeclaration();
4318 if (!Decl)
4319 return;
4320 TempDISubprogram NewDecl = Decl->clone();
4321 NewDecl->replaceLinkageName(MDName);
4322 SP->replaceDeclaration(MDNode::replaceWithUniqued(std::move(NewDecl)));
4323}
4324
4325CallsiteContextGraph<ModuleCallsiteContextGraph, Function,
4326 Instruction *>::FuncInfo
4327ModuleCallsiteContextGraph::cloneFunctionForCallsite(
4328 FuncInfo &Func, CallInfo &Call, DenseMap<CallInfo, CallInfo> &CallMap,
4329 std::vector<CallInfo> &CallsWithMetadataInFunc, unsigned CloneNo) {
4330 // Use existing LLVM facilities for cloning and obtaining Call in clone
4331 ValueToValueMapTy VMap;
4332 auto *NewFunc = CloneFunction(Func.func(), VMap);
4333 std::string Name = getMemProfFuncName(Func.func()->getName(), CloneNo);
4334 assert(!Func.func()->getParent()->getFunction(Name));
4335 NewFunc->setName(Name);
4336 updateSubprogramLinkageName(NewFunc, Name);
4337 for (auto &Inst : CallsWithMetadataInFunc) {
4338 // This map always has the initial version in it.
4339 assert(Inst.cloneNo() == 0);
4340 CallMap[Inst] = {cast<Instruction>(VMap[Inst.call()]), CloneNo};
4341 }
4342 OREGetter(Func.func())
4343 .emit(OptimizationRemark(DEBUG_TYPE, "MemprofClone", Func.func())
4344 << "created clone " << ore::NV("NewFunction", NewFunc));
4345 return {NewFunc, CloneNo};
4346}
4347
4348CallsiteContextGraph<IndexCallsiteContextGraph, FunctionSummary,
4349 IndexCall>::FuncInfo
4350IndexCallsiteContextGraph::cloneFunctionForCallsite(
4351 FuncInfo &Func, CallInfo &Call, DenseMap<CallInfo, CallInfo> &CallMap,
4352 std::vector<CallInfo> &CallsWithMetadataInFunc, unsigned CloneNo) {
4353 // Check how many clones we have of Call (and therefore function).
4354 // The next clone number is the current size of versions array.
4355 // Confirm this matches the CloneNo provided by the caller, which is based on
4356 // the number of function clones we have.
4357 assert(CloneNo == (isa<AllocInfo *>(Call.call())
4358 ? cast<AllocInfo *>(Call.call())->Versions.size()
4359 : cast<CallsiteInfo *>(Call.call())->Clones.size()));
4360 // Walk all the instructions in this function. Create a new version for
4361 // each (by adding an entry to the Versions/Clones summary array), and copy
4362 // over the version being called for the function clone being cloned here.
4363 // Additionally, add an entry to the CallMap for the new function clone,
4364 // mapping the original call (clone 0, what is in CallsWithMetadataInFunc)
4365 // to the new call clone.
4366 for (auto &Inst : CallsWithMetadataInFunc) {
4367 // This map always has the initial version in it.
4368 assert(Inst.cloneNo() == 0);
4369 if (auto *AI = dyn_cast<AllocInfo *>(Inst.call())) {
4370 assert(AI->Versions.size() == CloneNo);
4371 // We assign the allocation type later (in updateAllocationCall), just add
4372 // an entry for it here.
4373 AI->Versions.push_back(0);
4374 } else {
4375 auto *CI = cast<CallsiteInfo *>(Inst.call());
4376 assert(CI && CI->Clones.size() == CloneNo);
4377 // We assign the clone number later (in updateCall), just add an entry for
4378 // it here.
4379 CI->Clones.push_back(0);
4380 }
4381 CallMap[Inst] = {Inst.call(), CloneNo};
4382 }
4383 return {Func.func(), CloneNo};
4384}
4385
4386// We perform cloning for each allocation node separately. However, this
4387// sometimes results in a situation where the same node calls multiple
4388// clones of the same callee, created for different allocations. This
4389// causes issues when assigning functions to these clones, as each node can
4390// in reality only call a single callee clone.
4391//
4392// To address this, before assigning functions, merge callee clone nodes as
4393// needed using a post order traversal from the allocations. We attempt to
4394// use existing clones as the merge node when legal, and to share them
4395// among callers with the same properties (callers calling the same set of
4396// callee clone nodes for the same allocations).
4397//
4398// Without this fix, in some cases incorrect function assignment will lead
4399// to calling the wrong allocation clone.
4400template <typename DerivedCCG, typename FuncTy, typename CallTy>
4401void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::mergeClones() {
4402 if (!MergeClones)
4403 return;
4404
4405 // Generate a map from context id to the associated allocation node for use
4406 // when merging clones.
4407 DenseMap<uint32_t, ContextNode *> ContextIdToAllocationNode;
4408 for (auto &Entry : AllocationCallToContextNodeMap) {
4409 auto *Node = Entry.second;
4410 for (auto Id : Node->getContextIds())
4411 ContextIdToAllocationNode[Id] = Node->getOrigNode();
4412 for (auto *Clone : Node->Clones) {
4413 for (auto Id : Clone->getContextIds())
4414 ContextIdToAllocationNode[Id] = Clone->getOrigNode();
4415 }
4416 }
4417
4418 // Post order traversal starting from allocations to ensure each callsite
4419 // calls a single clone of its callee. Callee nodes that are clones of each
4420 // other are merged (via new merge nodes if needed) to achieve this.
4421 DenseSet<const ContextNode *> Visited;
4422 for (auto &Entry : AllocationCallToContextNodeMap) {
4423 auto *Node = Entry.second;
4424
4425 mergeClones(Node, Visited, ContextIdToAllocationNode);
4426
4427 // Make a copy so the recursive post order traversal that may create new
4428 // clones doesn't mess up iteration. Note that the recursive traversal
4429 // itself does not call mergeClones on any of these nodes, which are all
4430 // (clones of) allocations.
4431 auto Clones = Node->Clones;
4432 for (auto *Clone : Clones)
4433 mergeClones(Clone, Visited, ContextIdToAllocationNode);
4434 }
4435
4436 if (DumpCCG) {
4437 dbgs() << "CCG after merging:\n";
4438 dbgs() << *this;
4439 }
4440 if (ExportToDot)
4441 exportToDot("aftermerge");
4442
4443 if (VerifyCCG) {
4444 check();
4445 }
4446}
4447
4448// Recursive helper for above mergeClones method.
4449template <typename DerivedCCG, typename FuncTy, typename CallTy>
4450void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::mergeClones(
4451 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
4452 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode) {
4453 auto Inserted = Visited.insert(Node);
4454 if (!Inserted.second)
4455 return;
4456
4457 // Iteratively perform merging on this node to handle new caller nodes created
4458 // during the recursive traversal. We could do something more elegant such as
4459 // maintain a worklist, but this is a simple approach that doesn't cause a
4460 // measureable compile time effect, as most nodes don't have many caller
4461 // edges to check.
4462 bool FoundUnvisited = true;
4463 unsigned Iters = 0;
4464 while (FoundUnvisited) {
4465 Iters++;
4466 FoundUnvisited = false;
4467 // Make a copy since the recursive call may move a caller edge to a new
4468 // callee, messing up the iterator.
4469 auto CallerEdges = Node->CallerEdges;
4470 for (auto CallerEdge : CallerEdges) {
4471 // Skip any caller edge moved onto a different callee during recursion.
4472 if (CallerEdge->Callee != Node)
4473 continue;
4474 // If we found an unvisited caller, note that we should check the caller
4475 // edges again as mergeClones may add or change caller nodes.
4476 if (DoMergeIteration && !Visited.contains(CallerEdge->Caller))
4477 FoundUnvisited = true;
4478 mergeClones(CallerEdge->Caller, Visited, ContextIdToAllocationNode);
4479 }
4480 }
4481
4482 TotalMergeInvokes++;
4483 TotalMergeIters += Iters;
4484 if (Iters > MaxMergeIters)
4485 MaxMergeIters = Iters;
4486
4487 // Merge for this node after we handle its callers.
4488 mergeNodeCalleeClones(Node, Visited, ContextIdToAllocationNode);
4489}
4490
4491template <typename DerivedCCG, typename FuncTy, typename CallTy>
4492void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::mergeNodeCalleeClones(
4493 ContextNode *Node, DenseSet<const ContextNode *> &Visited,
4494 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode) {
4495 // Ignore Node if we moved all of its contexts to clones.
4496 if (Node->emptyContextIds())
4497 return;
4498
4499 // First identify groups of clones among Node's callee edges, by building
4500 // a map from each callee base node to the associated callee edges from Node.
4501 MapVector<ContextNode *, std::vector<std::shared_ptr<ContextEdge>>>
4502 OrigNodeToCloneEdges;
4503 for (const auto &E : Node->CalleeEdges) {
4504 auto *Callee = E->Callee;
4505 if (!Callee->CloneOf && Callee->Clones.empty())
4506 continue;
4507 ContextNode *Base = Callee->getOrigNode();
4508 OrigNodeToCloneEdges[Base].push_back(E);
4509 }
4510
4511 // Helper for callee edge sorting below. Return true if A's callee has fewer
4512 // caller edges than B, or if A is a clone and B is not, or if A's first
4513 // context id is smaller than B's.
4514 auto CalleeCallerEdgeLessThan = [](const std::shared_ptr<ContextEdge> &A,
4515 const std::shared_ptr<ContextEdge> &B) {
4516 if (A->Callee->CallerEdges.size() != B->Callee->CallerEdges.size())
4517 return A->Callee->CallerEdges.size() < B->Callee->CallerEdges.size();
4518 if (A->Callee->CloneOf && !B->Callee->CloneOf)
4519 return true;
4520 else if (!A->Callee->CloneOf && B->Callee->CloneOf)
4521 return false;
4522 // Use the first context id for each edge as a
4523 // tie-breaker.
4524 return *A->ContextIds.begin() < *B->ContextIds.begin();
4525 };
4526
4527 // Process each set of callee clones called by Node, performing the needed
4528 // merging.
4529 for (auto Entry : OrigNodeToCloneEdges) {
4530 // CalleeEdges is the set of edges from Node reaching callees that are
4531 // mutual clones of each other.
4532 auto &CalleeEdges = Entry.second;
4533 auto NumCalleeClones = CalleeEdges.size();
4534 // A single edge means there is no merging needed.
4535 if (NumCalleeClones == 1)
4536 continue;
4537 // Sort the CalleeEdges calling this group of clones in ascending order of
4538 // their caller edge counts, putting the original non-clone node first in
4539 // cases of a tie. This simplifies finding an existing node to use as the
4540 // merge node.
4541 llvm::stable_sort(CalleeEdges, CalleeCallerEdgeLessThan);
4542
4543 /// Find other callers of the given set of callee edges that can
4544 /// share the same callee merge node. See the comments at this method
4545 /// definition for details.
4546 DenseSet<ContextNode *> OtherCallersToShareMerge;
4547 findOtherCallersToShareMerge(Node, CalleeEdges, ContextIdToAllocationNode,
4548 OtherCallersToShareMerge);
4549
4550 // Now do the actual merging. Identify existing or create a new MergeNode
4551 // during the first iteration. Move each callee over, along with edges from
4552 // other callers we've determined above can share the same merge node.
4553 ContextNode *MergeNode = nullptr;
4554 DenseMap<ContextNode *, unsigned> CallerToMoveCount;
4555 for (auto CalleeEdge : CalleeEdges) {
4556 auto *OrigCallee = CalleeEdge->Callee;
4557 // If we don't have a MergeNode yet (only happens on the first iteration,
4558 // as a new one will be created when we go to move the first callee edge
4559 // over as needed), see if we can use this callee.
4560 if (!MergeNode) {
4561 // If there are no other callers, simply use this callee.
4562 if (CalleeEdge->Callee->CallerEdges.size() == 1) {
4563 MergeNode = OrigCallee;
4564 NonNewMergedNodes++;
4565 continue;
4566 }
4567 // Otherwise, if we have identified other caller nodes that can share
4568 // the merge node with Node, see if all of OrigCallee's callers are
4569 // going to share the same merge node. In that case we can use callee
4570 // (since all of its callers would move to the new merge node).
4571 if (!OtherCallersToShareMerge.empty()) {
4572 bool MoveAllCallerEdges = true;
4573 for (auto CalleeCallerE : OrigCallee->CallerEdges) {
4574 if (CalleeCallerE == CalleeEdge)
4575 continue;
4576 if (!OtherCallersToShareMerge.contains(CalleeCallerE->Caller)) {
4577 MoveAllCallerEdges = false;
4578 break;
4579 }
4580 }
4581 // If we are going to move all callers over, we can use this callee as
4582 // the MergeNode.
4583 if (MoveAllCallerEdges) {
4584 MergeNode = OrigCallee;
4585 NonNewMergedNodes++;
4586 continue;
4587 }
4588 }
4589 }
4590 // Move this callee edge, creating a new merge node if necessary.
4591 if (MergeNode) {
4592 assert(MergeNode != OrigCallee);
4593 moveEdgeToExistingCalleeClone(CalleeEdge, MergeNode,
4594 /*NewClone*/ false);
4595 } else {
4596 MergeNode = moveEdgeToNewCalleeClone(CalleeEdge);
4597 NewMergedNodes++;
4598 }
4599 // Now move all identified edges from other callers over to the merge node
4600 // as well.
4601 if (!OtherCallersToShareMerge.empty()) {
4602 // Make and iterate over a copy of OrigCallee's caller edges because
4603 // some of these will be moved off of the OrigCallee and that would mess
4604 // up the iteration from OrigCallee.
4605 auto OrigCalleeCallerEdges = OrigCallee->CallerEdges;
4606 for (auto &CalleeCallerE : OrigCalleeCallerEdges) {
4607 if (CalleeCallerE == CalleeEdge)
4608 continue;
4609 if (!OtherCallersToShareMerge.contains(CalleeCallerE->Caller))
4610 continue;
4611 CallerToMoveCount[CalleeCallerE->Caller]++;
4612 moveEdgeToExistingCalleeClone(CalleeCallerE, MergeNode,
4613 /*NewClone*/ false);
4614 }
4615 }
4616 removeNoneTypeCalleeEdges(OrigCallee);
4617 removeNoneTypeCalleeEdges(MergeNode);
4618 }
4619 }
4620}
4621
4622// Look for other nodes that have edges to the same set of callee
4623// clones as the current Node. Those can share the eventual merge node
4624// (reducing cloning and binary size overhead) iff:
4625// - they have edges to the same set of callee clones
4626// - each callee edge reaches a subset of the same allocations as Node's
4627// corresponding edge to the same callee clone.
4628// The second requirement is to ensure that we don't undo any of the
4629// necessary cloning to distinguish contexts with different allocation
4630// behavior.
4631// FIXME: This is somewhat conservative, as we really just need to ensure
4632// that they don't reach the same allocations as contexts on edges from Node
4633// going to any of the *other* callee clones being merged. However, that
4634// requires more tracking and checking to get right.
4635template <typename DerivedCCG, typename FuncTy, typename CallTy>
4636void CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::
4637 findOtherCallersToShareMerge(
4638 ContextNode *Node,
4639 std::vector<std::shared_ptr<ContextEdge>> &CalleeEdges,
4640 DenseMap<uint32_t, ContextNode *> &ContextIdToAllocationNode,
4641 DenseSet<ContextNode *> &OtherCallersToShareMerge) {
4642 auto NumCalleeClones = CalleeEdges.size();
4643 // This map counts how many edges to the same callee clone exist for other
4644 // caller nodes of each callee clone.
4645 DenseMap<ContextNode *, unsigned> OtherCallersToSharedCalleeEdgeCount;
4646 // Counts the number of other caller nodes that have edges to all callee
4647 // clones that don't violate the allocation context checking.
4648 unsigned PossibleOtherCallerNodes = 0;
4649
4650 // We only need to look at other Caller nodes if the first callee edge has
4651 // multiple callers (recall they are sorted in ascending order above).
4652 if (CalleeEdges[0]->Callee->CallerEdges.size() < 2)
4653 return;
4654
4655 // For each callee edge:
4656 // - Collect the count of other caller nodes calling the same callees.
4657 // - Collect the alloc nodes reached by contexts on each callee edge.
4658 DenseMap<ContextEdge *, DenseSet<ContextNode *>> CalleeEdgeToAllocNodes;
4659 for (auto CalleeEdge : CalleeEdges) {
4660 assert(CalleeEdge->Callee->CallerEdges.size() > 1);
4661 // For each other caller of the same callee, increment the count of
4662 // edges reaching the same callee clone.
4663 for (auto CalleeCallerEdges : CalleeEdge->Callee->CallerEdges) {
4664 if (CalleeCallerEdges->Caller == Node) {
4665 assert(CalleeCallerEdges == CalleeEdge);
4666 continue;
4667 }
4668 OtherCallersToSharedCalleeEdgeCount[CalleeCallerEdges->Caller]++;
4669 // If this caller edge now reaches all of the same callee clones,
4670 // increment the count of candidate other caller nodes.
4671 if (OtherCallersToSharedCalleeEdgeCount[CalleeCallerEdges->Caller] ==
4672 NumCalleeClones)
4673 PossibleOtherCallerNodes++;
4674 }
4675 // Collect the alloc nodes reached by contexts on each callee edge, for
4676 // later analysis.
4677 for (auto Id : CalleeEdge->getContextIds()) {
4678 auto *Alloc = ContextIdToAllocationNode.lookup(Id);
4679 if (!Alloc) {
4680 // FIXME: unclear why this happens occasionally, presumably
4681 // imperfect graph updates possibly with recursion.
4682 MissingAllocForContextId++;
4683 continue;
4684 }
4685 CalleeEdgeToAllocNodes[CalleeEdge.get()].insert(Alloc);
4686 }
4687 }
4688
4689 // Now walk the callee edges again, and make sure that for each candidate
4690 // caller node all of its edges to the callees reach the same allocs (or
4691 // a subset) as those along the corresponding callee edge from Node.
4692 for (auto CalleeEdge : CalleeEdges) {
4693 assert(CalleeEdge->Callee->CallerEdges.size() > 1);
4694 // Stop if we do not have any (more) candidate other caller nodes.
4695 if (!PossibleOtherCallerNodes)
4696 break;
4697 auto &CurCalleeAllocNodes = CalleeEdgeToAllocNodes[CalleeEdge.get()];
4698 // Check each other caller of this callee clone.
4699 for (auto &CalleeCallerE : CalleeEdge->Callee->CallerEdges) {
4700 // Not interested in the callee edge from Node itself.
4701 if (CalleeCallerE == CalleeEdge)
4702 continue;
4703 // Skip any callers that didn't have callee edges to all the same
4704 // callee clones.
4705 if (OtherCallersToSharedCalleeEdgeCount[CalleeCallerE->Caller] !=
4706 NumCalleeClones)
4707 continue;
4708 // Make sure that each context along edge from candidate caller node
4709 // reaches an allocation also reached by this callee edge from Node.
4710 for (auto Id : CalleeCallerE->getContextIds()) {
4711 auto *Alloc = ContextIdToAllocationNode.lookup(Id);
4712 if (!Alloc)
4713 continue;
4714 // If not, simply reset the map entry to 0 so caller is ignored, and
4715 // reduce the count of candidate other caller nodes.
4716 if (!CurCalleeAllocNodes.contains(Alloc)) {
4717 OtherCallersToSharedCalleeEdgeCount[CalleeCallerE->Caller] = 0;
4718 PossibleOtherCallerNodes--;
4719 break;
4720 }
4721 }
4722 }
4723 }
4724
4725 if (!PossibleOtherCallerNodes)
4726 return;
4727
4728 // Build the set of other caller nodes that can use the same callee merge
4729 // node.
4730 for (auto &[OtherCaller, Count] : OtherCallersToSharedCalleeEdgeCount) {
4731 if (Count != NumCalleeClones)
4732 continue;
4733 OtherCallersToShareMerge.insert(OtherCaller);
4734 }
4735}
4736
4737// This method assigns cloned callsites to functions, cloning the functions as
4738// needed. The assignment is greedy and proceeds roughly as follows:
4739//
4740// For each function Func:
4741// For each call with graph Node having clones:
4742// Initialize ClonesWorklist to Node and its clones
4743// Initialize NodeCloneCount to 0
4744// While ClonesWorklist is not empty:
4745// Clone = pop front ClonesWorklist
4746// NodeCloneCount++
4747// If Func has been cloned less than NodeCloneCount times:
4748// If NodeCloneCount is 1:
4749// Assign Clone to original Func
4750// Continue
4751// Create a new function clone
4752// If other callers not assigned to call a function clone yet:
4753// Assign them to call new function clone
4754// Continue
4755// Assign any other caller calling the cloned version to new clone
4756//
4757// For each caller of Clone:
4758// If caller is assigned to call a specific function clone:
4759// If we cannot assign Clone to that function clone:
4760// Create new callsite Clone NewClone
4761// Add NewClone to ClonesWorklist
4762// Continue
4763// Assign Clone to existing caller's called function clone
4764// Else:
4765// If Clone not already assigned to a function clone:
4766// Assign to first function clone without assignment
4767// Assign caller to selected function clone
4768// For each call with graph Node having clones:
4769// If number func clones > number call's callsite Node clones:
4770// Record func CallInfo clones without Node clone in UnassignedCallClones
4771// For callsite Nodes in DFS order from allocations:
4772// If IsAllocation:
4773// Update allocation with alloc type
4774// Else:
4775// For Call, all MatchingCalls, and associated UnnassignedCallClones:
4776// Update call to call recorded callee clone
4777//
4778template <typename DerivedCCG, typename FuncTy, typename CallTy>
4779bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::assignFunctions() {
4780 bool Changed = false;
4781
4782 mergeClones();
4783
4784 // Keep track of the assignment of nodes (callsites) to function clones they
4785 // call.
4786 DenseMap<ContextNode *, FuncInfo> CallsiteToCalleeFuncCloneMap;
4787
4788 // Update caller node to call function version CalleeFunc, by recording the
4789 // assignment in CallsiteToCalleeFuncCloneMap.
4790 auto RecordCalleeFuncOfCallsite = [&](ContextNode *Caller,
4791 const FuncInfo &CalleeFunc) {
4792 assert(Caller->hasCall());
4793 CallsiteToCalleeFuncCloneMap[Caller] = CalleeFunc;
4794 };
4795
4796 // Information for a single clone of this Func.
4797 struct FuncCloneInfo {
4798 // The function clone.
4799 FuncInfo FuncClone;
4800 // Remappings of each call of interest (from original uncloned call to the
4801 // corresponding cloned call in this function clone).
4802 DenseMap<CallInfo, CallInfo> CallMap;
4803 };
4804
4805 // Map to keep track of information needed to update calls in function clones
4806 // when their corresponding callsite node was not itself cloned for that
4807 // function clone. Because of call context pruning (i.e. we only keep as much
4808 // caller information as needed to distinguish hot vs cold), we may not have
4809 // caller edges coming to each callsite node from all possible function
4810 // callers. A function clone may get created for other callsites in the
4811 // function for which there are caller edges that were not pruned. Any other
4812 // callsites in that function clone, which were not themselved cloned for
4813 // that function clone, should get updated the same way as the corresponding
4814 // callsite in the original function (which may call a clone of its callee).
4815 //
4816 // We build this map after completing function cloning for each function, so
4817 // that we can record the information from its call maps before they are
4818 // destructed. The map will be used as we update calls to update any still
4819 // unassigned call clones. Note that we may create new node clones as we clone
4820 // other functions, so later on we check which node clones were still not
4821 // created. To this end, the inner map is a map from function clone number to
4822 // the list of calls cloned for that function (can be more than one due to the
4823 // Node's MatchingCalls array).
4824 //
4825 // The alternative is creating new callsite clone nodes below as we clone the
4826 // function, but that is tricker to get right and likely more overhead.
4827 //
4828 // Inner map is a std::map so sorted by key (clone number), in order to get
4829 // ordered remarks in the full LTO case.
4830 DenseMap<const ContextNode *, std::map<unsigned, SmallVector<CallInfo, 0>>>
4831 UnassignedCallClones;
4832
4833 // Walk all functions for which we saw calls with memprof metadata, and handle
4834 // cloning for each of its calls.
4835 for (auto &[Func, CallsWithMetadata] : FuncToCallsWithMetadata) {
4836 FuncInfo OrigFunc(Func);
4837 // Map from each clone number of OrigFunc to information about that function
4838 // clone (the function clone FuncInfo and call remappings). The index into
4839 // the vector is the clone number, as function clones are created and
4840 // numbered sequentially.
4841 std::vector<FuncCloneInfo> FuncCloneInfos;
4842 for (auto &Call : CallsWithMetadata) {
4843 ContextNode *Node = getNodeForInst(Call);
4844 // Skip call if we do not have a node for it (all uses of its stack ids
4845 // were either on inlined chains or pruned from the MIBs), or if we did
4846 // not create any clones for it.
4847 if (!Node || Node->Clones.empty())
4848 continue;
4849 assert(Node->hasCall() &&
4850 "Not having a call should have prevented cloning");
4851
4852 // Track the assignment of function clones to clones of the current
4853 // callsite Node being handled.
4854 std::map<FuncInfo, ContextNode *> FuncCloneToCurNodeCloneMap;
4855
4856 // Assign callsite version CallsiteClone to function version FuncClone,
4857 // and also assign (possibly cloned) Call to CallsiteClone.
4858 auto AssignCallsiteCloneToFuncClone = [&](const FuncInfo &FuncClone,
4859 CallInfo &Call,
4860 ContextNode *CallsiteClone,
4861 bool IsAlloc) {
4862 // Record the clone of callsite node assigned to this function clone.
4863 FuncCloneToCurNodeCloneMap[FuncClone] = CallsiteClone;
4864
4865 assert(FuncCloneInfos.size() > FuncClone.cloneNo());
4866 DenseMap<CallInfo, CallInfo> &CallMap =
4867 FuncCloneInfos[FuncClone.cloneNo()].CallMap;
4868 CallInfo CallClone(Call);
4869 if (auto It = CallMap.find(Call); It != CallMap.end())
4870 CallClone = It->second;
4871 CallsiteClone->setCall(CallClone);
4872 // Need to do the same for all matching calls.
4873 for (auto &MatchingCall : Node->MatchingCalls) {
4874 CallInfo CallClone(MatchingCall);
4875 if (auto It = CallMap.find(MatchingCall); It != CallMap.end())
4876 CallClone = It->second;
4877 // Updates the call in the list.
4878 MatchingCall = CallClone;
4879 }
4880 };
4881
4882 // Invokes moveEdgeToNewCalleeClone which creates a new clone, and then
4883 // performs the necessary fixups (removing none type edges, and
4884 // importantly, propagating any function call assignment of the original
4885 // node to the new clone).
4886 auto MoveEdgeToNewCalleeCloneAndSetUp =
4887 [&](const std::shared_ptr<ContextEdge> &Edge) {
4888 ContextNode *OrigCallee = Edge->Callee;
4889 ContextNode *NewClone = moveEdgeToNewCalleeClone(Edge);
4890 removeNoneTypeCalleeEdges(NewClone);
4891 assert(NewClone->AllocTypes != (uint8_t)AllocationType::None);
4892 // If the original Callee was already assigned to call a specific
4893 // function version, make sure its new clone is assigned to call
4894 // that same function clone.
4895 if (CallsiteToCalleeFuncCloneMap.count(OrigCallee))
4896 RecordCalleeFuncOfCallsite(
4897 NewClone, CallsiteToCalleeFuncCloneMap[OrigCallee]);
4898 return NewClone;
4899 };
4900
4901 // Keep track of the clones of callsite Node that need to be assigned to
4902 // function clones. This list may be expanded in the loop body below if we
4903 // find additional cloning is required.
4904 std::deque<ContextNode *> ClonesWorklist;
4905 // Ignore original Node if we moved all of its contexts to clones.
4906 if (!Node->emptyContextIds())
4907 ClonesWorklist.push_back(Node);
4908 llvm::append_range(ClonesWorklist, Node->Clones);
4909
4910 // Now walk through all of the clones of this callsite Node that we need,
4911 // and determine the assignment to a corresponding clone of the current
4912 // function (creating new function clones as needed).
4913 unsigned NodeCloneCount = 0;
4914 while (!ClonesWorklist.empty()) {
4915 ContextNode *Clone = ClonesWorklist.front();
4916 ClonesWorklist.pop_front();
4917 NodeCloneCount++;
4918 if (VerifyNodes)
4920
4921 // Need to create a new function clone if we have more callsite clones
4922 // than existing function clones, which would have been assigned to an
4923 // earlier clone in the list (we assign callsite clones to function
4924 // clones greedily).
4925 if (FuncCloneInfos.size() < NodeCloneCount) {
4926 // If this is the first callsite copy, assign to original function.
4927 if (NodeCloneCount == 1) {
4928 // Since FuncCloneInfos is empty in this case, no clones have
4929 // been created for this function yet, and no callers should have
4930 // been assigned a function clone for this callee node yet.
4932 Clone->CallerEdges, [&](const std::shared_ptr<ContextEdge> &E) {
4933 return CallsiteToCalleeFuncCloneMap.count(E->Caller);
4934 }));
4935 // Initialize with empty call map, assign Clone to original function
4936 // and its callers, and skip to the next clone.
4937 FuncCloneInfos.push_back(
4938 {OrigFunc, DenseMap<CallInfo, CallInfo>()});
4939 AssignCallsiteCloneToFuncClone(
4940 OrigFunc, Call, Clone,
4941 AllocationCallToContextNodeMap.count(Call));
4942 for (auto &CE : Clone->CallerEdges) {
4943 // Ignore any caller that does not have a recorded callsite Call.
4944 if (!CE->Caller->hasCall())
4945 continue;
4946 RecordCalleeFuncOfCallsite(CE->Caller, OrigFunc);
4947 }
4948 continue;
4949 }
4950
4951 // First locate which copy of OrigFunc to clone again. If a caller
4952 // of this callsite clone was already assigned to call a particular
4953 // function clone, we need to redirect all of those callers to the
4954 // new function clone, and update their other callees within this
4955 // function.
4956 FuncInfo PreviousAssignedFuncClone;
4957 auto EI = llvm::find_if(
4958 Clone->CallerEdges, [&](const std::shared_ptr<ContextEdge> &E) {
4959 return CallsiteToCalleeFuncCloneMap.count(E->Caller);
4960 });
4961 bool CallerAssignedToCloneOfFunc = false;
4962 if (EI != Clone->CallerEdges.end()) {
4963 const std::shared_ptr<ContextEdge> &Edge = *EI;
4964 PreviousAssignedFuncClone =
4965 CallsiteToCalleeFuncCloneMap[Edge->Caller];
4966 CallerAssignedToCloneOfFunc = true;
4967 }
4968
4969 // Clone function and save it along with the CallInfo map created
4970 // during cloning in the FuncCloneInfos.
4971 DenseMap<CallInfo, CallInfo> NewCallMap;
4972 unsigned CloneNo = FuncCloneInfos.size();
4973 assert(CloneNo > 0 && "Clone 0 is the original function, which "
4974 "should already exist in the map");
4975 FuncInfo NewFuncClone = cloneFunctionForCallsite(
4976 OrigFunc, Call, NewCallMap, CallsWithMetadata, CloneNo);
4977 FuncCloneInfos.push_back({NewFuncClone, std::move(NewCallMap)});
4978 FunctionClonesAnalysis++;
4979 Changed = true;
4980
4981 // If no caller callsites were already assigned to a clone of this
4982 // function, we can simply assign this clone to the new func clone
4983 // and update all callers to it, then skip to the next clone.
4984 if (!CallerAssignedToCloneOfFunc) {
4985 AssignCallsiteCloneToFuncClone(
4986 NewFuncClone, Call, Clone,
4987 AllocationCallToContextNodeMap.count(Call));
4988 for (auto &CE : Clone->CallerEdges) {
4989 // Ignore any caller that does not have a recorded callsite Call.
4990 if (!CE->Caller->hasCall())
4991 continue;
4992 RecordCalleeFuncOfCallsite(CE->Caller, NewFuncClone);
4993 }
4994 continue;
4995 }
4996
4997 // We may need to do additional node cloning in this case.
4998 // Reset the CallsiteToCalleeFuncCloneMap entry for any callers
4999 // that were previously assigned to call PreviousAssignedFuncClone,
5000 // to record that they now call NewFuncClone.
5001 // The none type edge removal may remove some of this Clone's caller
5002 // edges, if it is reached via another of its caller's callees.
5003 // Iterate over a copy and skip any that were removed.
5004 auto CallerEdges = Clone->CallerEdges;
5005 for (auto CE : CallerEdges) {
5006 // Skip any that have been removed on an earlier iteration.
5007 if (CE->isRemoved()) {
5008 assert(!is_contained(Clone->CallerEdges, CE));
5009 continue;
5010 }
5011 assert(CE);
5012 // Ignore any caller that does not have a recorded callsite Call.
5013 if (!CE->Caller->hasCall())
5014 continue;
5015
5016 if (!CallsiteToCalleeFuncCloneMap.count(CE->Caller) ||
5017 // We subsequently fall through to later handling that
5018 // will perform any additional cloning required for
5019 // callers that were calling other function clones.
5020 CallsiteToCalleeFuncCloneMap[CE->Caller] !=
5021 PreviousAssignedFuncClone)
5022 continue;
5023
5024 RecordCalleeFuncOfCallsite(CE->Caller, NewFuncClone);
5025
5026 // If we are cloning a function that was already assigned to some
5027 // callers, then essentially we are creating new callsite clones
5028 // of the other callsites in that function that are reached by those
5029 // callers. Clone the other callees of the current callsite's caller
5030 // that were already assigned to PreviousAssignedFuncClone
5031 // accordingly. This is important since we subsequently update the
5032 // calls from the nodes in the graph and their assignments to callee
5033 // functions recorded in CallsiteToCalleeFuncCloneMap.
5034 // The none type edge removal may remove some of this caller's
5035 // callee edges, if it is reached via another of its callees.
5036 // Iterate over a copy and skip any that were removed.
5037 auto CalleeEdges = CE->Caller->CalleeEdges;
5038 for (auto CalleeEdge : CalleeEdges) {
5039 // Skip any that have been removed on an earlier iteration when
5040 // cleaning up newly None type callee edges.
5041 if (CalleeEdge->isRemoved()) {
5042 assert(!is_contained(CE->Caller->CalleeEdges, CalleeEdge));
5043 continue;
5044 }
5045 assert(CalleeEdge);
5046 ContextNode *Callee = CalleeEdge->Callee;
5047 // Skip the current callsite, we are looking for other
5048 // callsites Caller calls, as well as any that does not have a
5049 // recorded callsite Call.
5050 if (Callee == Clone || !Callee->hasCall())
5051 continue;
5052 // Skip direct recursive calls. We don't need/want to clone the
5053 // caller node again, and this loop will not behave as expected if
5054 // we tried.
5055 if (Callee == CalleeEdge->Caller)
5056 continue;
5057 ContextNode *NewClone =
5058 MoveEdgeToNewCalleeCloneAndSetUp(CalleeEdge);
5059 // Moving the edge may have resulted in some none type
5060 // callee edges on the original Callee.
5061 removeNoneTypeCalleeEdges(Callee);
5062 // Update NewClone with the new Call clone of this callsite's Call
5063 // created for the new function clone created earlier.
5064 // Recall that we have already ensured when building the graph
5065 // that each caller can only call callsites within the same
5066 // function, so we are guaranteed that Callee Call is in the
5067 // current OrigFunc.
5068 // CallMap is set up as indexed by original Call at clone 0.
5069 CallInfo OrigCall(Callee->getOrigNode()->Call);
5070 OrigCall.setCloneNo(0);
5071 DenseMap<CallInfo, CallInfo> &CallMap =
5072 FuncCloneInfos[NewFuncClone.cloneNo()].CallMap;
5073 assert(CallMap.count(OrigCall));
5074 CallInfo NewCall(CallMap[OrigCall]);
5075 assert(NewCall);
5076 NewClone->setCall(NewCall);
5077 // Need to do the same for all matching calls.
5078 for (auto &MatchingCall : NewClone->MatchingCalls) {
5079 CallInfo OrigMatchingCall(MatchingCall);
5080 OrigMatchingCall.setCloneNo(0);
5081 assert(CallMap.count(OrigMatchingCall));
5082 CallInfo NewCall(CallMap[OrigMatchingCall]);
5083 assert(NewCall);
5084 // Updates the call in the list.
5085 MatchingCall = NewCall;
5086 }
5087 }
5088 }
5089 // Fall through to handling below to perform the recording of the
5090 // function for this callsite clone. This enables handling of cases
5091 // where the callers were assigned to different clones of a function.
5092 }
5093
5094 auto FindFirstAvailFuncClone = [&]() {
5095 // Find first function in FuncCloneInfos without an assigned
5096 // clone of this callsite Node. We should always have one
5097 // available at this point due to the earlier cloning when the
5098 // FuncCloneInfos size was smaller than the clone number.
5099 for (auto &CF : FuncCloneInfos) {
5100 if (!FuncCloneToCurNodeCloneMap.count(CF.FuncClone))
5101 return CF.FuncClone;
5102 }
5104 "Expected an available func clone for this callsite clone");
5105 };
5106
5107 // See if we can use existing function clone. Walk through
5108 // all caller edges to see if any have already been assigned to
5109 // a clone of this callsite's function. If we can use it, do so. If not,
5110 // because that function clone is already assigned to a different clone
5111 // of this callsite, then we need to clone again.
5112 // Basically, this checking is needed to handle the case where different
5113 // caller functions/callsites may need versions of this function
5114 // containing different mixes of callsite clones across the different
5115 // callsites within the function. If that happens, we need to create
5116 // additional function clones to handle the various combinations.
5117 //
5118 // Keep track of any new clones of this callsite created by the
5119 // following loop, as well as any existing clone that we decided to
5120 // assign this clone to.
5121 std::map<FuncInfo, ContextNode *> FuncCloneToNewCallsiteCloneMap;
5122 FuncInfo FuncCloneAssignedToCurCallsiteClone;
5123 // Iterate over a copy of Clone's caller edges, since we may need to
5124 // remove edges in the moveEdgeTo* methods, and this simplifies the
5125 // handling and makes it less error-prone.
5126 auto CloneCallerEdges = Clone->CallerEdges;
5127 for (auto &Edge : CloneCallerEdges) {
5128 // Skip removed edges (due to direct recursive edges updated when
5129 // updating callee edges when moving an edge and subsequently
5130 // removed by call to removeNoneTypeCalleeEdges on the Clone).
5131 if (Edge->isRemoved())
5132 continue;
5133 // Ignore any caller that does not have a recorded callsite Call.
5134 if (!Edge->Caller->hasCall())
5135 continue;
5136 // If this caller already assigned to call a version of OrigFunc, need
5137 // to ensure we can assign this callsite clone to that function clone.
5138 if (CallsiteToCalleeFuncCloneMap.count(Edge->Caller)) {
5139 FuncInfo FuncCloneCalledByCaller =
5140 CallsiteToCalleeFuncCloneMap[Edge->Caller];
5141 // First we need to confirm that this function clone is available
5142 // for use by this callsite node clone.
5143 //
5144 // While FuncCloneToCurNodeCloneMap is built only for this Node and
5145 // its callsite clones, one of those callsite clones X could have
5146 // been assigned to the same function clone called by Edge's caller
5147 // - if Edge's caller calls another callsite within Node's original
5148 // function, and that callsite has another caller reaching clone X.
5149 // We need to clone Node again in this case.
5150 if ((FuncCloneToCurNodeCloneMap.count(FuncCloneCalledByCaller) &&
5151 FuncCloneToCurNodeCloneMap[FuncCloneCalledByCaller] !=
5152 Clone) ||
5153 // Detect when we have multiple callers of this callsite that
5154 // have already been assigned to specific, and different, clones
5155 // of OrigFunc (due to other unrelated callsites in Func they
5156 // reach via call contexts). Is this Clone of callsite Node
5157 // assigned to a different clone of OrigFunc? If so, clone Node
5158 // again.
5159 (FuncCloneAssignedToCurCallsiteClone &&
5160 FuncCloneAssignedToCurCallsiteClone !=
5161 FuncCloneCalledByCaller)) {
5162 // We need to use a different newly created callsite clone, in
5163 // order to assign it to another new function clone on a
5164 // subsequent iteration over the Clones array (adjusted below).
5165 // Note we specifically do not reset the
5166 // CallsiteToCalleeFuncCloneMap entry for this caller, so that
5167 // when this new clone is processed later we know which version of
5168 // the function to copy (so that other callsite clones we have
5169 // assigned to that function clone are properly cloned over). See
5170 // comments in the function cloning handling earlier.
5171
5172 // Check if we already have cloned this callsite again while
5173 // walking through caller edges, for a caller calling the same
5174 // function clone. If so, we can move this edge to that new clone
5175 // rather than creating yet another new clone.
5176 if (FuncCloneToNewCallsiteCloneMap.count(
5177 FuncCloneCalledByCaller)) {
5178 ContextNode *NewClone =
5179 FuncCloneToNewCallsiteCloneMap[FuncCloneCalledByCaller];
5180 moveEdgeToExistingCalleeClone(Edge, NewClone);
5181 // Cleanup any none type edges cloned over.
5182 removeNoneTypeCalleeEdges(NewClone);
5183 } else {
5184 // Create a new callsite clone.
5185 ContextNode *NewClone = MoveEdgeToNewCalleeCloneAndSetUp(Edge);
5186 FuncCloneToNewCallsiteCloneMap[FuncCloneCalledByCaller] =
5187 NewClone;
5188 // Add to list of clones and process later.
5189 ClonesWorklist.push_back(NewClone);
5190 }
5191 // Moving the caller edge may have resulted in some none type
5192 // callee edges.
5193 removeNoneTypeCalleeEdges(Clone);
5194 // We will handle the newly created callsite clone in a subsequent
5195 // iteration over this Node's Clones.
5196 continue;
5197 }
5198
5199 // Otherwise, we can use the function clone already assigned to this
5200 // caller.
5201 if (!FuncCloneAssignedToCurCallsiteClone) {
5202 FuncCloneAssignedToCurCallsiteClone = FuncCloneCalledByCaller;
5203 // Assign Clone to FuncCloneCalledByCaller
5204 AssignCallsiteCloneToFuncClone(
5205 FuncCloneCalledByCaller, Call, Clone,
5206 AllocationCallToContextNodeMap.count(Call));
5207 } else
5208 // Don't need to do anything - callsite is already calling this
5209 // function clone.
5210 assert(FuncCloneAssignedToCurCallsiteClone ==
5211 FuncCloneCalledByCaller);
5212
5213 } else {
5214 // We have not already assigned this caller to a version of
5215 // OrigFunc. Do the assignment now.
5216
5217 // First check if we have already assigned this callsite clone to a
5218 // clone of OrigFunc for another caller during this iteration over
5219 // its caller edges.
5220 if (!FuncCloneAssignedToCurCallsiteClone) {
5221 FuncCloneAssignedToCurCallsiteClone = FindFirstAvailFuncClone();
5222 assert(FuncCloneAssignedToCurCallsiteClone);
5223 // Assign Clone to FuncCloneAssignedToCurCallsiteClone
5224 AssignCallsiteCloneToFuncClone(
5225 FuncCloneAssignedToCurCallsiteClone, Call, Clone,
5226 AllocationCallToContextNodeMap.count(Call));
5227 } else
5228 assert(FuncCloneToCurNodeCloneMap
5229 [FuncCloneAssignedToCurCallsiteClone] == Clone);
5230 // Update callers to record function version called.
5231 RecordCalleeFuncOfCallsite(Edge->Caller,
5232 FuncCloneAssignedToCurCallsiteClone);
5233 }
5234 }
5235 // If we didn't assign a function clone to this callsite clone yet, e.g.
5236 // none of its callers has a non-null call, do the assignment here.
5237 // We want to ensure that every callsite clone is assigned to some
5238 // function clone, so that the call updates below work as expected.
5239 // In particular if this is the original callsite, we want to ensure it
5240 // is assigned to the original function, otherwise the original function
5241 // will appear available for assignment to other callsite clones,
5242 // leading to unintended effects. For one, the unknown and not updated
5243 // callers will call into cloned paths leading to the wrong hints,
5244 // because they still call the original function (clone 0). Also,
5245 // because all callsites start out as being clone 0 by default, we can't
5246 // easily distinguish between callsites explicitly assigned to clone 0
5247 // vs those never assigned, which can lead to multiple updates of the
5248 // calls when invoking updateCall below, with mismatched clone values.
5249 // TODO: Add a flag to the callsite nodes or some other mechanism to
5250 // better distinguish and identify callsite clones that are not getting
5251 // assigned to function clones as expected.
5252 if (!FuncCloneAssignedToCurCallsiteClone) {
5253 FuncCloneAssignedToCurCallsiteClone = FindFirstAvailFuncClone();
5254 assert(FuncCloneAssignedToCurCallsiteClone &&
5255 "No available func clone for this callsite clone");
5256 AssignCallsiteCloneToFuncClone(
5257 FuncCloneAssignedToCurCallsiteClone, Call, Clone,
5258 /*IsAlloc=*/AllocationCallToContextNodeMap.contains(Call));
5259 }
5260 }
5261 if (VerifyCCG) {
5263 for (const auto &PE : Node->CalleeEdges)
5265 for (const auto &CE : Node->CallerEdges)
5267 for (auto *Clone : Node->Clones) {
5269 for (const auto &PE : Clone->CalleeEdges)
5271 for (const auto &CE : Clone->CallerEdges)
5273 }
5274 }
5275 }
5276
5277 if (FuncCloneInfos.size() < 2)
5278 continue;
5279
5280 // In this case there is more than just the original function copy.
5281 // Record call clones of any callsite nodes in the function that did not
5282 // themselves get cloned for all of the function clones.
5283 for (auto &Call : CallsWithMetadata) {
5284 ContextNode *Node = getNodeForInst(Call);
5285 if (!Node || !Node->hasCall() || Node->emptyContextIds())
5286 continue;
5287 // If Node has enough clones already to cover all function clones, we can
5288 // skip it. Need to add one for the original copy.
5289 // Use >= in case there were clones that were skipped due to having empty
5290 // context ids
5291 if (Node->Clones.size() + 1 >= FuncCloneInfos.size())
5292 continue;
5293 // First collect all function clones we cloned this callsite node for.
5294 // They may not be sequential due to empty clones e.g.
5295 DenseSet<unsigned> NodeCallClones;
5296 for (auto *C : Node->Clones)
5297 NodeCallClones.insert(C->Call.cloneNo());
5298 unsigned I = 0;
5299 // Now check all the function clones.
5300 for (auto &FC : FuncCloneInfos) {
5301 // Function clones should be sequential.
5302 assert(FC.FuncClone.cloneNo() == I);
5303 // Skip the first clone which got the original call.
5304 // Also skip any other clones created for this Node.
5305 if (++I == 1 || NodeCallClones.contains(I)) {
5306 continue;
5307 }
5308 // Record the call clones created for this callsite in this function
5309 // clone.
5310 auto &CallVector = UnassignedCallClones[Node][I];
5311 DenseMap<CallInfo, CallInfo> &CallMap = FC.CallMap;
5312 if (auto It = CallMap.find(Call); It != CallMap.end()) {
5313 CallInfo CallClone = It->second;
5314 CallVector.push_back(CallClone);
5315 } else {
5316 // All but the original clone (skipped earlier) should have an entry
5317 // for all calls.
5318 assert(false && "Expected to find call in CallMap");
5319 }
5320 // Need to do the same for all matching calls.
5321 for (auto &MatchingCall : Node->MatchingCalls) {
5322 if (auto It = CallMap.find(MatchingCall); It != CallMap.end()) {
5323 CallInfo CallClone = It->second;
5324 CallVector.push_back(CallClone);
5325 } else {
5326 // All but the original clone (skipped earlier) should have an entry
5327 // for all calls.
5328 assert(false && "Expected to find call in CallMap");
5329 }
5330 }
5331 }
5332 }
5333 }
5334
5335 uint8_t BothTypes =
5336 (uint8_t)AllocationType::Cold | (uint8_t)AllocationType::NotCold;
5337
5338 auto UpdateCalls = [&](ContextNode *Node,
5339 DenseSet<const ContextNode *> &Visited,
5340 auto &&UpdateCalls) {
5341 auto Inserted = Visited.insert(Node);
5342 if (!Inserted.second)
5343 return;
5344
5345 for (auto *Clone : Node->Clones)
5346 UpdateCalls(Clone, Visited, UpdateCalls);
5347
5348 for (auto &Edge : Node->CallerEdges)
5349 UpdateCalls(Edge->Caller, Visited, UpdateCalls);
5350
5351 // Skip if either no call to update, or if we ended up with no context ids
5352 // (we moved all edges onto other clones).
5353 if (!Node->hasCall() || Node->emptyContextIds())
5354 return;
5355
5356 if (Node->IsAllocation) {
5357 auto AT = allocTypeToUse(Node->AllocTypes);
5358 // If the allocation type is ambiguous, and more aggressive hinting
5359 // has been enabled via the MinClonedColdBytePercent flag, see if this
5360 // allocation should be hinted cold anyway because its fraction cold bytes
5361 // allocated is at least the given threshold.
5362 if (Node->AllocTypes == BothTypes && MinClonedColdBytePercent < 100 &&
5363 !ContextIdToContextSizeInfos.empty()) {
5364 uint64_t TotalCold = 0;
5365 uint64_t Total = 0;
5366 for (auto Id : Node->getContextIds()) {
5367 auto TypeI = ContextIdToAllocationType.find(Id);
5368 assert(TypeI != ContextIdToAllocationType.end());
5369 auto CSI = ContextIdToContextSizeInfos.find(Id);
5370 if (CSI != ContextIdToContextSizeInfos.end()) {
5371 for (auto &Info : CSI->second) {
5372 Total += Info.TotalSize;
5373 if (TypeI->second == AllocationType::Cold)
5374 TotalCold += Info.TotalSize;
5375 }
5376 }
5377 }
5378 if (TotalCold * 100 >= Total * MinClonedColdBytePercent)
5379 AT = AllocationType::Cold;
5380 }
5381 updateAllocationCall(Node->Call, AT);
5382 assert(Node->MatchingCalls.empty());
5383 return;
5384 }
5385
5386 if (!CallsiteToCalleeFuncCloneMap.count(Node))
5387 return;
5388
5389 auto CalleeFunc = CallsiteToCalleeFuncCloneMap[Node];
5390 updateCall(Node->Call, CalleeFunc);
5391 // Update all the matching calls as well.
5392 for (auto &Call : Node->MatchingCalls)
5393 updateCall(Call, CalleeFunc);
5394
5395 // Now update all calls recorded earlier that are still in function clones
5396 // which don't have a clone of this callsite node.
5397 if (!UnassignedCallClones.contains(Node))
5398 return;
5399 DenseSet<unsigned> NodeCallClones;
5400 for (auto *C : Node->Clones)
5401 NodeCallClones.insert(C->Call.cloneNo());
5402 // Note that we already confirmed Node is in this map a few lines above.
5403 auto &ClonedCalls = UnassignedCallClones[Node];
5404 for (auto &[CloneNo, CallVector] : ClonedCalls) {
5405 // Should start at 1 as we never create an entry for original node.
5406 assert(CloneNo > 0);
5407 // If we subsequently created a clone, skip this one.
5408 if (NodeCallClones.contains(CloneNo))
5409 continue;
5410 // Use the original Node's CalleeFunc.
5411 for (auto &Call : CallVector)
5412 updateCall(Call, CalleeFunc);
5413 }
5414 };
5415
5416 // Performs DFS traversal starting from allocation nodes to update calls to
5417 // reflect cloning decisions recorded earlier. For regular LTO this will
5418 // update the actual calls in the IR to call the appropriate function clone
5419 // (and add attributes to allocation calls), whereas for ThinLTO the decisions
5420 // are recorded in the summary entries.
5421 DenseSet<const ContextNode *> Visited;
5422 for (auto &Entry : AllocationCallToContextNodeMap)
5423 UpdateCalls(Entry.second, Visited, UpdateCalls);
5424
5425 return Changed;
5426}
5427
5428// Compute a SHA1 hash of the callsite and alloc version information of clone I
5429// in the summary, to use in detection of duplicate clones.
5431 SHA1 Hasher;
5432 // Update hash with any callsites that call non-default (non-zero) callee
5433 // versions.
5434 for (auto &SN : FS->callsites()) {
5435 // In theory all callsites and allocs in this function should have the same
5436 // number of clone entries, but handle any discrepancies gracefully below
5437 // for NDEBUG builds.
5438 assert(
5439 SN.Clones.size() > I &&
5440 "Callsite summary has fewer entries than other summaries in function");
5441 if (SN.Clones.size() <= I || !SN.Clones[I])
5442 continue;
5443 uint8_t Data[sizeof(SN.Clones[I])];
5444 support::endian::write32le(Data, SN.Clones[I]);
5445 Hasher.update(Data);
5446 }
5447 // Update hash with any allocs that have non-default (non-None) hints.
5448 for (auto &AN : FS->allocs()) {
5449 // In theory all callsites and allocs in this function should have the same
5450 // number of clone entries, but handle any discrepancies gracefully below
5451 // for NDEBUG builds.
5452 assert(AN.Versions.size() > I &&
5453 "Alloc summary has fewer entries than other summaries in function");
5454 if (AN.Versions.size() <= I ||
5455 (AllocationType)AN.Versions[I] == AllocationType::None)
5456 continue;
5457 Hasher.update(ArrayRef<uint8_t>(&AN.Versions[I], 1));
5458 }
5459 return support::endian::read64le(Hasher.result().data());
5460}
5461
5463 Function &F, unsigned NumClones, Module &M, OptimizationRemarkEmitter &ORE,
5465 &FuncToAliasMap,
5466 FunctionSummary *FS) {
5467 auto TakeDeclNameAndReplace = [](GlobalValue *DeclGV, GlobalValue *NewGV) {
5468 // We might have created this when adjusting callsite in another
5469 // function. It should be a declaration.
5470 assert(DeclGV->isDeclaration());
5471 NewGV->takeName(DeclGV);
5472 DeclGV->replaceAllUsesWith(NewGV);
5473 DeclGV->eraseFromParent();
5474 };
5475
5476 // Handle aliases to this function, and create analogous alias clones to the
5477 // provided clone of this function.
5478 auto CloneFuncAliases = [&](Function *NewF, unsigned I) {
5479 if (!FuncToAliasMap.count(&F))
5480 return;
5481 for (auto *A : FuncToAliasMap[&F]) {
5482 std::string AliasName = getMemProfFuncName(A->getName(), I);
5483 auto *PrevA = M.getNamedAlias(AliasName);
5484 auto *NewA = GlobalAlias::create(A->getValueType(),
5485 A->getType()->getPointerAddressSpace(),
5486 A->getLinkage(), AliasName, NewF);
5487 NewA->copyAttributesFrom(A);
5488 if (PrevA)
5489 TakeDeclNameAndReplace(PrevA, NewA);
5490 }
5491 };
5492
5493 // The first "clone" is the original copy, we should only call this if we
5494 // needed to create new clones.
5495 assert(NumClones > 1);
5497 VMaps.reserve(NumClones - 1);
5498 FunctionsClonedThinBackend++;
5499
5500 // Map of hash of callsite/alloc versions to the instantiated function clone
5501 // (possibly the original) implementing those calls. Used to avoid
5502 // instantiating duplicate function clones.
5503 // FIXME: Ideally the thin link would not generate such duplicate clones to
5504 // start with, but right now it happens due to phase ordering in the function
5505 // assignment and possible new clones that produces. We simply make each
5506 // duplicate an alias to the matching instantiated clone recorded in the map
5507 // (except for available_externally which are made declarations as they would
5508 // be aliases in the prevailing module, and available_externally aliases are
5509 // not well supported right now).
5511
5512 // Save the hash of the original function version.
5513 HashToFunc[ComputeHash(FS, 0)] = &F;
5514
5515 for (unsigned I = 1; I < NumClones; I++) {
5516 VMaps.emplace_back(std::make_unique<ValueToValueMapTy>());
5517 std::string Name = getMemProfFuncName(F.getName(), I);
5518 auto Hash = ComputeHash(FS, I);
5519 // If this clone would duplicate a previously seen clone, don't generate the
5520 // duplicate clone body, just make an alias to satisfy any (potentially
5521 // cross-module) references.
5522 if (HashToFunc.contains(Hash)) {
5523 FunctionCloneDuplicatesThinBackend++;
5524 auto *Func = HashToFunc[Hash];
5525 if (Func->hasAvailableExternallyLinkage()) {
5526 // Skip these as EliminateAvailableExternallyPass does not handle
5527 // available_externally aliases correctly and we end up with an
5528 // available_externally alias to a declaration. Just create a
5529 // declaration for now as we know we will have a definition in another
5530 // module.
5531 auto Decl = M.getOrInsertFunction(Name, Func->getFunctionType());
5532 ORE.emit(OptimizationRemark(DEBUG_TYPE, "MemprofClone", &F)
5533 << "created clone decl " << ore::NV("Decl", Decl.getCallee()));
5534 continue;
5535 }
5536 auto *PrevF = M.getFunction(Name);
5537 auto *Alias = GlobalAlias::create(Name, Func);
5538 if (PrevF)
5539 TakeDeclNameAndReplace(PrevF, Alias);
5540 ORE.emit(OptimizationRemark(DEBUG_TYPE, "MemprofClone", &F)
5541 << "created clone alias " << ore::NV("Alias", Alias));
5542
5543 // Now handle aliases to this function, and clone those as well.
5544 CloneFuncAliases(Func, I);
5545 continue;
5546 }
5547 auto *NewF = CloneFunction(&F, *VMaps.back());
5548 HashToFunc[Hash] = NewF;
5549 FunctionClonesThinBackend++;
5550 // Strip memprof and callsite metadata from clone as they are no longer
5551 // needed.
5552 for (auto &BB : *NewF) {
5553 for (auto &Inst : BB) {
5554 Inst.setMetadata(LLVMContext::MD_memprof, nullptr);
5555 Inst.setMetadata(LLVMContext::MD_callsite, nullptr);
5556 }
5557 }
5558 auto *PrevF = M.getFunction(Name);
5559 if (PrevF)
5560 TakeDeclNameAndReplace(PrevF, NewF);
5561 else
5562 NewF->setName(Name);
5563 updateSubprogramLinkageName(NewF, Name);
5564 ORE.emit(OptimizationRemark(DEBUG_TYPE, "MemprofClone", &F)
5565 << "created clone " << ore::NV("NewFunction", NewF));
5566
5567 // Now handle aliases to this function, and clone those as well.
5568 CloneFuncAliases(NewF, I);
5569 }
5570 return VMaps;
5571}
5572
5573// Locate the summary for F. This is complicated by the fact that it might
5574// have been internalized or promoted.
5576 const ModuleSummaryIndex *ImportSummary,
5577 const Function *CallingFunc = nullptr) {
5578 // FIXME: Ideally we would retain the original GUID in some fashion on the
5579 // function (e.g. as metadata), but for now do our best to locate the
5580 // summary without that information.
5581 ValueInfo TheFnVI = ImportSummary->getValueInfo(F.getGUID());
5582 if (!TheFnVI)
5583 // See if theFn was internalized, by checking index directly with
5584 // original name (this avoids the name adjustment done by getGUID() for
5585 // internal symbols).
5586 TheFnVI = ImportSummary->getValueInfo(
5588 if (TheFnVI)
5589 return TheFnVI;
5590 // Now query with the original name before any promotion was performed.
5591 StringRef OrigName =
5593 // When this pass is enabled, we always add thinlto_src_file provenance
5594 // metadata to imported function definitions, which allows us to recreate the
5595 // original internal symbol's GUID.
5596 auto SrcFileMD = F.getMetadata("thinlto_src_file");
5597 // If this is a call to an imported/promoted local for which we didn't import
5598 // the definition, the metadata will not exist on the declaration. However,
5599 // since we are doing this early, before any inlining in the LTO backend, we
5600 // can simply look at the metadata on the calling function which must have
5601 // been from the same module if F was an internal symbol originally.
5602 if (!SrcFileMD && F.isDeclaration()) {
5603 // We would only call this for a declaration for a direct callsite, in which
5604 // case the caller would have provided the calling function pointer.
5605 assert(CallingFunc);
5606 SrcFileMD = CallingFunc->getMetadata("thinlto_src_file");
5607 // If this is a promoted local (OrigName != F.getName()), since this is a
5608 // declaration, it must be imported from a different module and therefore we
5609 // should always find the metadata on its calling function. Any call to a
5610 // promoted local that came from this module should still be a definition.
5611 assert(SrcFileMD || OrigName == F.getName());
5612 }
5613 StringRef SrcFile = M.getSourceFileName();
5614 if (SrcFileMD)
5615 SrcFile = dyn_cast<MDString>(SrcFileMD->getOperand(0))->getString();
5616 std::string OrigId = GlobalValue::getGlobalIdentifier(
5617 OrigName, GlobalValue::InternalLinkage, SrcFile);
5618 TheFnVI = ImportSummary->getValueInfo(
5620 // Internal func in original module may have gotten a numbered suffix if we
5621 // imported an external function with the same name. This happens
5622 // automatically during IR linking for naming conflicts. It would have to
5623 // still be internal in that case (otherwise it would have been renamed on
5624 // promotion in which case we wouldn't have a naming conflict).
5625 if (!TheFnVI && OrigName == F.getName() && F.hasLocalLinkage() &&
5626 F.getName().contains('.')) {
5627 OrigName = F.getName().rsplit('.').first;
5629 OrigName, GlobalValue::InternalLinkage, SrcFile);
5630 TheFnVI = ImportSummary->getValueInfo(
5632 }
5633 // The only way we may not have a VI is if this is a declaration created for
5634 // an imported reference. For distributed ThinLTO we may not have a VI for
5635 // such declarations in the distributed summary.
5636 assert(TheFnVI || F.isDeclaration());
5637 return TheFnVI;
5638}
5639
5640bool MemProfContextDisambiguation::initializeIndirectCallPromotionInfo(
5641 Module &M) {
5642 ICallAnalysis = std::make_unique<ICallPromotionAnalysis>();
5643 Symtab = std::make_unique<InstrProfSymtab>();
5644 // Don't add canonical names, to avoid multiple functions to the symtab
5645 // when they both have the same root name with "." suffixes stripped.
5646 // If we pick the wrong one then this could lead to incorrect ICP and calling
5647 // a memprof clone that we don't actually create (resulting in linker unsats).
5648 // What this means is that the GUID of the function (or its PGOFuncName
5649 // metadata) *must* match that in the VP metadata to allow promotion.
5650 // In practice this should not be a limitation, since local functions should
5651 // have PGOFuncName metadata and global function names shouldn't need any
5652 // special handling (they should not get the ".llvm.*" suffix that the
5653 // canonicalization handling is attempting to strip).
5654 if (Error E = Symtab->create(M, /*InLTO=*/true, /*AddCanonical=*/false)) {
5655 std::string SymtabFailure = toString(std::move(E));
5656 M.getContext().emitError("Failed to create symtab: " + SymtabFailure);
5657 return false;
5658 }
5659 return true;
5660}
5661
5662#ifndef NDEBUG
5663// Sanity check that the MIB stack ids match between the summary and
5664// instruction metadata.
5666 const AllocInfo &AllocNode, const MDNode *MemProfMD,
5667 const CallStack<MDNode, MDNode::op_iterator> &CallsiteContext,
5668 const ModuleSummaryIndex *ImportSummary) {
5669 auto MIBIter = AllocNode.MIBs.begin();
5670 for (auto &MDOp : MemProfMD->operands()) {
5671 assert(MIBIter != AllocNode.MIBs.end());
5672 auto StackIdIndexIter = MIBIter->StackIdIndices.begin();
5673 auto *MIBMD = cast<const MDNode>(MDOp);
5674 MDNode *StackMDNode = getMIBStackNode(MIBMD);
5675 assert(StackMDNode);
5676 CallStack<MDNode, MDNode::op_iterator> StackContext(StackMDNode);
5677 auto ContextIterBegin =
5678 StackContext.beginAfterSharedPrefix(CallsiteContext);
5679 // Skip the checking on the first iteration.
5680 uint64_t LastStackContextId =
5681 (ContextIterBegin != StackContext.end() && *ContextIterBegin == 0) ? 1
5682 : 0;
5683 for (auto ContextIter = ContextIterBegin; ContextIter != StackContext.end();
5684 ++ContextIter) {
5685 // If this is a direct recursion, simply skip the duplicate
5686 // entries, to be consistent with how the summary ids were
5687 // generated during ModuleSummaryAnalysis.
5688 if (LastStackContextId == *ContextIter)
5689 continue;
5690 LastStackContextId = *ContextIter;
5691 assert(StackIdIndexIter != MIBIter->StackIdIndices.end());
5692 assert(ImportSummary->getStackIdAtIndex(*StackIdIndexIter) ==
5693 *ContextIter);
5694 StackIdIndexIter++;
5695 }
5696 MIBIter++;
5697 }
5698}
5699#endif
5700
5701bool MemProfContextDisambiguation::applyImport(Module &M) {
5702 assert(ImportSummary);
5703 bool Changed = false;
5704
5705 // We also need to clone any aliases that reference cloned functions, because
5706 // the modified callsites may invoke via the alias. Keep track of the aliases
5707 // for each function.
5708 std::map<const Function *, SmallPtrSet<const GlobalAlias *, 1>>
5709 FuncToAliasMap;
5710 for (auto &A : M.aliases()) {
5711 auto *Aliasee = A.getAliaseeObject();
5712 if (auto *F = dyn_cast<Function>(Aliasee))
5713 FuncToAliasMap[F].insert(&A);
5714 }
5715
5716 if (!initializeIndirectCallPromotionInfo(M))
5717 return false;
5718
5719 for (auto &F : M) {
5720 if (F.isDeclaration() || isMemProfClone(F))
5721 continue;
5722
5723 OptimizationRemarkEmitter ORE(&F);
5724
5726 bool ClonesCreated = false;
5727 unsigned NumClonesCreated = 0;
5728 auto CloneFuncIfNeeded = [&](unsigned NumClones, FunctionSummary *FS) {
5729 // We should at least have version 0 which is the original copy.
5730 assert(NumClones > 0);
5731 // If only one copy needed use original.
5732 if (NumClones == 1)
5733 return;
5734 // If we already performed cloning of this function, confirm that the
5735 // requested number of clones matches (the thin link should ensure the
5736 // number of clones for each constituent callsite is consistent within
5737 // each function), before returning.
5738 if (ClonesCreated) {
5739 assert(NumClonesCreated == NumClones);
5740 return;
5741 }
5742 VMaps = createFunctionClones(F, NumClones, M, ORE, FuncToAliasMap, FS);
5743 // The first "clone" is the original copy, which doesn't have a VMap.
5744 assert(VMaps.size() == NumClones - 1);
5745 Changed = true;
5746 ClonesCreated = true;
5747 NumClonesCreated = NumClones;
5748 };
5749
5750 auto CloneCallsite = [&](const CallsiteInfo &StackNode, CallBase *CB,
5751 Function *CalledFunction, FunctionSummary *FS) {
5752 // Perform cloning if not yet done.
5753 CloneFuncIfNeeded(/*NumClones=*/StackNode.Clones.size(), FS);
5754
5755 assert(!isMemProfClone(*CalledFunction));
5756
5757 // Because we update the cloned calls by calling setCalledOperand (see
5758 // comment below), out of an abundance of caution make sure the called
5759 // function was actually the called operand (or its aliasee). We also
5760 // strip pointer casts when looking for calls (to match behavior during
5761 // summary generation), however, with opaque pointers in theory this
5762 // should not be an issue. Note we still clone the current function
5763 // (containing this call) above, as that could be needed for its callers.
5764 auto *GA = dyn_cast_or_null<GlobalAlias>(CB->getCalledOperand());
5765 if (CalledFunction != CB->getCalledOperand() &&
5766 (!GA || CalledFunction != GA->getAliaseeObject())) {
5767 SkippedCallsCloning++;
5768 return;
5769 }
5770 // Update the calls per the summary info.
5771 // Save orig name since it gets updated in the first iteration
5772 // below.
5773 auto CalleeOrigName = CalledFunction->getName();
5774 for (unsigned J = 0; J < StackNode.Clones.size(); J++) {
5775 // If the VMap is empty, this clone was a duplicate of another and was
5776 // created as an alias or a declaration.
5777 if (J > 0 && VMaps[J - 1]->empty())
5778 continue;
5779 // Do nothing if this version calls the original version of its
5780 // callee.
5781 if (!StackNode.Clones[J])
5782 continue;
5783 auto NewF = M.getOrInsertFunction(
5784 getMemProfFuncName(CalleeOrigName, StackNode.Clones[J]),
5785 CalledFunction->getFunctionType());
5786 CallBase *CBClone;
5787 // Copy 0 is the original function.
5788 if (!J)
5789 CBClone = CB;
5790 else
5791 CBClone = cast<CallBase>((*VMaps[J - 1])[CB]);
5792 // Set the called operand directly instead of calling setCalledFunction,
5793 // as the latter mutates the function type on the call. In rare cases
5794 // we may have a slightly different type on a callee function
5795 // declaration due to it being imported from a different module with
5796 // incomplete types. We really just want to change the name of the
5797 // function to the clone, and not make any type changes.
5798 CBClone->setCalledOperand(NewF.getCallee());
5799 ORE.emit(OptimizationRemark(DEBUG_TYPE, "MemprofCall", CBClone)
5800 << ore::NV("Call", CBClone) << " in clone "
5801 << ore::NV("Caller", CBClone->getFunction())
5802 << " assigned to call function clone "
5803 << ore::NV("Callee", NewF.getCallee()));
5804 }
5805 };
5806
5807 // Locate the summary for F.
5808 ValueInfo TheFnVI = findValueInfoForFunc(F, M, ImportSummary);
5809 // If not found, this could be an imported local (see comment in
5810 // findValueInfoForFunc). Skip for now as it will be cloned in its original
5811 // module (where it would have been promoted to global scope so should
5812 // satisfy any reference in this module).
5813 if (!TheFnVI)
5814 continue;
5815
5816 auto *GVSummary =
5817 ImportSummary->findSummaryInModule(TheFnVI, M.getModuleIdentifier());
5818 if (!GVSummary) {
5819 // Must have been imported, use the summary which matches the definition。
5820 // (might be multiple if this was a linkonce_odr).
5821 auto SrcModuleMD = F.getMetadata("thinlto_src_module");
5822 assert(SrcModuleMD &&
5823 "enable-import-metadata is needed to emit thinlto_src_module");
5824 StringRef SrcModule =
5825 dyn_cast<MDString>(SrcModuleMD->getOperand(0))->getString();
5826 for (auto &GVS : TheFnVI.getSummaryList()) {
5827 if (GVS->modulePath() == SrcModule) {
5828 GVSummary = GVS.get();
5829 break;
5830 }
5831 }
5832 assert(GVSummary && GVSummary->modulePath() == SrcModule);
5833 }
5834
5835 // If this was an imported alias skip it as we won't have the function
5836 // summary, and it should be cloned in the original module.
5837 if (isa<AliasSummary>(GVSummary))
5838 continue;
5839
5840 auto *FS = cast<FunctionSummary>(GVSummary->getBaseObject());
5841
5842 if (FS->allocs().empty() && FS->callsites().empty())
5843 continue;
5844
5845 auto SI = FS->callsites().begin();
5846 auto AI = FS->allocs().begin();
5847
5848 // To handle callsite infos synthesized for tail calls which have missing
5849 // frames in the profiled context, map callee VI to the synthesized callsite
5850 // info.
5851 DenseMap<ValueInfo, CallsiteInfo> MapTailCallCalleeVIToCallsite;
5852 // Iterate the callsites for this function in reverse, since we place all
5853 // those synthesized for tail calls at the end.
5854 for (auto CallsiteIt = FS->callsites().rbegin();
5855 CallsiteIt != FS->callsites().rend(); CallsiteIt++) {
5856 auto &Callsite = *CallsiteIt;
5857 // Stop as soon as we see a non-synthesized callsite info (see comment
5858 // above loop). All the entries added for discovered tail calls have empty
5859 // stack ids.
5860 if (!Callsite.StackIdIndices.empty())
5861 break;
5862 MapTailCallCalleeVIToCallsite.insert({Callsite.Callee, Callsite});
5863 }
5864
5865 // Keeps track of needed ICP for the function.
5866 SmallVector<ICallAnalysisData> ICallAnalysisInfo;
5867
5868 // Assume for now that the instructions are in the exact same order
5869 // as when the summary was created, but confirm this is correct by
5870 // matching the stack ids.
5871 for (auto &BB : F) {
5872 for (auto &I : BB) {
5873 auto *CB = dyn_cast<CallBase>(&I);
5874 // Same handling as when creating module summary.
5875 if (!mayHaveMemprofSummary(CB))
5876 continue;
5877
5878 auto *CalledValue = CB->getCalledOperand();
5879 auto *CalledFunction = CB->getCalledFunction();
5880 if (CalledValue && !CalledFunction) {
5881 CalledValue = CalledValue->stripPointerCasts();
5882 // Stripping pointer casts can reveal a called function.
5883 CalledFunction = dyn_cast<Function>(CalledValue);
5884 }
5885 // Check if this is an alias to a function. If so, get the
5886 // called aliasee for the checks below.
5887 if (auto *GA = dyn_cast<GlobalAlias>(CalledValue)) {
5888 assert(!CalledFunction &&
5889 "Expected null called function in callsite for alias");
5890 CalledFunction = dyn_cast<Function>(GA->getAliaseeObject());
5891 }
5892
5893 CallStack<MDNode, MDNode::op_iterator> CallsiteContext(
5894 I.getMetadata(LLVMContext::MD_callsite));
5895 auto *MemProfMD = I.getMetadata(LLVMContext::MD_memprof);
5896
5897 // Include allocs that were already assigned a memprof function
5898 // attribute in the statistics. Only do this for those that do not have
5899 // memprof metadata, since we add an "ambiguous" memprof attribute by
5900 // default.
5901 if (CB->getAttributes().hasFnAttr("memprof") && !MemProfMD) {
5902 CB->getAttributes().getFnAttr("memprof").getValueAsString() == "cold"
5903 ? AllocTypeColdThinBackend++
5904 : AllocTypeNotColdThinBackend++;
5905 OrigAllocsThinBackend++;
5906 AllocVersionsThinBackend++;
5907 if (!MaxAllocVersionsThinBackend)
5908 MaxAllocVersionsThinBackend = 1;
5909 continue;
5910 }
5911
5912 if (MemProfMD) {
5913 // Consult the next alloc node.
5914 assert(AI != FS->allocs().end());
5915 auto &AllocNode = *(AI++);
5916
5917#ifndef NDEBUG
5918 checkAllocContextIds(AllocNode, MemProfMD, CallsiteContext,
5919 ImportSummary);
5920#endif
5921
5922 // Perform cloning if not yet done.
5923 CloneFuncIfNeeded(/*NumClones=*/AllocNode.Versions.size(), FS);
5924
5925 OrigAllocsThinBackend++;
5926 AllocVersionsThinBackend += AllocNode.Versions.size();
5927 if (MaxAllocVersionsThinBackend < AllocNode.Versions.size())
5928 MaxAllocVersionsThinBackend = AllocNode.Versions.size();
5929
5930 // If there is only one version that means we didn't end up
5931 // considering this function for cloning, and in that case the alloc
5932 // will still be none type or should have gotten the default NotCold.
5933 // Skip that after calling clone helper since that does some sanity
5934 // checks that confirm we haven't decided yet that we need cloning.
5935 // We might have a single version that is cold due to the
5936 // MinClonedColdBytePercent heuristic, make sure we don't skip in that
5937 // case.
5938 if (AllocNode.Versions.size() == 1 &&
5939 (AllocationType)AllocNode.Versions[0] != AllocationType::Cold) {
5940 assert((AllocationType)AllocNode.Versions[0] ==
5941 AllocationType::NotCold ||
5942 (AllocationType)AllocNode.Versions[0] ==
5943 AllocationType::None);
5944 UnclonableAllocsThinBackend++;
5945 continue;
5946 }
5947
5948 // All versions should have a singular allocation type.
5949 assert(llvm::none_of(AllocNode.Versions, [](uint8_t Type) {
5950 return Type == ((uint8_t)AllocationType::NotCold |
5951 (uint8_t)AllocationType::Cold);
5952 }));
5953
5954 // Update the allocation types per the summary info.
5955 for (unsigned J = 0; J < AllocNode.Versions.size(); J++) {
5956 // If the VMap is empty, this clone was a duplicate of another and
5957 // was created as an alias or a declaration.
5958 if (J > 0 && VMaps[J - 1]->empty())
5959 continue;
5960 // Ignore any that didn't get an assigned allocation type.
5961 if (AllocNode.Versions[J] == (uint8_t)AllocationType::None)
5962 continue;
5963 AllocationType AllocTy = (AllocationType)AllocNode.Versions[J];
5964 AllocTy == AllocationType::Cold ? AllocTypeColdThinBackend++
5965 : AllocTypeNotColdThinBackend++;
5966 std::string AllocTypeString = getAllocTypeAttributeString(AllocTy);
5967 auto A = llvm::Attribute::get(F.getContext(), "memprof",
5968 AllocTypeString);
5969 CallBase *CBClone;
5970 // Copy 0 is the original function.
5971 if (!J)
5972 CBClone = CB;
5973 else
5974 // Since VMaps are only created for new clones, we index with
5975 // clone J-1 (J==0 is the original clone and does not have a VMaps
5976 // entry).
5977 CBClone = cast<CallBase>((*VMaps[J - 1])[CB]);
5979 CBClone->addFnAttr(A);
5980 ORE.emit(OptimizationRemark(DEBUG_TYPE, "MemprofAttribute", CBClone)
5981 << ore::NV("AllocationCall", CBClone) << " in clone "
5982 << ore::NV("Caller", CBClone->getFunction())
5983 << " marked with memprof allocation attribute "
5984 << ore::NV("Attribute", AllocTypeString));
5985 }
5986 } else if (!CallsiteContext.empty()) {
5987 if (!CalledFunction) {
5988#ifndef NDEBUG
5989 // We should have skipped inline assembly calls.
5990 auto *CI = dyn_cast<CallInst>(CB);
5991 assert(!CI || !CI->isInlineAsm());
5992#endif
5993 // We should have skipped direct calls via a Constant.
5994 assert(CalledValue && !isa<Constant>(CalledValue));
5995
5996 // This is an indirect call, see if we have profile information and
5997 // whether any clones were recorded for the profiled targets (that
5998 // we synthesized CallsiteInfo summary records for when building the
5999 // index).
6000 auto NumClones =
6001 recordICPInfo(CB, FS->callsites(), SI, ICallAnalysisInfo);
6002
6003 // Perform cloning if not yet done. This is done here in case
6004 // we don't need to do ICP, but might need to clone this
6005 // function as it is the target of other cloned calls.
6006 if (NumClones)
6007 CloneFuncIfNeeded(NumClones, FS);
6008 }
6009
6010 else {
6011 // Consult the next callsite node.
6012 assert(SI != FS->callsites().end());
6013 auto &StackNode = *(SI++);
6014
6015#ifndef NDEBUG
6016 // Sanity check that the stack ids match between the summary and
6017 // instruction metadata.
6018 auto StackIdIndexIter = StackNode.StackIdIndices.begin();
6019 for (auto StackId : CallsiteContext) {
6020 assert(StackIdIndexIter != StackNode.StackIdIndices.end());
6021 assert(ImportSummary->getStackIdAtIndex(*StackIdIndexIter) ==
6022 StackId);
6023 StackIdIndexIter++;
6024 }
6025#endif
6026
6027 CloneCallsite(StackNode, CB, CalledFunction, FS);
6028 }
6029 } else if (CB->isTailCall() && CalledFunction) {
6030 // Locate the synthesized callsite info for the callee VI, if any was
6031 // created, and use that for cloning.
6032 ValueInfo CalleeVI =
6033 findValueInfoForFunc(*CalledFunction, M, ImportSummary, &F);
6034 if (CalleeVI && MapTailCallCalleeVIToCallsite.count(CalleeVI)) {
6035 auto Callsite = MapTailCallCalleeVIToCallsite.find(CalleeVI);
6036 assert(Callsite != MapTailCallCalleeVIToCallsite.end());
6037 CloneCallsite(Callsite->second, CB, CalledFunction, FS);
6038 }
6039 }
6040 }
6041 }
6042
6043 // Now do any promotion required for cloning.
6044 performICP(M, FS->callsites(), VMaps, ICallAnalysisInfo, ORE);
6045 }
6046
6047 // We skip some of the functions and instructions above, so remove all the
6048 // metadata in a single sweep here.
6049 for (auto &F : M) {
6050 // We can skip memprof clones because createFunctionClones already strips
6051 // the metadata from the newly created clones.
6052 if (F.isDeclaration() || isMemProfClone(F))
6053 continue;
6054 for (auto &BB : F) {
6055 for (auto &I : BB) {
6056 if (!isa<CallBase>(I))
6057 continue;
6058 I.setMetadata(LLVMContext::MD_memprof, nullptr);
6059 I.setMetadata(LLVMContext::MD_callsite, nullptr);
6060 }
6061 }
6062 }
6063
6064 return Changed;
6065}
6066
6067unsigned MemProfContextDisambiguation::recordICPInfo(
6068 CallBase *CB, ArrayRef<CallsiteInfo> AllCallsites,
6070 SmallVector<ICallAnalysisData> &ICallAnalysisInfo) {
6071 // First see if we have profile information for this indirect call.
6072 uint32_t NumCandidates;
6073 uint64_t TotalCount;
6074 auto CandidateProfileData =
6075 ICallAnalysis->getPromotionCandidatesForInstruction(
6076 CB, TotalCount, NumCandidates, MaxSummaryIndirectEdges);
6077 if (CandidateProfileData.empty())
6078 return 0;
6079
6080 // Iterate through all of the candidate profiled targets along with the
6081 // CallsiteInfo summary records synthesized for them when building the index,
6082 // and see if any are cloned and/or refer to clones.
6083 bool ICPNeeded = false;
6084 unsigned NumClones = 0;
6085 size_t CallsiteInfoStartIndex = std::distance(AllCallsites.begin(), SI);
6086 for (const auto &Candidate : CandidateProfileData) {
6087#ifndef NDEBUG
6088 auto CalleeValueInfo =
6089#endif
6090 ImportSummary->getValueInfo(Candidate.Value);
6091 // We might not have a ValueInfo if this is a distributed
6092 // ThinLTO backend and decided not to import that function.
6093 assert(!CalleeValueInfo || SI->Callee == CalleeValueInfo);
6094 assert(SI != AllCallsites.end());
6095 auto &StackNode = *(SI++);
6096 // See if any of the clones of the indirect callsite for this
6097 // profiled target should call a cloned version of the profiled
6098 // target. We only need to do the ICP here if so.
6099 ICPNeeded |= llvm::any_of(StackNode.Clones,
6100 [](unsigned CloneNo) { return CloneNo != 0; });
6101 // Every callsite in the same function should have been cloned the same
6102 // number of times.
6103 assert(!NumClones || NumClones == StackNode.Clones.size());
6104 NumClones = StackNode.Clones.size();
6105 }
6106 if (!ICPNeeded)
6107 return NumClones;
6108 // Save information for ICP, which is performed later to avoid messing up the
6109 // current function traversal.
6110 ICallAnalysisInfo.push_back({CB, CandidateProfileData.vec(), NumCandidates,
6111 TotalCount, CallsiteInfoStartIndex});
6112 return NumClones;
6113}
6114
6115void MemProfContextDisambiguation::performICP(
6116 Module &M, ArrayRef<CallsiteInfo> AllCallsites,
6117 ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps,
6118 ArrayRef<ICallAnalysisData> ICallAnalysisInfo,
6119 OptimizationRemarkEmitter &ORE) {
6120 // Now do any promotion required for cloning. Specifically, for each
6121 // recorded ICP candidate (which was only recorded because one clone of that
6122 // candidate should call a cloned target), we perform ICP (speculative
6123 // devirtualization) for each clone of the callsite, and update its callee
6124 // to the appropriate clone. Note that the ICP compares against the original
6125 // version of the target, which is what is in the vtable.
6126 for (auto &Info : ICallAnalysisInfo) {
6127 auto *CB = Info.CB;
6128 auto CallsiteIndex = Info.CallsiteInfoStartIndex;
6129 auto TotalCount = Info.TotalCount;
6130 unsigned NumPromoted = 0;
6131 unsigned NumClones = 0;
6132
6133 for (auto &Candidate : Info.CandidateProfileData) {
6134 auto &StackNode = AllCallsites[CallsiteIndex++];
6135
6136 // All calls in the same function must have the same number of clones.
6137 assert(!NumClones || NumClones == StackNode.Clones.size());
6138 NumClones = StackNode.Clones.size();
6139
6140 // See if the target is in the module. If it wasn't imported, it is
6141 // possible that this profile could have been collected on a different
6142 // target (or version of the code), and we need to be conservative
6143 // (similar to what is done in the ICP pass).
6144 Function *TargetFunction = Symtab->getFunction(Candidate.Value);
6145 if (TargetFunction == nullptr ||
6146 // Any ThinLTO global dead symbol removal should have already
6147 // occurred, so it should be safe to promote when the target is a
6148 // declaration.
6149 // TODO: Remove internal option once more fully tested.
6151 TargetFunction->isDeclaration())) {
6152 ORE.emit([&]() {
6153 return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToFindTarget", CB)
6154 << "Memprof cannot promote indirect call: target with md5sum "
6155 << ore::NV("target md5sum", Candidate.Value) << " not found";
6156 });
6157 // FIXME: See if we can use the new declaration importing support to
6158 // at least get the declarations imported for this case. Hot indirect
6159 // targets should have been imported normally, however.
6160 continue;
6161 }
6162
6163 // Check if legal to promote
6164 const char *Reason = nullptr;
6165 if (!isLegalToPromote(*CB, TargetFunction, &Reason)) {
6166 ORE.emit([&]() {
6167 return OptimizationRemarkMissed(DEBUG_TYPE, "UnableToPromote", CB)
6168 << "Memprof cannot promote indirect call to "
6169 << ore::NV("TargetFunction", TargetFunction)
6170 << " with count of " << ore::NV("TotalCount", TotalCount)
6171 << ": " << Reason;
6172 });
6173 continue;
6174 }
6175
6176 assert(!isMemProfClone(*TargetFunction));
6177
6178 // Handle each call clone, applying ICP so that each clone directly
6179 // calls the specified callee clone, guarded by the appropriate ICP
6180 // check.
6181 CallBase *CBClone = CB;
6182 for (unsigned J = 0; J < NumClones; J++) {
6183 // If the VMap is empty, this clone was a duplicate of another and was
6184 // created as an alias or a declaration.
6185 if (J > 0 && VMaps[J - 1]->empty())
6186 continue;
6187 // Copy 0 is the original function.
6188 if (J > 0)
6189 CBClone = cast<CallBase>((*VMaps[J - 1])[CB]);
6190 // We do the promotion using the original name, so that the comparison
6191 // is against the name in the vtable. Then just below, change the new
6192 // direct call to call the cloned function.
6193 auto &DirectCall =
6194 pgo::promoteIndirectCall(*CBClone, TargetFunction, Candidate.Count,
6195 TotalCount, isSamplePGO, &ORE);
6196 auto *TargetToUse = TargetFunction;
6197 // Call original if this version calls the original version of its
6198 // callee.
6199 if (StackNode.Clones[J]) {
6200 TargetToUse =
6201 cast<Function>(M.getOrInsertFunction(
6202 getMemProfFuncName(TargetFunction->getName(),
6203 StackNode.Clones[J]),
6204 TargetFunction->getFunctionType())
6205 .getCallee());
6206 }
6207 DirectCall.setCalledFunction(TargetToUse);
6208 // During matching we generate synthetic VP metadata for indirect calls
6209 // not already having any, from the memprof profile's callee GUIDs. If
6210 // we subsequently promote and inline those callees, we currently lose
6211 // the ability to generate this synthetic VP metadata. Optionally apply
6212 // a noinline attribute to promoted direct calls, where the threshold is
6213 // set to capture synthetic VP metadata targets which get a count of 1.
6215 Candidate.Count < MemProfICPNoInlineThreshold)
6216 DirectCall.setIsNoInline();
6217 ORE.emit(OptimizationRemark(DEBUG_TYPE, "MemprofCall", CBClone)
6218 << ore::NV("Call", CBClone) << " in clone "
6219 << ore::NV("Caller", CBClone->getFunction())
6220 << " promoted and assigned to call function clone "
6221 << ore::NV("Callee", TargetToUse));
6222 }
6223
6224 // Update TotalCount (all clones should get same count above)
6225 TotalCount -= Candidate.Count;
6226 NumPromoted++;
6227 }
6228 // Adjust the MD.prof metadata for all clones, now that we have the new
6229 // TotalCount and the number promoted.
6230 CallBase *CBClone = CB;
6231 for (unsigned J = 0; J < NumClones; J++) {
6232 // If the VMap is empty, this clone was a duplicate of another and was
6233 // created as an alias or a declaration.
6234 if (J > 0 && VMaps[J - 1]->empty())
6235 continue;
6236 // Copy 0 is the original function.
6237 if (J > 0)
6238 CBClone = cast<CallBase>((*VMaps[J - 1])[CB]);
6239 // First delete the old one.
6240 CBClone->setMetadata(LLVMContext::MD_prof, nullptr);
6241 // If all promoted, we don't need the MD.prof metadata.
6242 // Otherwise we need update with the un-promoted records back.
6243 if (TotalCount != 0)
6245 M, *CBClone, ArrayRef(Info.CandidateProfileData).slice(NumPromoted),
6246 TotalCount, IPVK_IndirectCallTarget, Info.NumCandidates);
6247 }
6248 }
6249}
6250
6251template <typename DerivedCCG, typename FuncTy, typename CallTy>
6252bool CallsiteContextGraph<DerivedCCG, FuncTy, CallTy>::process() {
6253 if (DumpCCG) {
6254 dbgs() << "CCG before cloning:\n";
6255 dbgs() << *this;
6256 }
6257 if (ExportToDot)
6258 exportToDot("postbuild");
6259
6260 if (VerifyCCG) {
6261 check();
6262 }
6263
6264 identifyClones();
6265
6266 if (VerifyCCG) {
6267 check();
6268 }
6269
6270 if (DumpCCG) {
6271 dbgs() << "CCG after cloning:\n";
6272 dbgs() << *this;
6273 }
6274 if (ExportToDot)
6275 exportToDot("cloned");
6276
6277 bool Changed = assignFunctions();
6278
6279 if (DumpCCG) {
6280 dbgs() << "CCG after assigning function clones:\n";
6281 dbgs() << *this;
6282 }
6283 if (ExportToDot)
6284 exportToDot("clonefuncassign");
6285
6287 printTotalSizes(errs());
6288
6289 return Changed;
6290}
6291
6292bool MemProfContextDisambiguation::processModule(
6293 Module &M,
6294 llvm::function_ref<OptimizationRemarkEmitter &(Function *)> OREGetter) {
6295
6296 // If we have an import summary, then the cloning decisions were made during
6297 // the thin link on the index. Apply them and return.
6298 if (ImportSummary)
6299 return applyImport(M);
6300
6301 // TODO: If/when other types of memprof cloning are enabled beyond just for
6302 // hot and cold, we will need to change this to individually control the
6303 // AllocationType passed to addStackNodesForMIB during CCG construction.
6304 // Note that we specifically check this after applying imports above, so that
6305 // the option isn't needed to be passed to distributed ThinLTO backend
6306 // clang processes, which won't necessarily have visibility into the linker
6307 // dependences. Instead the information is communicated from the LTO link to
6308 // the backends via the combined summary index.
6309 if (!SupportsHotColdNew)
6310 return false;
6311
6312 ModuleCallsiteContextGraph CCG(M, OREGetter);
6313 return CCG.process();
6314}
6315
6317 const ModuleSummaryIndex *Summary, bool isSamplePGO)
6318 : ImportSummary(Summary), isSamplePGO(isSamplePGO) {
6319 // Check the dot graph printing options once here, to make sure we have valid
6320 // and expected combinations.
6321 if (DotGraphScope == DotScope::Alloc && !AllocIdForDot.getNumOccurrences())
6323 "-memprof-dot-scope=alloc requires -memprof-dot-alloc-id");
6325 !ContextIdForDot.getNumOccurrences())
6327 "-memprof-dot-scope=context requires -memprof-dot-context-id");
6328 if (DotGraphScope == DotScope::All && AllocIdForDot.getNumOccurrences() &&
6329 ContextIdForDot.getNumOccurrences())
6331 "-memprof-dot-scope=all can't have both -memprof-dot-alloc-id and "
6332 "-memprof-dot-context-id");
6333 if (ImportSummary) {
6334 // The MemProfImportSummary should only be used for testing ThinLTO
6335 // distributed backend handling via opt, in which case we don't have a
6336 // summary from the pass pipeline.
6338 return;
6339 }
6340 if (MemProfImportSummary.empty())
6341 return;
6342
6343 auto ReadSummaryFile =
6345 if (!ReadSummaryFile) {
6346 logAllUnhandledErrors(ReadSummaryFile.takeError(), errs(),
6347 "Error loading file '" + MemProfImportSummary +
6348 "': ");
6349 return;
6350 }
6351 auto ImportSummaryForTestingOrErr = getModuleSummaryIndex(**ReadSummaryFile);
6352 if (!ImportSummaryForTestingOrErr) {
6353 logAllUnhandledErrors(ImportSummaryForTestingOrErr.takeError(), errs(),
6354 "Error parsing file '" + MemProfImportSummary +
6355 "': ");
6356 return;
6357 }
6358 ImportSummaryForTesting = std::move(*ImportSummaryForTestingOrErr);
6359 ImportSummary = ImportSummaryForTesting.get();
6360}
6361
6364 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
6365 auto OREGetter = [&](Function *F) -> OptimizationRemarkEmitter & {
6366 return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*F);
6367 };
6368 if (!processModule(M, OREGetter))
6369 return PreservedAnalyses::all();
6370 return PreservedAnalyses::none();
6371}
6372
6374 ModuleSummaryIndex &Index,
6376 isPrevailing) {
6377 // TODO: If/when other types of memprof cloning are enabled beyond just for
6378 // hot and cold, we will need to change this to individually control the
6379 // AllocationType passed to addStackNodesForMIB during CCG construction.
6380 // The index was set from the option, so these should be in sync.
6381 assert(Index.withSupportsHotColdNew() == SupportsHotColdNew);
6382 if (!SupportsHotColdNew)
6383 return;
6384
6385 IndexCallsiteContextGraph CCG(Index, isPrevailing);
6386 CCG.process();
6387}
6388
6389// Strips MemProf attributes and metadata. Can be invoked by the pass pipeline
6390// when we don't have an index that has recorded that we are linking with
6391// allocation libraries containing the necessary APIs for downstream
6392// transformations.
6394 // The profile matcher applies hotness attributes directly for allocations,
6395 // and those will cause us to generate calls to the hot/cold interfaces
6396 // unconditionally. If supports-hot-cold-new was not enabled in the LTO
6397 // link then assume we don't want these calls (e.g. not linking with
6398 // the appropriate library, or otherwise trying to disable this behavior).
6399 bool Changed = false;
6400 for (auto &F : M) {
6401 for (auto &BB : F) {
6402 for (auto &I : BB) {
6403 auto *CI = dyn_cast<CallBase>(&I);
6404 if (!CI)
6405 continue;
6406 if (CI->hasFnAttr("memprof")) {
6407 CI->removeFnAttr("memprof");
6408 Changed = true;
6409 }
6410 if (!CI->hasMetadata(LLVMContext::MD_callsite)) {
6411 assert(!CI->hasMetadata(LLVMContext::MD_memprof));
6412 continue;
6413 }
6414 // Strip off all memprof metadata as it is no longer needed.
6415 // Importantly, this avoids the addition of new memprof attributes
6416 // after inlining propagation.
6417 CI->setMetadata(LLVMContext::MD_memprof, nullptr);
6418 CI->setMetadata(LLVMContext::MD_callsite, nullptr);
6419 Changed = true;
6420 }
6421 }
6422 }
6423 if (!Changed)
6424 return PreservedAnalyses::all();
6425 return PreservedAnalyses::none();
6426}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
AMDGPU Prepare AGPR Alloc
Unify divergent function exit nodes
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
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")
Analysis containing CSE Info
Definition CSEInfo.cpp:27
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
#define DEBUG_TYPE
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
Machine Check Debug Module
This file implements a map that provides insertion order iteration.
static cl::opt< unsigned > TailCallSearchDepth("memprof-tail-call-search-depth", cl::init(5), cl::Hidden, cl::desc("Max depth to recursively search for missing " "frames through tail calls."))
uint64_t ComputeHash(const FunctionSummary *FS, unsigned I)
static cl::opt< DotScope > DotGraphScope("memprof-dot-scope", cl::desc("Scope of graph to export to dot"), cl::Hidden, cl::init(DotScope::All), cl::values(clEnumValN(DotScope::All, "all", "Export full callsite graph"), clEnumValN(DotScope::Alloc, "alloc", "Export only nodes with contexts feeding given " "-memprof-dot-alloc-id"), clEnumValN(DotScope::Context, "context", "Export only nodes with given -memprof-dot-context-id")))
static cl::opt< bool > DoMergeIteration("memprof-merge-iteration", cl::init(true), cl::Hidden, cl::desc("Iteratively apply merging on a node to catch new callers"))
static bool isMemProfClone(const Function &F)
static cl::opt< unsigned > AllocIdForDot("memprof-dot-alloc-id", cl::init(0), cl::Hidden, cl::desc("Id of alloc to export if -memprof-dot-scope=alloc " "or to highlight if -memprof-dot-scope=all"))
static cl::opt< unsigned > ContextIdForDot("memprof-dot-context-id", cl::init(0), cl::Hidden, cl::desc("Id of context to export if -memprof-dot-scope=context or to " "highlight otherwise"))
static cl::opt< bool > ExportToDot("memprof-export-to-dot", cl::init(false), cl::Hidden, cl::desc("Export graph to dot files."))
static void checkEdge(const std::shared_ptr< ContextEdge< DerivedCCG, FuncTy, CallTy > > &Edge)
static cl::opt< bool > AllowRecursiveCallsites("memprof-allow-recursive-callsites", cl::init(true), cl::Hidden, cl::desc("Allow cloning of callsites involved in recursive cycles"))
bool checkColdOrNotCold(uint8_t AllocType)
static ValueInfo findValueInfoForFunc(const Function &F, const Module &M, const ModuleSummaryIndex *ImportSummary, const Function *CallingFunc=nullptr)
static cl::opt< bool > CloneRecursiveContexts("memprof-clone-recursive-contexts", cl::init(true), cl::Hidden, cl::desc("Allow cloning of contexts through recursive cycles"))
static std::string getAllocTypeString(uint8_t AllocTypes)
static cl::opt< unsigned > MemProfICPNoInlineThreshold("memprof-icp-noinline-threshold", cl::init(2), cl::Hidden, cl::desc("Minimum absolute count for promoted target to be inlinable"))
bool DOTGraphTraits< constCallsiteContextGraph< DerivedCCG, FuncTy, CallTy > * >::DoHighlight
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 cl::opt< bool > VerifyCCG("memprof-verify-ccg", cl::init(false), cl::Hidden, cl::desc("Perform verification checks on CallingContextGraph."))
static void checkNode(const ContextNode< DerivedCCG, FuncTy, CallTy > *Node, bool CheckEdges=true)
static cl::opt< bool > MergeClones("memprof-merge-clones", cl::init(true), cl::Hidden, cl::desc("Merge clones before assigning functions"))
static std::string getMemProfFuncName(Twine Base, unsigned CloneNo)
static cl::opt< std::string > MemProfImportSummary("memprof-import-summary", cl::desc("Import summary to use for testing the ThinLTO backend via opt"), cl::Hidden)
static const std::string MemProfCloneSuffix
static void updateSubprogramLinkageName(Function *NewFunc, StringRef Name)
static cl::opt< bool > AllowRecursiveContexts("memprof-allow-recursive-contexts", cl::init(true), cl::Hidden, cl::desc("Allow cloning of contexts having recursive cycles"))
static cl::opt< std::string > DotFilePathPrefix("memprof-dot-file-path-prefix", cl::init(""), cl::Hidden, cl::value_desc("filename"), cl::desc("Specify the path prefix of the MemProf dot files."))
static cl::opt< bool > VerifyNodes("memprof-verify-nodes", cl::init(false), cl::Hidden, cl::desc("Perform frequent verification checks on nodes."))
static void checkAllocContextIds(const AllocInfo &AllocNode, const MDNode *MemProfMD, const CallStack< MDNode, MDNode::op_iterator > &CallsiteContext, const ModuleSummaryIndex *ImportSummary)
static cl::opt< bool > DumpCCG("memprof-dump-ccg", cl::init(false), cl::Hidden, cl::desc("Dump CallingContextGraph to stdout after each stage."))
AllocType
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...
#define P(N)
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
FunctionAnalysisManager FAM
if(PassOpts->AAPipeline)
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)
Definition Statistic.h:171
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:114
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:131
const_pointer iterator
Definition ArrayRef.h:47
iterator begin() const
Definition ArrayRef.h:130
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
void setCalledOperand(Value *V)
Subprogram description. Uses SubclassData1.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
unsigned size() const
Definition DenseMap.h:110
bool empty() const
Definition DenseMap.h:109
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:174
iterator end()
Definition DenseMap.h:81
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:169
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:241
void reserve(size_type NumEntries)
Grow the densemap so that it can contain at least NumEntries items before resizing again.
Definition DenseMap.h:114
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
Function summary information to aid decisions and implementation of importing.
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition Function.h:209
DISubprogram * getSubprogram() const
Get the attached subprogram.
const Function & getFunction() const
Definition Function.h:164
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:359
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...
Definition Globals.cpp:598
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.
Definition Globals.cpp:77
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...
Definition Globals.cpp:328
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
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.
Definition Globals.cpp:93
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....
Definition Globals.cpp:161
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
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.
Metadata node.
Definition Metadata.h:1078
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1442
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1440
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1448
LLVM_ABI TempMDNode clone() const
Create a (temporary) clone of this.
Definition Metadata.cpp:669
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.
Definition Metadata.h:1317
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:608
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
size_type count(const KeyT &Key) const
Definition MapVector.h:150
MemProfContextDisambiguation(const ModuleSummaryIndex *Summary=nullptr, bool isSamplePGO=false)
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
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
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:67
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:285
A NodeSet contains a set of SUnit DAG nodes with additional information that assigns a priority to th...
unsigned size() const
bool insert(SUnit *SU)
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
A discriminated union of two or more pointer types, with the discriminator in the low bit of the poin...
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition Analysis.h:115
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
A class that wrap the SHA1 algorithm.
Definition SHA1.h:27
LLVM_ABI void update(ArrayRef< uint8_t > Data)
Digest more data.
Definition SHA1.cpp:208
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().
Definition SHA1.cpp:288
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.
Definition SmallSet.h:183
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:322
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
Definition DenseSet.h:96
void insert_range(Range &&R)
Definition DenseSet.h:228
size_type size() const
Definition DenseSet.h:87
void swap(DenseSetImpl &RHS)
Definition DenseSet.h:102
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:175
bool erase(const ValueT &V)
Definition DenseSet.h:100
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:180
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.
Definition raw_ostream.h:53
CallInst * Call
Changed
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ Entry
Definition COFF.h:862
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ CE
Windows NT (Windows on ARM)
Definition MCAsmInfo.h:48
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:695
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 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.
DiagnosticInfoOptimizationBase::Argument NV
LLVM_ABI CallBase & promoteIndirectCall(CallBase &CB, Function *F, uint64_t Count, uint64_t TotalCount, bool AttachProfToDirectCall, OptimizationRemarkEmitter *ORE)
uint32_t NodeId
Definition RDFGraph.h:262
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
bool empty() const
Definition BasicBlock.h:101
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
uint64_t read64le(const void *P)
Definition Endian.h:435
void write32le(void *P, uint32_t V)
Definition Endian.h:475
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.
Definition STLExtras.h:316
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.
Definition Error.cpp:65
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
void stable_sort(R &&Range)
Definition STLExtras.h:2106
cl::opt< bool > MemProfReportHintedSizes("memprof-report-hinted-sizes", cl::init(false), cl::Hidden, cl::desc("Report total allocation sizes of hinted allocations"))
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)
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2530
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.
Definition Casting.h:643
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
static cl::opt< bool > MemProfRequireDefinitionForPromotion("memprof-require-definition-for-promotion", cl::init(false), cl::Hidden, cl::desc("Require target function definition when promoting indirect calls"))
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 ...
Definition Casting.h:732
cl::opt< unsigned > MemProfTopNImportant("memprof-top-n-important", cl::init(10), cl::Hidden, cl::desc("Number of largest cold contexts to consider important"))
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.
Definition STLExtras.h:2184
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 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.
Definition STLExtras.h:1150
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)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1744
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...
cl::opt< unsigned > MaxSummaryIndirectEdges("module-summary-max-indirect-edges", cl::init(0), cl::Hidden, cl::desc("Max number of summary edges added from " "indirect call profile metadata"))
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1751
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:167
FunctionAddr VTableAddr Count
Definition InstrProf.h:139
bool set_union(S1Ty &S1, const S2Ty &S2)
set_union(A, B) - Compute A := A u B, return whether A changed.
cl::opt< bool > SupportsHotColdNew
Indicate we are linking with an allocator that supports hot/cold operator new interfaces.
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...
Definition Casting.h:547
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.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:189
cl::opt< bool > EnableMemProfContextDisambiguation
Enable MemProf context disambiguation for thin link.
S1Ty set_difference(const S1Ty &S1, const S2Ty &S2)
set_difference(A, B) - Return A - B
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
Expected< T > errorOrToExpected(ErrorOr< T > &&EO)
Convert an ErrorOr<T> to an Expected<T>.
Definition Error.h:1245
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.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1770
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1945
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.
Definition MIRParser.h:39
cl::opt< bool > MemProfFixupImportant("memprof-fixup-important", cl::init(true), cl::Hidden, cl::desc("Enables edge fixup for important contexts"))
#define N
static std::string getEdgeAttributes(NodeRef, ChildIteratorType ChildIter, GraphType G)
static const ContextNode< DerivedCCG, FuncTy, CallTy > * GetCallee(const EdgePtrTy &P)
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
mapped_iterator< typename std::vector< NodePtrTy >::const_iterator, decltype(&getNode)> nodes_iterator
std::shared_ptr< ContextEdge< DerivedCCG, FuncTy, CallTy > > EdgePtrTy
Summary of memprof metadata on allocations.
std::vector< MIBInfo > MIBs
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
Definition GraphTraits.h:95
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...
Definition Casting.h:34