LLVM 24.0.0git
MergeFunctions.cpp
Go to the documentation of this file.
1//===- MergeFunctions.cpp - Merge identical functions ---------------------===//
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 pass looks for equivalent functions that are mergable and folds them.
10//
11// Order relation is defined on set of functions. It was made through
12// special function comparison procedure that returns
13// 0 when functions are equal,
14// -1 when Left function is less than right function, and
15// 1 for opposite case. We need total-ordering, so we need to maintain
16// four properties on the functions set:
17// a <= a (reflexivity)
18// if a <= b and b <= a then a = b (antisymmetry)
19// if a <= b and b <= c then a <= c (transitivity).
20// for all a and b: a <= b or b <= a (totality).
21//
22// Comparison iterates through each instruction in each basic block.
23// Functions are kept on binary tree. For each new function F we perform
24// lookup in binary tree.
25// In practice it works the following way:
26// -- We define Function* container class with custom "operator<" (FunctionPtr).
27// -- "FunctionPtr" instances are stored in std::set collection, so every
28// std::set::insert operation will give you result in log(N) time.
29//
30// As an optimization, a hash of the function structure is calculated first, and
31// two functions are only compared if they have the same hash. This hash is
32// cheap to compute, and has the property that if function F == G according to
33// the comparison function, then hash(F) == hash(G). This consistency property
34// is critical to ensuring all possible merging opportunities are exploited.
35// Collisions in the hash affect the speed of the pass but not the correctness
36// or determinism of the resulting transformation.
37//
38// When a match is found the functions are folded. If both functions are
39// overridable, we move the functionality into a new internal function and
40// leave two overridable thunks to it.
41//
42//===----------------------------------------------------------------------===//
43//
44// Future work:
45//
46// * virtual functions.
47//
48// Many functions have their address taken by the virtual function table for
49// the object they belong to. However, as long as it's only used for a lookup
50// and call, this is irrelevant, and we'd like to fold such functions.
51//
52// * be smarter about bitcasts.
53//
54// In order to fold functions, we will sometimes add either bitcast instructions
55// or bitcast constant expressions. Unfortunately, this can confound further
56// analysis since the two functions differ where one has a bitcast and the
57// other doesn't. We should learn to look through bitcasts.
58//
59// * Compare complex types with pointer types inside.
60// * Compare cross-reference cases.
61// * Compare complex expressions.
62//
63// All the three issues above could be described as ability to prove that
64// fA == fB == fC == fE == fF == fG in example below:
65//
66// void fA() {
67// fB();
68// }
69// void fB() {
70// fA();
71// }
72//
73// void fE() {
74// fF();
75// }
76// void fF() {
77// fG();
78// }
79// void fG() {
80// fE();
81// }
82//
83// Simplest cross-reference case (fA <--> fB) was implemented in previous
84// versions of MergeFunctions, though it presented only in two function pairs
85// in test-suite (that counts >50k functions)
86// Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A)
87// could cover much more cases.
88//
89//===----------------------------------------------------------------------===//
90
92#include "llvm/ADT/ArrayRef.h"
93#include "llvm/ADT/DenseMap.h"
94#include "llvm/ADT/DenseSet.h"
96#include "llvm/ADT/STLExtras.h"
98#include "llvm/ADT/Statistic.h"
101#include "llvm/IR/Argument.h"
102#include "llvm/IR/BasicBlock.h"
104#include "llvm/IR/DebugLoc.h"
105#include "llvm/IR/DerivedTypes.h"
106#include "llvm/IR/Function.h"
107#include "llvm/IR/GlobalValue.h"
108#include "llvm/IR/IRBuilder.h"
109#include "llvm/IR/InstrTypes.h"
110#include "llvm/IR/Instruction.h"
111#include "llvm/IR/Instructions.h"
113#include "llvm/IR/Metadata.h"
114#include "llvm/IR/Module.h"
115#include "llvm/IR/PassManager.h"
118#include "llvm/IR/Type.h"
119#include "llvm/IR/Use.h"
120#include "llvm/IR/User.h"
121#include "llvm/IR/Value.h"
122#include "llvm/IR/ValueHandle.h"
124#include "llvm/Support/Casting.h"
126#include "llvm/Support/Debug.h"
130#include "llvm/Transforms/IPO.h"
133#include <algorithm>
134#include <cassert>
135#include <cstddef>
136#include <cstdint>
137#include <iterator>
138#include <optional>
139#include <set>
140#include <utility>
141#include <vector>
142
143using namespace llvm;
144
145#define DEBUG_TYPE "mergefunc"
146
147STATISTIC(NumFunctionsMerged, "Number of functions merged");
148STATISTIC(NumThunksWritten, "Number of thunks generated");
149STATISTIC(NumAliasesWritten, "Number of aliases generated");
150STATISTIC(NumDoubleWeak, "Number of new functions created");
151
153 "mergefunc-verify",
154 cl::desc("How many functions in a module could be used for "
155 "MergeFunctions to pass a basic correctness check. "
156 "'0' disables this check. Works only with '-debug' key."),
157 cl::init(0), cl::Hidden);
158
159// Under option -mergefunc-preserve-debug-info we:
160// - Do not create a new function for a thunk.
161// - Retain the debug info for a thunk's parameters (and associated
162// instructions for the debug info) from the entry block.
163// Note: -debug will display the algorithm at work.
164// - Create debug-info for the call (to the shared implementation) made by
165// a thunk and its return value.
166// - Erase the rest of the function, retaining the (minimally sized) entry
167// block to create a thunk.
168// - Preserve a thunk's call site to point to the thunk even when both occur
169// within the same translation unit, to aid debugability. Note that this
170// behaviour differs from the underlying -mergefunc implementation which
171// modifies the thunk's call site to point to the shared implementation
172// when both occur within the same translation unit.
173static cl::opt<bool>
174 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
175 cl::init(false),
176 cl::desc("Preserve debug info in thunk when mergefunc "
177 "transformations are made."));
178
179static cl::opt<bool>
180 MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
181 cl::init(false),
182 cl::desc("Allow mergefunc to create aliases"));
183
184namespace {
185
186class FunctionNode {
187 mutable AssertingVH<Function> F;
188 stable_hash Hash;
189
190public:
191 // Note the hash is recalculated potentially multiple times, but it is cheap.
192 FunctionNode(Function *F) : F(F), Hash(StructuralHash(*F)) {}
193
194 Function *getFunc() const { return F; }
195 stable_hash getHash() const { return Hash; }
196
197 /// Replace the reference to the function F by the function G, assuming their
198 /// implementations are equal.
199 void replaceBy(Function *G) const {
200 F = G;
201 }
202};
203
204/// MergeFunctions finds functions which will generate identical machine code,
205/// by considering all pointer types to be equivalent. Once identified,
206/// MergeFunctions will fold them by replacing a call to one to a call to a
207/// bitcast of the other.
208class MergeFunctions {
209public:
210 explicit MergeFunctions(FunctionAnalysisManager &FAM)
211 : FnTree(FunctionNodeCmp(&GlobalNumbers)), FAM(FAM) {}
212
213 template <typename FuncContainer> bool run(FuncContainer &Functions);
214 DenseMap<Function *, Function *> runOnFunctions(ArrayRef<Function *> Funcs);
215
216 SmallPtrSet<GlobalValue *, 4> &getUsed();
217
218private:
219 // The function comparison operator is provided here so that FunctionNodes do
220 // not need to become larger with another pointer.
221 class FunctionNodeCmp {
222 GlobalNumberState* GlobalNumbers;
223
224 public:
225 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
226
227 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
228 // Order first by hashes, then full function comparison.
229 if (LHS.getHash() != RHS.getHash())
230 return LHS.getHash() < RHS.getHash();
231 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
232 return FCmp.compare() < 0;
233 }
234 };
235 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
236
237 GlobalNumberState GlobalNumbers;
238
239 /// A work queue of functions that may have been modified and should be
240 /// analyzed again.
241 std::vector<WeakTrackingVH> Deferred;
242
243 /// Set of values marked as used in llvm.used and llvm.compiler.used.
244 SmallPtrSet<GlobalValue *, 4> Used;
245
246#ifndef NDEBUG
247 /// Checks the rules of order relation introduced among functions set.
248 /// Returns true, if check has been passed, and false if failed.
249 bool doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist);
250#endif
251
252 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
253 /// equal to one that's already present.
254 bool insert(Function *NewFunction);
255
256 /// Remove a Function from the FnTree and queue it up for a second sweep of
257 /// analysis.
258 void remove(Function *F);
259
260 /// Find the functions that use this Value and remove them from FnTree and
261 /// queue the functions.
262 void removeUsers(Value *V);
263
264 /// Replace all direct calls of Old with calls of New. Will bitcast New if
265 /// necessary to make types match.
266 void replaceDirectCallers(Function *Old, Function *New);
267
268 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
269 /// be converted into a thunk. In either case, it should never be visited
270 /// again.
271 void mergeTwoFunctions(Function *F, Function *G);
272
273 /// Merge \p Src's instruction-level annotations into the corresponding
274 /// instructions of \p Dst. \p Dst is the surviving function; \p Src will be
275 /// erased or rewritten after this call.
276 /// Both functions must be structurally identical.
277 void mergeInstrAnnotations(Function *Dst, Function *Src);
278
279 /// Fill PDIUnrelatedWL with instructions from the entry block that are
280 /// unrelated to parameter related debug info.
281 /// \param PDVRUnrelatedWL The equivalent non-intrinsic debug records.
282 void
283 filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
284 std::vector<Instruction *> &PDIUnrelatedWL,
285 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
286
287 /// Erase the rest of the CFG (i.e. barring the entry block).
288 void eraseTail(Function *G);
289
290 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
291 /// parameter debug info, from the entry block.
292 /// \param PDVRUnrelatedWL contains the equivalent set of non-instruction
293 /// debug-info records.
294 void
295 eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL,
296 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
297
298 /// Replace G with a simple tail call to bitcast(F). Also (unless
299 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
300 /// delete G.
301 void writeThunk(Function *F, Function *G);
302
303 // Replace G with an alias to F (deleting function G)
304 void writeAlias(Function *F, Function *G);
305
306 // If needed, replace G with an alias to F if possible, or a thunk to F if
307 // profitable. Returns false if neither is the case. If \p G is not needed
308 // (i.e. it is discardable and not used), \p G is removed directly.
309 bool writeThunkOrAliasIfNeeded(Function *F, Function *G);
310
311 /// Replace function F with function G in the function tree.
312 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
313
314 /// The set of all distinct functions. Use the insert() and remove() methods
315 /// to modify it. The map allows efficient lookup and deferring of Functions.
316 FnTreeType FnTree;
317
318 // Map functions to the iterators of the FunctionNode which contains them
319 // in the FnTree. This must be updated carefully whenever the FnTree is
320 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
321 // dangling iterators into FnTree. The invariant that preserves this is that
322 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
323 DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
324
325 /// Deleted-New functions mapping
326 DenseMap<Function *, Function *> DelToNewMap;
327
329};
330} // end anonymous namespace
331
338
339SmallPtrSet<GlobalValue *, 4> &MergeFunctions::getUsed() { return Used; }
340
342 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
343 MergeFunctions MF(FAM);
345 collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/false);
346 collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/true);
347 MF.getUsed().insert_range(UsedV);
348 return MF.run(M);
349}
350
354 if (Funcs.empty())
356
357 Module &M = *Funcs.front()->getParent();
358 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
359 MergeFunctions MF(FAM);
360 return MF.runOnFunctions(Funcs);
361}
362
363#ifndef NDEBUG
364bool MergeFunctions::doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist) {
365 if (const unsigned Max = NumFunctionsForVerificationCheck) {
366 unsigned TripleNumber = 0;
367 bool Valid = true;
368
369 dbgs() << "MERGEFUNC-VERIFY: Started for first " << Max << " functions.\n";
370
371 unsigned i = 0;
372 for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
373 E = Worklist.end();
374 I != E && i < Max; ++I, ++i) {
375 unsigned j = i;
376 for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
377 ++J, ++j) {
378 Function *F1 = cast<Function>(*I);
379 Function *F2 = cast<Function>(*J);
380 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
381 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
382
383 // If F1 <= F2, then F2 >= F1, otherwise report failure.
384 if (Res1 != -Res2) {
385 dbgs() << "MERGEFUNC-VERIFY: Non-symmetric; triple: " << TripleNumber
386 << "\n";
387 dbgs() << *F1 << '\n' << *F2 << '\n';
388 Valid = false;
389 }
390
391 if (Res1 == 0)
392 continue;
393
394 unsigned k = j;
395 for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
396 ++k, ++K, ++TripleNumber) {
397 if (K == J)
398 continue;
399
400 Function *F3 = cast<Function>(*K);
401 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
402 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
403
404 bool Transitive = true;
405
406 if (Res1 != 0 && Res1 == Res4) {
407 // F1 > F2, F2 > F3 => F1 > F3
408 Transitive = Res3 == Res1;
409 } else if (Res3 != 0 && Res3 == -Res4) {
410 // F1 > F3, F3 > F2 => F1 > F2
411 Transitive = Res3 == Res1;
412 } else if (Res4 != 0 && -Res3 == Res4) {
413 // F2 > F3, F3 > F1 => F2 > F1
414 Transitive = Res4 == -Res1;
415 }
416
417 if (!Transitive) {
418 dbgs() << "MERGEFUNC-VERIFY: Non-transitive; triple: "
419 << TripleNumber << "\n";
420 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
421 << Res4 << "\n";
422 dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
423 Valid = false;
424 }
425 }
426 }
427 }
428
429 dbgs() << "MERGEFUNC-VERIFY: " << (Valid ? "Passed." : "Failed.") << "\n";
430 return Valid;
431 }
432 return true;
433}
434#endif
435
436/// Check whether \p F has an intrinsic which references
437/// distinct metadata as an operand. The most common
438/// instance of this would be CFI checks for function-local types.
440 for (const BasicBlock &BB : F) {
441 for (const Instruction &I : BB) {
442 if (!isa<IntrinsicInst>(&I))
443 continue;
444
445 for (MetadataAsValue *MDL :
447 if (MDNode *N = dyn_cast<MDNode>(MDL->getMetadata()))
448 if (N->isDistinct())
449 return true;
450 }
451 }
452 }
453 return false;
454}
455
456/// Check whether \p F is eligible for function merging.
458 // Oracle functions of llvm.speculative.load may only be referenced by
459 // llvm.speculative.load, so they can neither become thunks nor be called.
460 return !F.isDeclaration() && !F.hasAvailableExternallyLinkage() &&
461 !F.hasFnAttribute(Attribute::NoIPA) &&
462 !F.hasFnAttribute("oracle-function") &&
464}
465
466inline Function *asPtr(Function *Fn) { return Fn; }
467inline Function *asPtr(Function &Fn) { return &Fn; }
468
469template <typename FuncContainer> bool MergeFunctions::run(FuncContainer &M) {
470 bool Changed = false;
471
472 // All functions in the module, ordered by hash. Functions with a unique
473 // hash value are easily eliminated.
474 std::vector<std::pair<stable_hash, Function *>> HashedFuncs;
475 for (auto &Func : M) {
476 Function *FuncPtr = asPtr(Func);
477 if (isEligibleForMerging(*FuncPtr)) {
478 HashedFuncs.push_back({StructuralHash(*FuncPtr), FuncPtr});
479 }
480 }
481
482 llvm::stable_sort(HashedFuncs, less_first());
483
484 auto S = HashedFuncs.begin();
485 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
486 // If the hash value matches the previous value or the next one, we must
487 // consider merging it. Otherwise it is dropped and never considered again.
488 if ((I != S && std::prev(I)->first == I->first) ||
489 (std::next(I) != IE && std::next(I)->first == I->first)) {
490 Deferred.push_back(WeakTrackingVH(I->second));
491 }
492 }
493
494 do {
495 std::vector<WeakTrackingVH> Worklist;
496 Deferred.swap(Worklist);
497
498 LLVM_DEBUG(doFunctionalCheck(Worklist));
499
500 LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
501 LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
502
503 // Insert functions and merge them.
504 for (WeakTrackingVH &I : Worklist) {
505 if (!I)
506 continue;
508 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
509 !F->hasFnAttribute(Attribute::NoIPA)) {
510 Changed |= insert(F);
511 }
512 }
513 LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
514 } while (!Deferred.empty());
515
516 FnTree.clear();
517 FNodesInTree.clear();
518 GlobalNumbers.clear();
519 Used.clear();
520
521 return Changed;
522}
523
525MergeFunctions::runOnFunctions(ArrayRef<Function *> Funcs) {
526 [[maybe_unused]] bool MergeResult = this->run(Funcs);
527 assert(MergeResult == !DelToNewMap.empty());
528 return this->DelToNewMap;
529}
530
531// Direct calls to Old are about to call New. The verifier requires a location
532// on a call from a function with debug info to a function with debug info, but
533// a call to Old need not have one if Old has no debug info. Give such calls a
534// line 0 location in the caller.
536 if (!New->getSubprogram())
537 return;
538 for (Use &U : Old->uses()) {
539 auto *CB = dyn_cast<CallBase>(U.getUser());
540 if (!CB || !CB->isCallee(&U) || CB->getDebugLoc())
541 continue;
542 if (DISubprogram *SP = CB->getFunction()->getSubprogram())
543 CB->setDebugLoc(DILocation::get(CB->getContext(), 0, 0, SP));
544 }
545}
546
547// Replace direct callers of Old with New.
548void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
549 addMissingCallLocations(Old, New);
550 for (Use &U : make_early_inc_range(Old->uses())) {
551 CallBase *CB = dyn_cast<CallBase>(U.getUser());
552 if (CB && CB->isCallee(&U)) {
553 // Do not copy attributes from the called function to the call-site.
554 // Function comparison ensures that the attributes are the same up to
555 // type congruences in byval(), in which case we need to keep the byval
556 // type of the call-site, not the callee function.
557 remove(CB->getFunction());
558 U.set(New);
559 }
560 }
561}
562
563// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
564// parameter debug info, from the entry block.
565void MergeFunctions::eraseInstsUnrelatedToPDI(
566 std::vector<Instruction *> &PDIUnrelatedWL,
567 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
569 dbgs() << " Erasing instructions (in reverse order of appearance in "
570 "entry block) unrelated to parameter debug info from entry "
571 "block: {\n");
572 while (!PDIUnrelatedWL.empty()) {
573 Instruction *I = PDIUnrelatedWL.back();
574 LLVM_DEBUG(dbgs() << " Deleting Instruction: ");
575 LLVM_DEBUG(I->print(dbgs()));
576 LLVM_DEBUG(dbgs() << "\n");
577 I->eraseFromParent();
578 PDIUnrelatedWL.pop_back();
579 }
580
581 while (!PDVRUnrelatedWL.empty()) {
582 DbgVariableRecord *DVR = PDVRUnrelatedWL.back();
583 LLVM_DEBUG(dbgs() << " Deleting DbgVariableRecord ");
584 LLVM_DEBUG(DVR->print(dbgs()));
585 LLVM_DEBUG(dbgs() << "\n");
586 DVR->eraseFromParent();
587 PDVRUnrelatedWL.pop_back();
588 }
589
590 LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
591 "debug info from entry block. \n");
592}
593
594// Reduce G to its entry block.
595void MergeFunctions::eraseTail(Function *G) {
596 std::vector<BasicBlock *> WorklistBB;
597 for (BasicBlock &BB : drop_begin(*G)) {
598 BB.dropAllReferences();
599 WorklistBB.push_back(&BB);
600 }
601 while (!WorklistBB.empty()) {
602 BasicBlock *BB = WorklistBB.back();
603 BB->eraseFromParent();
604 WorklistBB.pop_back();
605 }
606}
607
608// We are interested in the following instructions from the entry block as being
609// related to parameter debug info:
610// - @llvm.dbg.declare
611// - stores from the incoming parameters to locations on the stack-frame
612// - allocas that create these locations on the stack-frame
613// - @llvm.dbg.value
614// - the entry block's terminator
615// The rest are unrelated to debug info for the parameters; fill up
616// PDIUnrelatedWL with such instructions.
617void MergeFunctions::filterInstsUnrelatedToPDI(
618 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL,
619 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
620 std::set<Instruction *> PDIRelated;
621 std::set<DbgVariableRecord *> PDVRRelated;
622
623 // Work out whether a dbg.value intrinsic or an equivalent DbgVariableRecord
624 // is a parameter to be preserved.
625 auto ExamineDbgValue = [&PDVRRelated](DbgVariableRecord *DbgVal) {
626 LLVM_DEBUG(dbgs() << " Deciding: ");
627 LLVM_DEBUG(DbgVal->print(dbgs()));
628 LLVM_DEBUG(dbgs() << "\n");
629 DILocalVariable *DILocVar = DbgVal->getVariable();
630 if (DILocVar->isParameter()) {
631 LLVM_DEBUG(dbgs() << " Include (parameter): ");
632 LLVM_DEBUG(DbgVal->print(dbgs()));
633 LLVM_DEBUG(dbgs() << "\n");
634 PDVRRelated.insert(DbgVal);
635 } else {
636 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
637 LLVM_DEBUG(DbgVal->print(dbgs()));
638 LLVM_DEBUG(dbgs() << "\n");
639 }
640 };
641
642 auto ExamineDbgDeclare = [&PDIRelated,
643 &PDVRRelated](DbgVariableRecord *DbgDecl) {
644 LLVM_DEBUG(dbgs() << " Deciding: ");
645 LLVM_DEBUG(DbgDecl->print(dbgs()));
646 LLVM_DEBUG(dbgs() << "\n");
647 DILocalVariable *DILocVar = DbgDecl->getVariable();
648 if (DILocVar->isParameter()) {
649 LLVM_DEBUG(dbgs() << " Parameter: ");
650 LLVM_DEBUG(DILocVar->print(dbgs()));
651 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DbgDecl->getAddress());
652 if (AI) {
653 LLVM_DEBUG(dbgs() << " Processing alloca users: ");
654 LLVM_DEBUG(dbgs() << "\n");
655 for (User *U : AI->users()) {
656 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
657 if (Value *Arg = SI->getValueOperand()) {
658 if (isa<Argument>(Arg)) {
659 LLVM_DEBUG(dbgs() << " Include: ");
660 LLVM_DEBUG(AI->print(dbgs()));
661 LLVM_DEBUG(dbgs() << "\n");
662 PDIRelated.insert(AI);
663 LLVM_DEBUG(dbgs() << " Include (parameter): ");
664 LLVM_DEBUG(SI->print(dbgs()));
665 LLVM_DEBUG(dbgs() << "\n");
666 PDIRelated.insert(SI);
667 LLVM_DEBUG(dbgs() << " Include: ");
668 LLVM_DEBUG(DbgDecl->print(dbgs()));
669 LLVM_DEBUG(dbgs() << "\n");
670 PDVRRelated.insert(DbgDecl);
671 } else {
672 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
673 LLVM_DEBUG(SI->print(dbgs()));
674 LLVM_DEBUG(dbgs() << "\n");
675 }
676 }
677 } else {
678 LLVM_DEBUG(dbgs() << " Defer: ");
679 LLVM_DEBUG(U->print(dbgs()));
680 LLVM_DEBUG(dbgs() << "\n");
681 }
682 }
683 } else {
684 LLVM_DEBUG(dbgs() << " Delete (alloca NULL): ");
685 LLVM_DEBUG(DbgDecl->print(dbgs()));
686 LLVM_DEBUG(dbgs() << "\n");
687 }
688 } else {
689 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
690 LLVM_DEBUG(DbgDecl->print(dbgs()));
691 LLVM_DEBUG(dbgs() << "\n");
692 }
693 };
694
695 for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
696 BI != BIE; ++BI) {
697 // Examine DbgVariableRecords as they happen "before" the instruction. Are
698 // they connected to parameters?
699 for (DbgVariableRecord &DVR : filterDbgVars(BI->getDbgRecordRange())) {
700 if (DVR.isDbgValue() || DVR.isDbgAssign()) {
701 ExamineDbgValue(&DVR);
702 } else {
703 assert(DVR.isDbgDeclare());
704 ExamineDbgDeclare(&DVR);
705 }
706 }
707
708 if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
709 LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
710 LLVM_DEBUG(BI->print(dbgs()));
711 LLVM_DEBUG(dbgs() << "\n");
712 PDIRelated.insert(&*BI);
713 } else {
714 LLVM_DEBUG(dbgs() << " Defer: ");
715 LLVM_DEBUG(BI->print(dbgs()));
716 LLVM_DEBUG(dbgs() << "\n");
717 }
718 }
720 dbgs()
721 << " Report parameter debug info related/related instructions: {\n");
722
723 auto IsPDIRelated = [](auto *Rec, auto &Container, auto &UnrelatedCont) {
724 if (Container.find(Rec) == Container.end()) {
725 LLVM_DEBUG(dbgs() << " !PDIRelated: ");
726 LLVM_DEBUG(Rec->print(dbgs()));
727 LLVM_DEBUG(dbgs() << "\n");
728 UnrelatedCont.push_back(Rec);
729 } else {
730 LLVM_DEBUG(dbgs() << " PDIRelated: ");
731 LLVM_DEBUG(Rec->print(dbgs()));
732 LLVM_DEBUG(dbgs() << "\n");
733 }
734 };
735
736 // Collect the set of unrelated instructions and debug records.
737 for (Instruction &I : *GEntryBlock) {
738 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
739 IsPDIRelated(&DVR, PDVRRelated, PDVRUnrelatedWL);
740 IsPDIRelated(&I, PDIRelated, PDIUnrelatedWL);
741 }
742 LLVM_DEBUG(dbgs() << " }\n");
743}
744
745/// Whether this function may be replaced by a forwarding thunk.
747 if (F->isVarArg())
748 return false;
749
750 if (F->hasKernelCallingConv())
751 return false;
752
753 // Don't merge tiny functions using a thunk, since it can just end up
754 // making the function larger.
755 if (F->size() == 1) {
756 if (F->front().size() < 2) {
757 LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName()
758 << " is too small to bother creating a thunk for\n");
759 return false;
760 }
761 }
762 return true;
763}
764
765/// Copy all metadata of a specific kind from one function to another.
767 StringRef Kind) {
769 From->getMetadata(Kind, MDs);
770 for (MDNode *MD : MDs)
771 To->addMetadata(Kind, *MD);
772}
773
774// Replace G with a simple tail call to bitcast(F). Also (unless
775// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
776// delete G. Under MergeFunctionsPDI, we use G itself for creating
777// the thunk as we preserve the debug info (and associated instructions)
778// from G's entry block pertaining to G's incoming arguments which are
779// passed on as corresponding arguments in the call that G makes to F.
780// For better debugability, under MergeFunctionsPDI, we do not modify G's
781// call sites to point to F even when within the same translation unit.
782void MergeFunctions::writeThunk(Function *F, Function *G) {
783 std::optional<uint64_t> GEntryCount = G->getEntryCount();
784 BasicBlock *GEntryBlock = nullptr;
785 std::vector<Instruction *> PDIUnrelatedWL;
786 std::vector<DbgVariableRecord *> PDVRUnrelatedWL;
787 BasicBlock *BB = nullptr;
788 Function *NewG = nullptr;
789 if (MergeFunctionsPDI) {
790 LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
791 "function as thunk; retain original: "
792 << G->getName() << "()\n");
793 GEntryBlock = &G->getEntryBlock();
795 dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
796 "debug info for "
797 << G->getName() << "() {\n");
798 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL, PDVRUnrelatedWL);
799 GEntryBlock->getTerminator()->eraseFromParent();
800 BB = GEntryBlock;
801 } else {
802 NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
803 G->getAddressSpace(), "", G->getParent());
804 NewG->setComdat(G->getComdat());
805 BB = BasicBlock::Create(F->getContext(), "", NewG);
806 }
807
808 IRBuilder<> Builder(BB);
809 Function *H = MergeFunctionsPDI ? G : NewG;
811 unsigned i = 0;
812 FunctionType *FFTy = F->getFunctionType();
813 for (Argument &AI : H->args()) {
814 Args.push_back(Builder.CreateAggregateCast(&AI, FFTy->getParamType(i)));
815 ++i;
816 }
817
818 CallInst *CI = Builder.CreateCall(F, Args);
819 ReturnInst *RI = nullptr;
820 bool isSwiftTailCall = F->getCallingConv() == CallingConv::SwiftTail &&
821 G->getCallingConv() == CallingConv::SwiftTail;
822 CI->setTailCallKind(isSwiftTailCall ? CallInst::TCK_MustTail
824 CI->setCallingConv(F->getCallingConv());
825 CI->setAttributes(F->getAttributes());
826 if (H->getReturnType()->isVoidTy()) {
827 RI = Builder.CreateRetVoid();
828 } else {
829 RI = Builder.CreateRet(Builder.CreateAggregateCast(CI, H->getReturnType()));
830 }
831
832 if (MergeFunctionsPDI) {
833 DISubprogram *DIS = G->getSubprogram();
834 if (DIS) {
835 DebugLoc CIDbgLoc =
836 DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
837 DebugLoc RIDbgLoc =
838 DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
839 CI->setDebugLoc(CIDbgLoc);
840 RI->setDebugLoc(RIDbgLoc);
841 } else {
843 dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
844 << G->getName() << "()\n");
845 }
846 eraseTail(G);
847 eraseInstsUnrelatedToPDI(PDIUnrelatedWL, PDVRUnrelatedWL);
849 dbgs() << "} // End of parameter related debug info filtering for: "
850 << G->getName() << "()\n");
851 } else {
852 NewG->copyAttributesFrom(G);
853 if (GEntryCount)
854 NewG->setEntryCount(*GEntryCount);
855 NewG->takeName(G);
856 // Ensure CFI type metadata is propagated to the new function.
857 copyMetadataIfPresent(G, NewG, "type");
858 copyMetadataIfPresent(G, NewG, "kcfi_type");
859 copyMetadataIfPresent(G, NewG, "callgraph");
860 removeUsers(G);
861 G->replaceAllUsesWith(NewG);
862 G->eraseFromParent();
863 }
864
865 LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
866 ++NumThunksWritten;
867}
868
869// Whether this function may be replaced by an alias
871 if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
872 return false;
873
874 // We should only see linkages supported by aliases here
875 assert(F->hasLocalLinkage() || F->hasExternalLinkage()
876 || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
877 return true;
878}
879
880static bool hasNonLocalAlias(const Function *F) {
881 for (const GlobalAlias &GA : F->getParent()->aliases())
882 if (!GA.hasLocalLinkage() && GA.getAliaseeObject() == F)
883 return true;
884 return false;
885}
886
887/// A COFF weak external must name its target, and a local symbol has no name
888/// the linker can agree on across objects (LNK1227).
889static bool canBeAliasee(const Function *F) {
890 if (!F->getParent()->getTargetTriple().isOSBinFormatCOFF())
891 return true;
892 return F->hasName() && !F->hasLocalLinkage();
893}
894
895// Replace G with an alias to F (deleting function G)
896void MergeFunctions::writeAlias(Function *F, Function *G) {
897 PointerType *PtrType = G->getType();
898 auto *GA =
899 GlobalAlias::create(G->getFunctionType(), PtrType->getAddressSpace(),
900 G->getLinkage(), "", F, G->getParent());
901
902 const MaybeAlign FAlign = F->getAlign();
903 const MaybeAlign GAlign = G->getAlign();
904 if (FAlign || GAlign)
905 F->setAlignment(std::max(FAlign.valueOrOne(), GAlign.valueOrOne()));
906 else
907 F->setAlignment(std::nullopt);
908 GA->takeName(G);
909 GA->setVisibility(G->getVisibility());
910 GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
911
912 removeUsers(G);
913 G->replaceAllUsesWith(GA);
914 G->eraseFromParent();
915
916 LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
917 ++NumAliasesWritten;
918}
919
921 const Function &G) {
922 DenseSet<GlobalValue::GUID> AllImports = F.getImportGUIDs();
923 DenseSet<GlobalValue::GUID> GImports = G.getImportGUIDs();
924 AllImports.insert(GImports.begin(), GImports.end());
925 return AllImports;
926}
927
929 std::optional<uint64_t> FEntryCount = F.getEntryCount();
930 std::optional<uint64_t> GEntryCount = G.getEntryCount();
932 if (!FEntryCount && !GEntryCount && AllImports.empty())
933 return;
934
935 // -1 is a safe placeholder here, getEntryCount() already treats it as
936 // "unknown" (same sentinel SamplePGO uses for no-sample functions), so
937 // it won't look hot to anyone reading the count back.
938 uint64_t Sum = static_cast<uint64_t>(-1);
939 if (FEntryCount || GEntryCount)
940 Sum = SaturatingAdd(FEntryCount ? *FEntryCount : uint64_t{0},
941 GEntryCount ? *GEntryCount : uint64_t{0});
942 F.setEntryCount(Sum, AllImports.empty() ? nullptr : &AllImports);
943}
944
945bool MergeFunctions::writeThunkOrAliasIfNeeded(Function *F, Function *G) {
946 bool ShouldErase =
947 G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI;
948 bool ShouldAlias = canCreateAliasFor(G) && canBeAliasee(F);
949 bool ShouldThunk = canCreateThunkFor(F);
950
951 if (!ShouldErase && !ShouldAlias && !ShouldThunk)
952 return false;
953
954 if (ShouldErase) {
955 G->eraseFromParent();
956 return true;
957 }
958
959 if (ShouldAlias) {
960 writeAlias(F, G);
961 return true;
962 }
963 if (ShouldThunk) {
964 writeThunk(F, G);
965 return true;
966 }
967
968 llvm_unreachable("Erase, alias or thunk must apply");
969}
970
971/// Returns true if \p F is either weak_odr or linkonce_odr.
972static bool isODR(const Function *F) {
973 return F->hasWeakODRLinkage() || F->hasLinkOnceODRLinkage();
974}
975
977 const BasicBlock *BB) {
978 if (auto Count = BFI.getBlockProfileCount(BB))
979 return *Count;
980 return 1;
981}
982
983// Combine the scaled branch_weights of corresponding instructions of F and G.
985 const Instruction *SrcI,
986 const BlockFrequencyInfo &DstBFI,
987 const BlockFrequencyInfo &SrcBFI) {
988 SmallVector<uint32_t, 8> DstWeights, SrcWeights;
989 bool HasDst = extractBranchWeights(*DstI, DstWeights);
990 bool HasSrc = extractBranchWeights(*SrcI, SrcWeights);
991 if (!HasDst && !HasSrc)
992 return;
993
994 uint64_t DstBlockCount = getBlockCountForMerging(DstBFI, DstI->getParent());
995 uint64_t SrcBlockCount = getBlockCountForMerging(SrcBFI, SrcI->getParent());
996
997 uint64_t DstTotal = 0, SrcTotal = 0;
998 if (HasDst)
999 extractProfTotalWeight(*DstI, DstTotal);
1000 if (HasSrc)
1001 extractProfTotalWeight(*SrcI, SrcTotal);
1002
1003 assert((!HasDst || !HasSrc || DstWeights.size() == SrcWeights.size()) &&
1004 "equivalent branch/select instructions must have matching weight "
1005 "arity");
1006 size_t NumWeights = HasDst ? DstWeights.size() : SrcWeights.size();
1007 SmallVector<uint64_t, 8> MergedWeights;
1008 MergedWeights.reserve(NumWeights);
1009 for (size_t I = 0; I < NumWeights; ++I) {
1010 uint64_t DstW = HasDst ? DstWeights[I] : 0;
1011 uint64_t SrcW = HasSrc ? SrcWeights[I] : 0;
1012 // The branch weights are relative within a function. Before merging we
1013 // normalize these to absolute counts.
1014 // (weight * BlockCount / TotalWeight)
1015 uint64_t DstAbs =
1016 DstTotal == 0 ? 0 : mulDivNearest(DstBlockCount, DstW, DstTotal);
1017 uint64_t SrcAbs =
1018 SrcTotal == 0 ? 0 : mulDivNearest(SrcBlockCount, SrcW, SrcTotal);
1019 MergedWeights.push_back(SaturatingAdd(DstAbs, SrcAbs));
1020 }
1021
1022 bool IsExpected =
1024 setFittedBranchWeights(*DstI, MergedWeights, IsExpected);
1025}
1026
1027// Accumulate value profile counts of Instruction I into Merged. Value profile
1028// counts are absolute, not relative branch-style weights.
1031 uint64_t Total = 0;
1033 getValueProfDataFromInst(I, Kind, /*MaxNumValueData=*/UINT32_MAX, Total);
1034 if (VDs.empty())
1035 return;
1036 for (const InstrProfValueData &VD : VDs)
1037 Merged[VD.Value] = SaturatingAdd(Merged[VD.Value], VD.Count);
1038}
1039
1040// Merge (union) value profiles of Dst and Src.
1042 const Instruction *SrcI) {
1043 MDNode *DstProf = DstI->getMetadata(LLVMContext::MD_prof);
1044 MDNode *SrcProf = SrcI->getMetadata(LLVMContext::MD_prof);
1045 bool HasDst = DstProf && isValueProfileMD(DstProf);
1046 bool HasSrc = SrcProf && isValueProfileMD(SrcProf);
1047 if (!HasDst && !HasSrc)
1048 return;
1049
1050 auto *DstKind =
1051 HasDst ? mdconst::dyn_extract<ConstantInt>(DstProf->getOperand(1))
1052 : nullptr;
1053 auto *SrcKind =
1054 HasSrc ? mdconst::dyn_extract<ConstantInt>(SrcProf->getOperand(1))
1055 : nullptr;
1056 if (HasDst && HasSrc && DstKind && SrcKind &&
1057 DstKind->getZExtValue() != SrcKind->getZExtValue()) {
1058 DstI->setMetadata(LLVMContext::MD_prof, nullptr);
1059 return;
1060 }
1061
1062 const ConstantInt *KindCI = DstKind ? DstKind : SrcKind;
1063 if (!KindCI) {
1064 DstI->setMetadata(LLVMContext::MD_prof, nullptr);
1065 return;
1066 }
1067
1068 InstrProfValueKind Kind =
1069 static_cast<InstrProfValueKind>(KindCI->getZExtValue());
1070
1072 if (HasDst)
1073 addValueProfile(*DstI, Kind, Merged);
1074 if (HasSrc)
1075 addValueProfile(*SrcI, Kind, Merged);
1076
1077 if (Merged.empty())
1078 return;
1079
1081 VDs.reserve(Merged.size());
1082 uint64_t Sum = 0;
1083 for (auto &[Value, Count] : Merged) {
1084 VDs.push_back({Value, Count});
1085 Sum = SaturatingAdd(Sum, Count);
1086 }
1087 llvm::sort(VDs, [](const InstrProfValueData &A, const InstrProfValueData &B) {
1088 return A.Count > B.Count;
1089 });
1090 annotateValueSite(*DstI->getFunction()->getParent(), *DstI, VDs, Sum, Kind,
1091 VDs.size());
1092}
1093
1094void MergeFunctions::mergeInstrAnnotations(Function *Dst, Function *Src) {
1095 const BlockFrequencyInfo &DstBFI =
1097 const BlockFrequencyInfo &SrcBFI =
1099
1100 // FunctionComparator guarantees identical CFG topology and instruction
1101 // ordering. Walk the CFGs in RPO rather than function block-list order, as
1102 // equivalent functions need not store their basic blocks in the same order.
1105 for (auto [DstBB, SrcBB] : llvm::zip_equal(DstRPOT, SrcRPOT)) {
1106 for (auto [DstI, SrcI] : llvm::zip_equal(*DstBB, *SrcBB)) {
1107 // Merge poison-generating flags.
1108 DstI.andIRFlags(&SrcI);
1109
1110 MDNode *DstProf = DstI.getMetadata(LLVMContext::MD_prof);
1111 MDNode *SrcProf = SrcI.getMetadata(LLVMContext::MD_prof);
1112 if ((DstProf && isValueProfileMD(DstProf)) ||
1113 (SrcProf && isValueProfileMD(SrcProf)))
1114 mergeValueProfileOnInstructions(&DstI, &SrcI);
1115
1116 // Handle branch weights on SelectInsts here. Terminators are handled
1117 // separately below, outside the instruction loop.
1118 if (isa<SelectInst>(DstI))
1119 mergeBranchWeightsOnInstructions(&DstI, &SrcI, DstBFI, SrcBFI);
1120 }
1121 Instruction *DstTerm = DstBB->getTerminator();
1122 const Instruction *SrcTerm = SrcBB->getTerminator();
1123 mergeBranchWeightsOnInstructions(DstTerm, SrcTerm, DstBFI, SrcBFI);
1124 }
1125
1129 FAM.invalidate(*Dst, PA);
1130}
1131
1132// Merge two equivalent functions. Upon completion, Function G is deleted.
1133void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
1134
1135 std::optional<uint64_t> FEntryCount = F->getEntryCount();
1136
1137 // Create a new thunk that both F and G can call, if F cannot call G directly.
1138 // That is the case if F is either interposable or if G is either weak_odr or
1139 // linkonce_odr.
1140 if (F->isInterposable() || (isODR(F) && isODR(G))) {
1141 assert((!isODR(G) || isODR(F)) &&
1142 "if G is ODR, F must also be ODR due to ordering");
1143
1144 // Both writeThunkOrAliasIfNeeded() calls below must succeed, either because
1145 // we can create aliases for G and NewF, or because a thunk for F is
1146 // profitable. F here has the same signature as NewF below, so that's what
1147 // we check.
1148 if (!canCreateThunkFor(F) &&
1150 return;
1151
1152 // Make them both thunks to the same internal function.
1153 Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
1154 F->getAddressSpace(), "", F->getParent());
1155 NewF->copyAttributesFrom(F);
1156 NewF->takeName(F);
1157 NewF->setComdat(F->getComdat());
1158 F->setComdat(nullptr);
1159 // Ensure CFI type metadata is propagated to the new function.
1160 copyMetadataIfPresent(F, NewF, "type");
1161 copyMetadataIfPresent(F, NewF, "kcfi_type");
1162 copyMetadataIfPresent(F, NewF, "callgraph");
1163 removeUsers(F);
1164 F->replaceAllUsesWith(NewF);
1165
1166 // If G or NewF are (weak|linkonce)_odr, update all callers to call the
1167 // thunk.
1168 if (isODR(G))
1169 replaceDirectCallers(G, F);
1170 if (isODR(F))
1171 replaceDirectCallers(NewF, F);
1172
1173 // We collect alignment before writeThunkOrAliasIfNeeded that overwrites
1174 // NewF and G's content.
1175 const MaybeAlign NewFAlign = NewF->getAlign();
1176 const MaybeAlign GAlign = G->getAlign();
1177
1178 // Merge annotations, while G still has its body.
1179 mergeInstrAnnotations(F, G);
1181
1182 writeThunkOrAliasIfNeeded(F, G);
1183 if (FEntryCount)
1184 NewF->setEntryCount(*FEntryCount);
1185 // NewF becomes thunk/alias to the shared body F, it has no annotations to
1186 // be merged.
1187 writeThunkOrAliasIfNeeded(F, NewF);
1188
1189 if (NewFAlign || GAlign)
1190 F->setAlignment(std::max(NewFAlign.valueOrOne(), GAlign.valueOrOne()));
1191 else
1192 F->setAlignment(std::nullopt);
1193 F->setLinkage(GlobalValue::PrivateLinkage);
1194 ++NumDoubleWeak;
1195 ++NumFunctionsMerged;
1196 } else {
1197 // For better debugability, under MergeFunctionsPDI, we do not modify G's
1198 // call sites to point to F even when within the same translation unit.
1199 if (!G->isInterposable() && !MergeFunctionsPDI) {
1200 // Functions referred to by llvm.used/llvm.compiler.used are special:
1201 // there are uses of the symbol name that are not visible to LLVM,
1202 // usually from inline asm.
1203 // Replacing G also retargets G's aliases at F.
1204 if (G->hasGlobalUnnamedAddr() && !Used.contains(G) &&
1205 (!hasNonLocalAlias(G) || canBeAliasee(F))) {
1206 // G might have been a key in our GlobalNumberState, and it's illegal
1207 // to replace a key in ValueMap<GlobalValue *> with a non-global.
1208 GlobalNumbers.erase(G);
1209 // If G's address is not significant, replace it entirely.
1210 removeUsers(G);
1212 G->replaceAllUsesWith(F);
1213 } else {
1214 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
1215 // above).
1216 replaceDirectCallers(G, F);
1217 }
1218 }
1219
1220 mergeInstrAnnotations(F, G);
1222
1223 // If G was internal then we may have replaced all uses of G with F. If so,
1224 // stop here and delete G. There's no need for a thunk. (See note on
1225 // MergeFunctionsPDI above).
1226 if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
1227 G->eraseFromParent();
1228 ++NumFunctionsMerged;
1229 return;
1230 }
1231
1232 if (writeThunkOrAliasIfNeeded(F, G))
1233 ++NumFunctionsMerged;
1234 }
1235}
1236
1237/// Replace function F by function G.
1238void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
1239 Function *G) {
1240 Function *F = FN.getFunc();
1241 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
1242 "The two functions must be equal");
1243
1244 auto I = FNodesInTree.find(F);
1245 assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
1246 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
1247
1248 FnTreeType::iterator IterToFNInFnTree = I->second;
1249 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
1250 // Remove F -> FN and insert G -> FN
1251 FNodesInTree.erase(I);
1252 FNodesInTree.insert({G, IterToFNInFnTree});
1253 // Replace F with G in FN, which is stored inside the FnTree.
1254 FN.replaceBy(G);
1255}
1256
1257// Ordering for functions that are equal under FunctionComparator
1258static bool isFuncOrderCorrect(const Function *F, const Function *G) {
1259 if (isODR(F) != isODR(G)) {
1260 // ODR functions before non-ODR functions. A ODR function can call a non-ODR
1261 // function if it is not interposable, but not the other way around.
1262 return isODR(G);
1263 }
1264
1265 if (F->isInterposable() != G->isInterposable()) {
1266 // Strong before weak, because the weak function may call the strong
1267 // one, but not the other way around.
1268 return !F->isInterposable();
1269 }
1270
1271 if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
1272 // External before local, because we definitely have to keep the external
1273 // function, but may be able to drop the local one.
1274 return !F->hasLocalLinkage();
1275 }
1276
1277 // Impose a total order (by name) on the replacement of functions. This is
1278 // important when operating on more than one module independently to prevent
1279 // cycles of thunks calling each other when the modules are linked together.
1280 return F->getName() <= G->getName();
1281}
1282
1283// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
1284// that was already inserted.
1285bool MergeFunctions::insert(Function *NewFunction) {
1286 std::pair<FnTreeType::iterator, bool> Result =
1287 FnTree.insert(FunctionNode(NewFunction));
1288
1289 if (Result.second) {
1290 assert(FNodesInTree.count(NewFunction) == 0);
1291 FNodesInTree.insert({NewFunction, Result.first});
1292 LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
1293 << '\n');
1294 return false;
1295 }
1296
1297 const FunctionNode &OldF = *Result.first;
1298
1299 if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
1300 // Swap the two functions.
1301 Function *F = OldF.getFunc();
1302 replaceFunctionInTree(*Result.first, NewFunction);
1303 NewFunction = F;
1304 assert(OldF.getFunc() != F && "Must have swapped the functions.");
1305 }
1306
1307 // Capture the Function pointer before mergeTwoFunctions, which may invalidate
1308 // OldF by erasing it from FnTree via removeUsers().
1309 Function *OldFunc = OldF.getFunc();
1310
1311 LLVM_DEBUG(dbgs() << " " << OldFunc->getName()
1312 << " == " << NewFunction->getName() << '\n');
1313
1314 Function *DeleteF = NewFunction;
1315 mergeTwoFunctions(OldFunc, DeleteF);
1316 this->DelToNewMap.insert({DeleteF, OldFunc});
1317 return true;
1318}
1319
1320// Remove a function from FnTree. If it was already in FnTree, add
1321// it to Deferred so that we'll look at it in the next round.
1322void MergeFunctions::remove(Function *F) {
1323 auto I = FNodesInTree.find(F);
1324 if (I != FNodesInTree.end()) {
1325 LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
1326 FnTree.erase(I->second);
1327 // I->second has been invalidated, remove it from the FNodesInTree map to
1328 // preserve the invariant.
1329 FNodesInTree.erase(I);
1330 Deferred.emplace_back(F);
1331 }
1332}
1333
1334// For each instruction used by the value, remove() the function that contains
1335// the instruction. This should happen right before a call to RAUW.
1336void MergeFunctions::removeUsers(Value *V) {
1337 for (User *U : V->users())
1338 if (auto *I = dyn_cast<Instruction>(U))
1339 remove(I->getFunction());
1340}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use 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
#define H(x, y, z)
Definition MD5.cpp:56
static void mergeEntryCountsAndImportsInto(Function &F, Function &G)
static uint64_t getBlockCountForMerging(const BlockFrequencyInfo &BFI, const BasicBlock *BB)
static void mergeValueProfileOnInstructions(Instruction *DstI, const Instruction *SrcI)
static bool canCreateAliasFor(Function *F)
static bool isEligibleForMerging(Function &F)
Check whether F is eligible for function merging.
static bool isODR(const Function *F)
Returns true if F is either weak_odr or linkonce_odr.
static cl::opt< unsigned > NumFunctionsForVerificationCheck("mergefunc-verify", cl::desc("How many functions in a module could be used for " "MergeFunctions to pass a basic correctness check. " "'0' disables this check. Works only with '-debug' key."), cl::init(0), cl::Hidden)
static bool hasNonLocalAlias(const Function *F)
static DenseSet< GlobalValue::GUID > unionImportGUIDs(const Function &F, const Function &G)
static bool canCreateThunkFor(Function *F)
Whether this function may be replaced by a forwarding thunk.
static bool canBeAliasee(const Function *F)
A COFF weak external must name its target, and a local symbol has no name the linker can agree on acr...
static void addMissingCallLocations(Function *Old, Function *New)
static cl::opt< bool > MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden, cl::init(false), cl::desc("Preserve debug info in thunk when mergefunc " "transformations are made."))
static bool hasDistinctMetadataIntrinsic(const Function &F)
Check whether F has an intrinsic which references distinct metadata as an operand.
Function * asPtr(Function *Fn)
static void addValueProfile(const Instruction &I, InstrProfValueKind Kind, DenseMap< uint64_t, uint64_t > &Merged)
static void copyMetadataIfPresent(Function *From, Function *To, StringRef Kind)
Copy all metadata of a specific kind from one function to another.
static cl::opt< bool > MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden, cl::init(false), cl::desc("Allow mergefunc to create aliases"))
static void mergeBranchWeightsOnInstructions(Instruction *DstI, const Instruction *SrcI, const BlockFrequencyInfo &DstBFI, const BlockFrequencyInfo &SrcBFI)
static bool isFuncOrderCorrect(const Function *F, const Function *G)
This file contains the declarations for metadata subclasses.
FunctionAnalysisManager FAM
This file builds on the ADT/GraphTraits.h file to build a generic graph post order iterator.
This file contains the declarations for profiling metadata utility functions.
This file contains some templates that are useful if you are working with the STL at all.
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
#define LLVM_DEBUG(...)
Definition Debug.h:119
Value * RHS
Value * LHS
an instruction to allocate memory on the stack
void invalidate(IRUnitT &IR, const PreservedAnalyses &PA)
Invalidate cached analyses for an IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
Value handle that asserts if the Value is deleted.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI std::optional< uint64_t > getBlockProfileCount(const BasicBlock *BB) const
Returns the estimated profile count of BB.
Analysis pass which computes BranchProbabilityInfo.
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
bool isCallee(Value::const_user_iterator UI) const
Determine whether the passed iterator points to the callee operand's Use.
void setAttributes(AttributeList A)
Set the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
void setTailCallKind(TailCallKind TCK)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
LLVM_ABI DISubprogram * getSubprogram() const
Get the subprogram for this scope.
Subprogram description. Uses SubclassData1.
LLVM_ABI void eraseFromParent()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
A debug info location.
Definition DebugLoc.h:126
bool empty() const
Definition DenseMap.h:716
unsigned size() const
Definition DenseMap.h:717
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
FunctionComparator - Compares two functions to determine whether or not they will generate machine co...
LLVM_ABI int compare()
Test whether the two functions have equivalent behaviour.
Class to represent function types.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition Function.h:169
MaybeAlign getAlign() const
Returns the alignment of the given function.
Definition Function.h:1022
void setEntryCount(uint64_t Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition Function.cpp:846
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:692
void erase(GlobalValue *Global)
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:287
LLVM_ABI void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
Module * getParent()
Get the module that this global value is contained inside of...
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2909
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
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.
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
LLVMContext & getContext() const
Definition Metadata.h:1245
static LLVM_ABI bool runOnModule(Module &M, ModuleAnalysisManager &AM)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
static LLVM_ABI DenseMap< Function *, Function * > runOnFunctions(ArrayRef< Function * > Funcs, ModuleAnalysisManager &AM)
Metadata wrapper in the Value hierarchy.
Definition Metadata.h:184
LLVM_ABI void print(raw_ostream &OS, const Module *M=nullptr, bool IsForDebug=false) const
Print.
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Class to represent pointers.
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
PreservedAnalyses & abandon()
Mark an analysis as abandoned.
Definition Analysis.h:171
Return a value (possibly void), from a function.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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.
An instruction for storing to memory.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void print(raw_ostream &O, bool IsForDebug=false) const
Implement operator<< on Value.
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:396
Value handle that is nullable, but tries to track the Value.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
const ParentTy * getParent() const
Definition ilist_node.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
@ SwiftTail
This follows the Swift calling convention in how arguments are passed but guarantees tail calls will ...
Definition CallingConv.h:87
int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale)
Compare two scaled numbers.
@ Valid
The data is already valid.
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:707
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
void stable_sort(R &&Range)
Definition STLExtras.h:2132
LLVM_ABI bool extractProfTotalWeight(const MDNode *ProfileData, uint64_t &TotalWeights)
Retrieve the total of all weights from MD_prof data.
detail::zippy< detail::zip_first, T, U, Args... > zip_equal(T &&t, U &&u, Args &&...args)
zip iterator that assumes that all iteratees have the same length.
Definition STLExtras.h:856
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
uint64_t stable_hash
An opaque object representing a stable hash code.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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...
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
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
LLVM_ABI bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
InstrProfValueKind
Definition InstrProf.h:324
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI uint64_t mulDivNearest(uint64_t X, uint64_t Y, uint64_t Z)
Returns (X * Y) / Z rounded by round-half-up, like divideNearest.
LLVM_ABI void setFittedBranchWeights(Instruction &I, ArrayRef< uint64_t > Weights, bool IsExpected, bool ElideAllZero=false)
Variant of setBranchWeights where the Weights will be fit first to uint32_t by shifting right.
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition MathExtras.h:609
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI stable_hash StructuralHash(const Function &F, bool DetailedHash=false)
Returns a hash of the function F.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition Module.cpp:966
#define N
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:135
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1455