LLVM 23.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"
94#include "llvm/ADT/Statistic.h"
95#include "llvm/IR/Argument.h"
96#include "llvm/IR/BasicBlock.h"
98#include "llvm/IR/DebugLoc.h"
100#include "llvm/IR/Function.h"
101#include "llvm/IR/GlobalValue.h"
102#include "llvm/IR/IRBuilder.h"
103#include "llvm/IR/InstrTypes.h"
104#include "llvm/IR/Instruction.h"
105#include "llvm/IR/Instructions.h"
107#include "llvm/IR/Module.h"
109#include "llvm/IR/Type.h"
110#include "llvm/IR/Use.h"
111#include "llvm/IR/User.h"
112#include "llvm/IR/Value.h"
113#include "llvm/IR/ValueHandle.h"
114#include "llvm/Support/Casting.h"
116#include "llvm/Support/Debug.h"
119#include "llvm/Transforms/IPO.h"
122#include <algorithm>
123#include <cassert>
124#include <iterator>
125#include <optional>
126#include <set>
127#include <utility>
128#include <vector>
129
130using namespace llvm;
131
132#define DEBUG_TYPE "mergefunc"
133
134STATISTIC(NumFunctionsMerged, "Number of functions merged");
135STATISTIC(NumThunksWritten, "Number of thunks generated");
136STATISTIC(NumAliasesWritten, "Number of aliases generated");
137STATISTIC(NumDoubleWeak, "Number of new functions created");
138
140 "mergefunc-verify",
141 cl::desc("How many functions in a module could be used for "
142 "MergeFunctions to pass a basic correctness check. "
143 "'0' disables this check. Works only with '-debug' key."),
144 cl::init(0), cl::Hidden);
145
146// Under option -mergefunc-preserve-debug-info we:
147// - Do not create a new function for a thunk.
148// - Retain the debug info for a thunk's parameters (and associated
149// instructions for the debug info) from the entry block.
150// Note: -debug will display the algorithm at work.
151// - Create debug-info for the call (to the shared implementation) made by
152// a thunk and its return value.
153// - Erase the rest of the function, retaining the (minimally sized) entry
154// block to create a thunk.
155// - Preserve a thunk's call site to point to the thunk even when both occur
156// within the same translation unit, to aid debugability. Note that this
157// behaviour differs from the underlying -mergefunc implementation which
158// modifies the thunk's call site to point to the shared implementation
159// when both occur within the same translation unit.
160static cl::opt<bool>
161 MergeFunctionsPDI("mergefunc-preserve-debug-info", cl::Hidden,
162 cl::init(false),
163 cl::desc("Preserve debug info in thunk when mergefunc "
164 "transformations are made."));
165
166static cl::opt<bool>
167 MergeFunctionsAliases("mergefunc-use-aliases", cl::Hidden,
168 cl::init(false),
169 cl::desc("Allow mergefunc to create aliases"));
170
171namespace {
172
173class FunctionNode {
174 mutable AssertingVH<Function> F;
175 stable_hash Hash;
176
177public:
178 // Note the hash is recalculated potentially multiple times, but it is cheap.
179 FunctionNode(Function *F) : F(F), Hash(StructuralHash(*F)) {}
180
181 Function *getFunc() const { return F; }
182 stable_hash getHash() const { return Hash; }
183
184 /// Replace the reference to the function F by the function G, assuming their
185 /// implementations are equal.
186 void replaceBy(Function *G) const {
187 F = G;
188 }
189};
190
191/// MergeFunctions finds functions which will generate identical machine code,
192/// by considering all pointer types to be equivalent. Once identified,
193/// MergeFunctions will fold them by replacing a call to one to a call to a
194/// bitcast of the other.
195class MergeFunctions {
196public:
197 MergeFunctions() : FnTree(FunctionNodeCmp(&GlobalNumbers)) {
198 }
199
200 template <typename FuncContainer> bool run(FuncContainer &Functions);
201 DenseMap<Function *, Function *> runOnFunctions(ArrayRef<Function *> F);
202
203 SmallPtrSet<GlobalValue *, 4> &getUsed();
204
205private:
206 // The function comparison operator is provided here so that FunctionNodes do
207 // not need to become larger with another pointer.
208 class FunctionNodeCmp {
209 GlobalNumberState* GlobalNumbers;
210
211 public:
212 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {}
213
214 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const {
215 // Order first by hashes, then full function comparison.
216 if (LHS.getHash() != RHS.getHash())
217 return LHS.getHash() < RHS.getHash();
218 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers);
219 return FCmp.compare() < 0;
220 }
221 };
222 using FnTreeType = std::set<FunctionNode, FunctionNodeCmp>;
223
224 GlobalNumberState GlobalNumbers;
225
226 /// A work queue of functions that may have been modified and should be
227 /// analyzed again.
228 std::vector<WeakTrackingVH> Deferred;
229
230 /// Set of values marked as used in llvm.used and llvm.compiler.used.
231 SmallPtrSet<GlobalValue *, 4> Used;
232
233#ifndef NDEBUG
234 /// Checks the rules of order relation introduced among functions set.
235 /// Returns true, if check has been passed, and false if failed.
236 bool doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist);
237#endif
238
239 /// Insert a ComparableFunction into the FnTree, or merge it away if it's
240 /// equal to one that's already present.
241 bool insert(Function *NewFunction);
242
243 /// Remove a Function from the FnTree and queue it up for a second sweep of
244 /// analysis.
245 void remove(Function *F);
246
247 /// Find the functions that use this Value and remove them from FnTree and
248 /// queue the functions.
249 void removeUsers(Value *V);
250
251 /// Replace all direct calls of Old with calls of New. Will bitcast New if
252 /// necessary to make types match.
253 void replaceDirectCallers(Function *Old, Function *New);
254
255 /// Merge two equivalent functions. Upon completion, G may be deleted, or may
256 /// be converted into a thunk. In either case, it should never be visited
257 /// again.
258 void mergeTwoFunctions(Function *F, Function *G);
259
260 /// Fill PDIUnrelatedWL with instructions from the entry block that are
261 /// unrelated to parameter related debug info.
262 /// \param PDVRUnrelatedWL The equivalent non-intrinsic debug records.
263 void
264 filterInstsUnrelatedToPDI(BasicBlock *GEntryBlock,
265 std::vector<Instruction *> &PDIUnrelatedWL,
266 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
267
268 /// Erase the rest of the CFG (i.e. barring the entry block).
269 void eraseTail(Function *G);
270
271 /// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
272 /// parameter debug info, from the entry block.
273 /// \param PDVRUnrelatedWL contains the equivalent set of non-instruction
274 /// debug-info records.
275 void
276 eraseInstsUnrelatedToPDI(std::vector<Instruction *> &PDIUnrelatedWL,
277 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL);
278
279 /// Replace G with a simple tail call to bitcast(F). Also (unless
280 /// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
281 /// delete G.
282 void writeThunk(Function *F, Function *G);
283
284 // Replace G with an alias to F (deleting function G)
285 void writeAlias(Function *F, Function *G);
286
287 // If needed, replace G with an alias to F if possible, or a thunk to F if
288 // profitable. Returns false if neither is the case. If \p G is not needed
289 // (i.e. it is discardable and not used), \p G is removed directly.
290 bool writeThunkOrAliasIfNeeded(Function *F, Function *G);
291
292 /// Replace function F with function G in the function tree.
293 void replaceFunctionInTree(const FunctionNode &FN, Function *G);
294
295 /// The set of all distinct functions. Use the insert() and remove() methods
296 /// to modify it. The map allows efficient lookup and deferring of Functions.
297 FnTreeType FnTree;
298
299 // Map functions to the iterators of the FunctionNode which contains them
300 // in the FnTree. This must be updated carefully whenever the FnTree is
301 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid
302 // dangling iterators into FnTree. The invariant that preserves this is that
303 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree.
304 DenseMap<AssertingVH<Function>, FnTreeType::iterator> FNodesInTree;
305
306 /// Deleted-New functions mapping
307 DenseMap<Function *, Function *> DelToNewMap;
308};
309} // end anonymous namespace
310
317
318SmallPtrSet<GlobalValue *, 4> &MergeFunctions::getUsed() { return Used; }
319
321 MergeFunctions MF;
323 collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/false);
324 collectUsedGlobalVariables(M, UsedV, /*CompilerUsed=*/true);
325 MF.getUsed().insert_range(UsedV);
326 return MF.run(M);
327}
328
331 MergeFunctions MF;
332 return MF.runOnFunctions(F);
333}
334
335#ifndef NDEBUG
336bool MergeFunctions::doFunctionalCheck(std::vector<WeakTrackingVH> &Worklist) {
337 if (const unsigned Max = NumFunctionsForVerificationCheck) {
338 unsigned TripleNumber = 0;
339 bool Valid = true;
340
341 dbgs() << "MERGEFUNC-VERIFY: Started for first " << Max << " functions.\n";
342
343 unsigned i = 0;
344 for (std::vector<WeakTrackingVH>::iterator I = Worklist.begin(),
345 E = Worklist.end();
346 I != E && i < Max; ++I, ++i) {
347 unsigned j = i;
348 for (std::vector<WeakTrackingVH>::iterator J = I; J != E && j < Max;
349 ++J, ++j) {
350 Function *F1 = cast<Function>(*I);
351 Function *F2 = cast<Function>(*J);
352 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare();
353 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare();
354
355 // If F1 <= F2, then F2 >= F1, otherwise report failure.
356 if (Res1 != -Res2) {
357 dbgs() << "MERGEFUNC-VERIFY: Non-symmetric; triple: " << TripleNumber
358 << "\n";
359 dbgs() << *F1 << '\n' << *F2 << '\n';
360 Valid = false;
361 }
362
363 if (Res1 == 0)
364 continue;
365
366 unsigned k = j;
367 for (std::vector<WeakTrackingVH>::iterator K = J; K != E && k < Max;
368 ++k, ++K, ++TripleNumber) {
369 if (K == J)
370 continue;
371
372 Function *F3 = cast<Function>(*K);
373 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare();
374 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare();
375
376 bool Transitive = true;
377
378 if (Res1 != 0 && Res1 == Res4) {
379 // F1 > F2, F2 > F3 => F1 > F3
380 Transitive = Res3 == Res1;
381 } else if (Res3 != 0 && Res3 == -Res4) {
382 // F1 > F3, F3 > F2 => F1 > F2
383 Transitive = Res3 == Res1;
384 } else if (Res4 != 0 && -Res3 == Res4) {
385 // F2 > F3, F3 > F1 => F2 > F1
386 Transitive = Res4 == -Res1;
387 }
388
389 if (!Transitive) {
390 dbgs() << "MERGEFUNC-VERIFY: Non-transitive; triple: "
391 << TripleNumber << "\n";
392 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", "
393 << Res4 << "\n";
394 dbgs() << *F1 << '\n' << *F2 << '\n' << *F3 << '\n';
395 Valid = false;
396 }
397 }
398 }
399 }
400
401 dbgs() << "MERGEFUNC-VERIFY: " << (Valid ? "Passed." : "Failed.") << "\n";
402 return Valid;
403 }
404 return true;
405}
406#endif
407
408/// Check whether \p F has an intrinsic which references
409/// distinct metadata as an operand. The most common
410/// instance of this would be CFI checks for function-local types.
412 for (const BasicBlock &BB : F) {
413 for (const Instruction &I : BB) {
414 if (!isa<IntrinsicInst>(&I))
415 continue;
416
417 for (Value *Op : I.operands()) {
418 auto *MDL = dyn_cast<MetadataAsValue>(Op);
419 if (!MDL)
420 continue;
421 if (MDNode *N = dyn_cast<MDNode>(MDL->getMetadata()))
422 if (N->isDistinct())
423 return true;
424 }
425 }
426 }
427 return false;
428}
429
430/// Check whether \p F is eligible for function merging.
432 return !F.isDeclaration() && !F.hasAvailableExternallyLinkage() &&
433 !F.hasFnAttribute(Attribute::NoIPA) &&
435}
436
437inline Function *asPtr(Function *Fn) { return Fn; }
438inline Function *asPtr(Function &Fn) { return &Fn; }
439
440template <typename FuncContainer> bool MergeFunctions::run(FuncContainer &M) {
441 bool Changed = false;
442
443 // All functions in the module, ordered by hash. Functions with a unique
444 // hash value are easily eliminated.
445 std::vector<std::pair<stable_hash, Function *>> HashedFuncs;
446 for (auto &Func : M) {
447 Function *FuncPtr = asPtr(Func);
448 if (isEligibleForMerging(*FuncPtr)) {
449 HashedFuncs.push_back({StructuralHash(*FuncPtr), FuncPtr});
450 }
451 }
452
453 llvm::stable_sort(HashedFuncs, less_first());
454
455 auto S = HashedFuncs.begin();
456 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) {
457 // If the hash value matches the previous value or the next one, we must
458 // consider merging it. Otherwise it is dropped and never considered again.
459 if ((I != S && std::prev(I)->first == I->first) ||
460 (std::next(I) != IE && std::next(I)->first == I->first)) {
461 Deferred.push_back(WeakTrackingVH(I->second));
462 }
463 }
464
465 do {
466 std::vector<WeakTrackingVH> Worklist;
467 Deferred.swap(Worklist);
468
469 LLVM_DEBUG(doFunctionalCheck(Worklist));
470
471 LLVM_DEBUG(dbgs() << "size of module: " << M.size() << '\n');
472 LLVM_DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n');
473
474 // Insert functions and merge them.
475 for (WeakTrackingVH &I : Worklist) {
476 if (!I)
477 continue;
479 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() &&
480 !F->hasFnAttribute(Attribute::NoIPA)) {
481 Changed |= insert(F);
482 }
483 }
484 LLVM_DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n');
485 } while (!Deferred.empty());
486
487 FnTree.clear();
488 FNodesInTree.clear();
489 GlobalNumbers.clear();
490 Used.clear();
491
492 return Changed;
493}
494
496MergeFunctions::runOnFunctions(ArrayRef<Function *> F) {
497 [[maybe_unused]] bool MergeResult = this->run(F);
498 assert(MergeResult == !DelToNewMap.empty());
499 return this->DelToNewMap;
500}
501
502// Replace direct callers of Old with New.
503void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) {
504 for (Use &U : make_early_inc_range(Old->uses())) {
505 CallBase *CB = dyn_cast<CallBase>(U.getUser());
506 if (CB && CB->isCallee(&U)) {
507 // Do not copy attributes from the called function to the call-site.
508 // Function comparison ensures that the attributes are the same up to
509 // type congruences in byval(), in which case we need to keep the byval
510 // type of the call-site, not the callee function.
511 remove(CB->getFunction());
512 U.set(New);
513 }
514 }
515}
516
517// Erase the instructions in PDIUnrelatedWL as they are unrelated to the
518// parameter debug info, from the entry block.
519void MergeFunctions::eraseInstsUnrelatedToPDI(
520 std::vector<Instruction *> &PDIUnrelatedWL,
521 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
523 dbgs() << " Erasing instructions (in reverse order of appearance in "
524 "entry block) unrelated to parameter debug info from entry "
525 "block: {\n");
526 while (!PDIUnrelatedWL.empty()) {
527 Instruction *I = PDIUnrelatedWL.back();
528 LLVM_DEBUG(dbgs() << " Deleting Instruction: ");
529 LLVM_DEBUG(I->print(dbgs()));
530 LLVM_DEBUG(dbgs() << "\n");
531 I->eraseFromParent();
532 PDIUnrelatedWL.pop_back();
533 }
534
535 while (!PDVRUnrelatedWL.empty()) {
536 DbgVariableRecord *DVR = PDVRUnrelatedWL.back();
537 LLVM_DEBUG(dbgs() << " Deleting DbgVariableRecord ");
538 LLVM_DEBUG(DVR->print(dbgs()));
539 LLVM_DEBUG(dbgs() << "\n");
540 DVR->eraseFromParent();
541 PDVRUnrelatedWL.pop_back();
542 }
543
544 LLVM_DEBUG(dbgs() << " } // Done erasing instructions unrelated to parameter "
545 "debug info from entry block. \n");
546}
547
548// Reduce G to its entry block.
549void MergeFunctions::eraseTail(Function *G) {
550 std::vector<BasicBlock *> WorklistBB;
551 for (BasicBlock &BB : drop_begin(*G)) {
552 BB.dropAllReferences();
553 WorklistBB.push_back(&BB);
554 }
555 while (!WorklistBB.empty()) {
556 BasicBlock *BB = WorklistBB.back();
557 BB->eraseFromParent();
558 WorklistBB.pop_back();
559 }
560}
561
562// We are interested in the following instructions from the entry block as being
563// related to parameter debug info:
564// - @llvm.dbg.declare
565// - stores from the incoming parameters to locations on the stack-frame
566// - allocas that create these locations on the stack-frame
567// - @llvm.dbg.value
568// - the entry block's terminator
569// The rest are unrelated to debug info for the parameters; fill up
570// PDIUnrelatedWL with such instructions.
571void MergeFunctions::filterInstsUnrelatedToPDI(
572 BasicBlock *GEntryBlock, std::vector<Instruction *> &PDIUnrelatedWL,
573 std::vector<DbgVariableRecord *> &PDVRUnrelatedWL) {
574 std::set<Instruction *> PDIRelated;
575 std::set<DbgVariableRecord *> PDVRRelated;
576
577 // Work out whether a dbg.value intrinsic or an equivalent DbgVariableRecord
578 // is a parameter to be preserved.
579 auto ExamineDbgValue = [&PDVRRelated](DbgVariableRecord *DbgVal) {
580 LLVM_DEBUG(dbgs() << " Deciding: ");
581 LLVM_DEBUG(DbgVal->print(dbgs()));
582 LLVM_DEBUG(dbgs() << "\n");
583 DILocalVariable *DILocVar = DbgVal->getVariable();
584 if (DILocVar->isParameter()) {
585 LLVM_DEBUG(dbgs() << " Include (parameter): ");
586 LLVM_DEBUG(DbgVal->print(dbgs()));
587 LLVM_DEBUG(dbgs() << "\n");
588 PDVRRelated.insert(DbgVal);
589 } else {
590 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
591 LLVM_DEBUG(DbgVal->print(dbgs()));
592 LLVM_DEBUG(dbgs() << "\n");
593 }
594 };
595
596 auto ExamineDbgDeclare = [&PDIRelated,
597 &PDVRRelated](DbgVariableRecord *DbgDecl) {
598 LLVM_DEBUG(dbgs() << " Deciding: ");
599 LLVM_DEBUG(DbgDecl->print(dbgs()));
600 LLVM_DEBUG(dbgs() << "\n");
601 DILocalVariable *DILocVar = DbgDecl->getVariable();
602 if (DILocVar->isParameter()) {
603 LLVM_DEBUG(dbgs() << " Parameter: ");
604 LLVM_DEBUG(DILocVar->print(dbgs()));
605 AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DbgDecl->getAddress());
606 if (AI) {
607 LLVM_DEBUG(dbgs() << " Processing alloca users: ");
608 LLVM_DEBUG(dbgs() << "\n");
609 for (User *U : AI->users()) {
610 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
611 if (Value *Arg = SI->getValueOperand()) {
612 if (isa<Argument>(Arg)) {
613 LLVM_DEBUG(dbgs() << " Include: ");
614 LLVM_DEBUG(AI->print(dbgs()));
615 LLVM_DEBUG(dbgs() << "\n");
616 PDIRelated.insert(AI);
617 LLVM_DEBUG(dbgs() << " Include (parameter): ");
618 LLVM_DEBUG(SI->print(dbgs()));
619 LLVM_DEBUG(dbgs() << "\n");
620 PDIRelated.insert(SI);
621 LLVM_DEBUG(dbgs() << " Include: ");
622 LLVM_DEBUG(DbgDecl->print(dbgs()));
623 LLVM_DEBUG(dbgs() << "\n");
624 PDVRRelated.insert(DbgDecl);
625 } else {
626 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
627 LLVM_DEBUG(SI->print(dbgs()));
628 LLVM_DEBUG(dbgs() << "\n");
629 }
630 }
631 } else {
632 LLVM_DEBUG(dbgs() << " Defer: ");
633 LLVM_DEBUG(U->print(dbgs()));
634 LLVM_DEBUG(dbgs() << "\n");
635 }
636 }
637 } else {
638 LLVM_DEBUG(dbgs() << " Delete (alloca NULL): ");
639 LLVM_DEBUG(DbgDecl->print(dbgs()));
640 LLVM_DEBUG(dbgs() << "\n");
641 }
642 } else {
643 LLVM_DEBUG(dbgs() << " Delete (!parameter): ");
644 LLVM_DEBUG(DbgDecl->print(dbgs()));
645 LLVM_DEBUG(dbgs() << "\n");
646 }
647 };
648
649 for (BasicBlock::iterator BI = GEntryBlock->begin(), BIE = GEntryBlock->end();
650 BI != BIE; ++BI) {
651 // Examine DbgVariableRecords as they happen "before" the instruction. Are
652 // they connected to parameters?
653 for (DbgVariableRecord &DVR : filterDbgVars(BI->getDbgRecordRange())) {
654 if (DVR.isDbgValue() || DVR.isDbgAssign()) {
655 ExamineDbgValue(&DVR);
656 } else {
657 assert(DVR.isDbgDeclare());
658 ExamineDbgDeclare(&DVR);
659 }
660 }
661
662 if (BI->isTerminator() && &*BI == GEntryBlock->getTerminator()) {
663 LLVM_DEBUG(dbgs() << " Will Include Terminator: ");
664 LLVM_DEBUG(BI->print(dbgs()));
665 LLVM_DEBUG(dbgs() << "\n");
666 PDIRelated.insert(&*BI);
667 } else {
668 LLVM_DEBUG(dbgs() << " Defer: ");
669 LLVM_DEBUG(BI->print(dbgs()));
670 LLVM_DEBUG(dbgs() << "\n");
671 }
672 }
674 dbgs()
675 << " Report parameter debug info related/related instructions: {\n");
676
677 auto IsPDIRelated = [](auto *Rec, auto &Container, auto &UnrelatedCont) {
678 if (Container.find(Rec) == Container.end()) {
679 LLVM_DEBUG(dbgs() << " !PDIRelated: ");
680 LLVM_DEBUG(Rec->print(dbgs()));
681 LLVM_DEBUG(dbgs() << "\n");
682 UnrelatedCont.push_back(Rec);
683 } else {
684 LLVM_DEBUG(dbgs() << " PDIRelated: ");
685 LLVM_DEBUG(Rec->print(dbgs()));
686 LLVM_DEBUG(dbgs() << "\n");
687 }
688 };
689
690 // Collect the set of unrelated instructions and debug records.
691 for (Instruction &I : *GEntryBlock) {
692 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
693 IsPDIRelated(&DVR, PDVRRelated, PDVRUnrelatedWL);
694 IsPDIRelated(&I, PDIRelated, PDIUnrelatedWL);
695 }
696 LLVM_DEBUG(dbgs() << " }\n");
697}
698
699/// Whether this function may be replaced by a forwarding thunk.
701 if (F->isVarArg())
702 return false;
703
704 if (F->hasKernelCallingConv())
705 return false;
706
707 // Don't merge tiny functions using a thunk, since it can just end up
708 // making the function larger.
709 if (F->size() == 1) {
710 if (F->front().size() < 2) {
711 LLVM_DEBUG(dbgs() << "canCreateThunkFor: " << F->getName()
712 << " is too small to bother creating a thunk for\n");
713 return false;
714 }
715 }
716 return true;
717}
718
719/// Copy all metadata of a specific kind from one function to another.
721 StringRef Kind) {
723 From->getMetadata(Kind, MDs);
724 for (MDNode *MD : MDs)
725 To->addMetadata(Kind, *MD);
726}
727
728// Replace G with a simple tail call to bitcast(F). Also (unless
729// MergeFunctionsPDI holds) replace direct uses of G with bitcast(F),
730// delete G. Under MergeFunctionsPDI, we use G itself for creating
731// the thunk as we preserve the debug info (and associated instructions)
732// from G's entry block pertaining to G's incoming arguments which are
733// passed on as corresponding arguments in the call that G makes to F.
734// For better debugability, under MergeFunctionsPDI, we do not modify G's
735// call sites to point to F even when within the same translation unit.
736void MergeFunctions::writeThunk(Function *F, Function *G) {
737 std::optional<uint64_t> GEC = G->getEntryCount();
738 BasicBlock *GEntryBlock = nullptr;
739 std::vector<Instruction *> PDIUnrelatedWL;
740 std::vector<DbgVariableRecord *> PDVRUnrelatedWL;
741 BasicBlock *BB = nullptr;
742 Function *NewG = nullptr;
743 if (MergeFunctionsPDI) {
744 LLVM_DEBUG(dbgs() << "writeThunk: (MergeFunctionsPDI) Do not create a new "
745 "function as thunk; retain original: "
746 << G->getName() << "()\n");
747 GEntryBlock = &G->getEntryBlock();
749 dbgs() << "writeThunk: (MergeFunctionsPDI) filter parameter related "
750 "debug info for "
751 << G->getName() << "() {\n");
752 filterInstsUnrelatedToPDI(GEntryBlock, PDIUnrelatedWL, PDVRUnrelatedWL);
753 GEntryBlock->getTerminator()->eraseFromParent();
754 BB = GEntryBlock;
755 } else {
756 NewG = Function::Create(G->getFunctionType(), G->getLinkage(),
757 G->getAddressSpace(), "", G->getParent());
758 NewG->setComdat(G->getComdat());
759 BB = BasicBlock::Create(F->getContext(), "", NewG);
760 }
761
762 IRBuilder<> Builder(BB);
763 Function *H = MergeFunctionsPDI ? G : NewG;
765 unsigned i = 0;
766 FunctionType *FFTy = F->getFunctionType();
767 for (Argument &AI : H->args()) {
768 Args.push_back(Builder.CreateAggregateCast(&AI, FFTy->getParamType(i)));
769 ++i;
770 }
771
772 CallInst *CI = Builder.CreateCall(F, Args);
773 ReturnInst *RI = nullptr;
774 bool isSwiftTailCall = F->getCallingConv() == CallingConv::SwiftTail &&
775 G->getCallingConv() == CallingConv::SwiftTail;
776 CI->setTailCallKind(isSwiftTailCall ? CallInst::TCK_MustTail
778 CI->setCallingConv(F->getCallingConv());
779 CI->setAttributes(F->getAttributes());
780 if (H->getReturnType()->isVoidTy()) {
781 RI = Builder.CreateRetVoid();
782 } else {
783 RI = Builder.CreateRet(Builder.CreateAggregateCast(CI, H->getReturnType()));
784 }
785
786 if (MergeFunctionsPDI) {
787 DISubprogram *DIS = G->getSubprogram();
788 if (DIS) {
789 DebugLoc CIDbgLoc =
790 DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
791 DebugLoc RIDbgLoc =
792 DILocation::get(DIS->getContext(), DIS->getScopeLine(), 0, DIS);
793 CI->setDebugLoc(CIDbgLoc);
794 RI->setDebugLoc(RIDbgLoc);
795 } else {
797 dbgs() << "writeThunk: (MergeFunctionsPDI) No DISubprogram for "
798 << G->getName() << "()\n");
799 }
800 eraseTail(G);
801 eraseInstsUnrelatedToPDI(PDIUnrelatedWL, PDVRUnrelatedWL);
803 dbgs() << "} // End of parameter related debug info filtering for: "
804 << G->getName() << "()\n");
805 } else {
806 NewG->copyAttributesFrom(G);
807 if (GEC)
808 NewG->setEntryCount(*GEC);
809 NewG->takeName(G);
810 // Ensure CFI type metadata is propagated to the new function.
811 copyMetadataIfPresent(G, NewG, "type");
812 copyMetadataIfPresent(G, NewG, "kcfi_type");
813 copyMetadataIfPresent(G, NewG, "callgraph");
814 removeUsers(G);
815 G->replaceAllUsesWith(NewG);
816 G->eraseFromParent();
817 }
818
819 LLVM_DEBUG(dbgs() << "writeThunk: " << H->getName() << '\n');
820 ++NumThunksWritten;
821}
822
823// Whether this function may be replaced by an alias
825 if (!MergeFunctionsAliases || !F->hasGlobalUnnamedAddr())
826 return false;
827
828 // We should only see linkages supported by aliases here
829 assert(F->hasLocalLinkage() || F->hasExternalLinkage()
830 || F->hasWeakLinkage() || F->hasLinkOnceLinkage());
831 return true;
832}
833
834// Replace G with an alias to F (deleting function G)
835void MergeFunctions::writeAlias(Function *F, Function *G) {
836 PointerType *PtrType = G->getType();
837 auto *GA =
838 GlobalAlias::create(G->getFunctionType(), PtrType->getAddressSpace(),
839 G->getLinkage(), "", F, G->getParent());
840
841 const MaybeAlign FAlign = F->getAlign();
842 const MaybeAlign GAlign = G->getAlign();
843 if (FAlign || GAlign)
844 F->setAlignment(std::max(FAlign.valueOrOne(), GAlign.valueOrOne()));
845 else
846 F->setAlignment(std::nullopt);
847 GA->takeName(G);
848 GA->setVisibility(G->getVisibility());
849 GA->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
850
851 removeUsers(G);
852 G->replaceAllUsesWith(GA);
853 G->eraseFromParent();
854
855 LLVM_DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n');
856 ++NumAliasesWritten;
857}
858
859// If needed, replace G with an alias to F if possible, or a thunk to F if
860// profitable. Returns false if neither is the case. If \p G is not needed (i.e.
861// it is discardable and unused), \p G is removed directly.
862bool MergeFunctions::writeThunkOrAliasIfNeeded(Function *F, Function *G) {
863 if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
864 G->eraseFromParent();
865 return true;
866 }
867 if (canCreateAliasFor(G)) {
868 writeAlias(F, G);
869 return true;
870 }
871 if (canCreateThunkFor(F)) {
872 writeThunk(F, G);
873 return true;
874 }
875 return false;
876}
877
878/// Returns true if \p F is either weak_odr or linkonce_odr.
879static bool isODR(const Function *F) {
880 return F->hasWeakODRLinkage() || F->hasLinkOnceODRLinkage();
881}
882
883static void mergeEntryCountsInto(Function *F, std::optional<uint64_t> FC,
884 std::optional<uint64_t> GC) {
885 if (!FC && !GC)
886 return;
887 uint64_t Sum = SaturatingAdd(FC ? *FC : uint64_t{0}, GC ? *GC : uint64_t{0});
888 F->setEntryCount(Sum);
889}
890
891// Merge two equivalent functions. Upon completion, Function G is deleted.
892void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) {
893
894 std::optional<uint64_t> FEC = F->getEntryCount();
895 std::optional<uint64_t> GEC = G->getEntryCount();
896
897 // Create a new thunk that both F and G can call, if F cannot call G directly.
898 // That is the case if F is either interposable or if G is either weak_odr or
899 // linkonce_odr.
900 if (F->isInterposable() || (isODR(F) && isODR(G))) {
901 assert((!isODR(G) || isODR(F)) &&
902 "if G is ODR, F must also be ODR due to ordering");
903
904 // Both writeThunkOrAliasIfNeeded() calls below must succeed, either because
905 // we can create aliases for G and NewF, or because a thunk for F is
906 // profitable. F here has the same signature as NewF below, so that's what
907 // we check.
908 if (!canCreateThunkFor(F) &&
910 return;
911
912 // Make them both thunks to the same internal function.
913 Function *NewF = Function::Create(F->getFunctionType(), F->getLinkage(),
914 F->getAddressSpace(), "", F->getParent());
915 NewF->copyAttributesFrom(F);
916 NewF->takeName(F);
917 NewF->setComdat(F->getComdat());
918 F->setComdat(nullptr);
919 // Ensure CFI type metadata is propagated to the new function.
920 copyMetadataIfPresent(F, NewF, "type");
921 copyMetadataIfPresent(F, NewF, "kcfi_type");
922 copyMetadataIfPresent(F, NewF, "callgraph");
923 removeUsers(F);
924 F->replaceAllUsesWith(NewF);
925
926 // If G or NewF are (weak|linkonce)_odr, update all callers to call the
927 // thunk.
928 if (isODR(G))
929 replaceDirectCallers(G, F);
930 if (isODR(F))
931 replaceDirectCallers(NewF, F);
932
933 // We collect alignment before writeThunkOrAliasIfNeeded that overwrites
934 // NewF and G's content.
935 const MaybeAlign NewFAlign = NewF->getAlign();
936 const MaybeAlign GAlign = G->getAlign();
937
938 writeThunkOrAliasIfNeeded(F, G);
939 if (FEC)
940 NewF->setEntryCount(*FEC);
941 writeThunkOrAliasIfNeeded(F, NewF);
942
943 if (NewFAlign || GAlign)
944 F->setAlignment(std::max(NewFAlign.valueOrOne(), GAlign.valueOrOne()));
945 else
946 F->setAlignment(std::nullopt);
947 F->setLinkage(GlobalValue::PrivateLinkage);
948 // The private shared implementation accumulates both symbols' entries
949 // (FEC + GEC), while each ODR thunk retains its own per-symbol entry count.
950 mergeEntryCountsInto(F, FEC, GEC);
951 ++NumDoubleWeak;
952 ++NumFunctionsMerged;
953 } else {
954 // For better debugability, under MergeFunctionsPDI, we do not modify G's
955 // call sites to point to F even when within the same translation unit.
956 if (!G->isInterposable() && !MergeFunctionsPDI) {
957 // Functions referred to by llvm.used/llvm.compiler.used are special:
958 // there are uses of the symbol name that are not visible to LLVM,
959 // usually from inline asm.
960 if (G->hasGlobalUnnamedAddr() && !Used.contains(G)) {
961 // G might have been a key in our GlobalNumberState, and it's illegal
962 // to replace a key in ValueMap<GlobalValue *> with a non-global.
963 GlobalNumbers.erase(G);
964 // If G's address is not significant, replace it entirely.
965 removeUsers(G);
966 G->replaceAllUsesWith(F);
967 } else {
968 // Redirect direct callers of G to F. (See note on MergeFunctionsPDI
969 // above).
970 replaceDirectCallers(G, F);
971 }
972 }
973
974 // If G was internal then we may have replaced all uses of G with F. If so,
975 // stop here and delete G. There's no need for a thunk. (See note on
976 // MergeFunctionsPDI above).
977 if (G->isDiscardableIfUnused() && G->use_empty() && !MergeFunctionsPDI) {
978 mergeEntryCountsInto(F, FEC, GEC);
979 G->eraseFromParent();
980 ++NumFunctionsMerged;
981 return;
982 }
983
984 if (writeThunkOrAliasIfNeeded(F, G)) {
985 mergeEntryCountsInto(F, FEC, GEC);
986 ++NumFunctionsMerged;
987 }
988 }
989}
990
991/// Replace function F by function G.
992void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN,
993 Function *G) {
994 Function *F = FN.getFunc();
995 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 &&
996 "The two functions must be equal");
997
998 auto I = FNodesInTree.find(F);
999 assert(I != FNodesInTree.end() && "F should be in FNodesInTree");
1000 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G");
1001
1002 FnTreeType::iterator IterToFNInFnTree = I->second;
1003 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree.");
1004 // Remove F -> FN and insert G -> FN
1005 FNodesInTree.erase(I);
1006 FNodesInTree.insert({G, IterToFNInFnTree});
1007 // Replace F with G in FN, which is stored inside the FnTree.
1008 FN.replaceBy(G);
1009}
1010
1011// Ordering for functions that are equal under FunctionComparator
1012static bool isFuncOrderCorrect(const Function *F, const Function *G) {
1013 if (isODR(F) != isODR(G)) {
1014 // ODR functions before non-ODR functions. A ODR function can call a non-ODR
1015 // function if it is not interposable, but not the other way around.
1016 return isODR(G);
1017 }
1018
1019 if (F->isInterposable() != G->isInterposable()) {
1020 // Strong before weak, because the weak function may call the strong
1021 // one, but not the other way around.
1022 return !F->isInterposable();
1023 }
1024
1025 if (F->hasLocalLinkage() != G->hasLocalLinkage()) {
1026 // External before local, because we definitely have to keep the external
1027 // function, but may be able to drop the local one.
1028 return !F->hasLocalLinkage();
1029 }
1030
1031 // Impose a total order (by name) on the replacement of functions. This is
1032 // important when operating on more than one module independently to prevent
1033 // cycles of thunks calling each other when the modules are linked together.
1034 return F->getName() <= G->getName();
1035}
1036
1037// Insert a ComparableFunction into the FnTree, or merge it away if equal to one
1038// that was already inserted.
1039bool MergeFunctions::insert(Function *NewFunction) {
1040 std::pair<FnTreeType::iterator, bool> Result =
1041 FnTree.insert(FunctionNode(NewFunction));
1042
1043 if (Result.second) {
1044 assert(FNodesInTree.count(NewFunction) == 0);
1045 FNodesInTree.insert({NewFunction, Result.first});
1046 LLVM_DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName()
1047 << '\n');
1048 return false;
1049 }
1050
1051 const FunctionNode &OldF = *Result.first;
1052
1053 if (!isFuncOrderCorrect(OldF.getFunc(), NewFunction)) {
1054 // Swap the two functions.
1055 Function *F = OldF.getFunc();
1056 replaceFunctionInTree(*Result.first, NewFunction);
1057 NewFunction = F;
1058 assert(OldF.getFunc() != F && "Must have swapped the functions.");
1059 }
1060
1061 // Capture the Function pointer before mergeTwoFunctions, which may invalidate
1062 // OldF by erasing it from FnTree via removeUsers().
1063 Function *OldFunc = OldF.getFunc();
1064
1065 LLVM_DEBUG(dbgs() << " " << OldFunc->getName()
1066 << " == " << NewFunction->getName() << '\n');
1067
1068 Function *DeleteF = NewFunction;
1069 mergeTwoFunctions(OldFunc, DeleteF);
1070 this->DelToNewMap.insert({DeleteF, OldFunc});
1071 return true;
1072}
1073
1074// Remove a function from FnTree. If it was already in FnTree, add
1075// it to Deferred so that we'll look at it in the next round.
1076void MergeFunctions::remove(Function *F) {
1077 auto I = FNodesInTree.find(F);
1078 if (I != FNodesInTree.end()) {
1079 LLVM_DEBUG(dbgs() << "Deferred " << F->getName() << ".\n");
1080 FnTree.erase(I->second);
1081 // I->second has been invalidated, remove it from the FNodesInTree map to
1082 // preserve the invariant.
1083 FNodesInTree.erase(I);
1084 Deferred.emplace_back(F);
1085 }
1086}
1087
1088// For each instruction used by the value, remove() the function that contains
1089// the instruction. This should happen right before a call to RAUW.
1090void MergeFunctions::removeUsers(Value *V) {
1091 for (User *U : V->users())
1092 if (auto *I = dyn_cast<Instruction>(U))
1093 remove(I->getFunction());
1094}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Module.h This file contains the declarations for the Module class.
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 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 canCreateThunkFor(Function *F)
Whether this function may be replaced by a forwarding thunk.
static void mergeEntryCountsInto(Function *F, std::optional< uint64_t > FC, std::optional< uint64_t > GC)
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 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 bool isFuncOrderCorrect(const Function *F, const Function *G)
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
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
Value handle that asserts if the Value is deleted.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:474
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:461
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
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)
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
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:168
MaybeAlign getAlign() const
Returns the alignment of the given function.
Definition Function.h:1011
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:838
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:630
void erase(GlobalValue *Global)
LLVM_ABI void setComdat(Comdat *C)
Definition Globals.cpp:225
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.
@ 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:2848
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.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Metadata node.
Definition Metadata.h:1069
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1554
LLVMContext & getContext() const
Definition Metadata.h:1233
static LLVM_ABI DenseMap< Function *, Function * > runOnFunctions(ArrayRef< Function * > F)
static LLVM_ABI bool runOnModule(Module &M)
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
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:67
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
Return a value (possibly void), from a function.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
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< user_iterator > users()
Definition Value.h:426
iterator_range< use_iterator > uses()
Definition Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:400
Value handle that is nullable, but tries to track the Value.
Changed
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)
DXILDebugInfoMap run(Module &M)
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:315
void stable_sort(R &&Range)
Definition STLExtras.h:2116
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:633
uint64_t stable_hash
An opaque object representing a stable hash code.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
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
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
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:898
#define N
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition Alignment.h:130
Function object to check whether the first component of a container supported by std::get (like std::...
Definition STLExtras.h:1439