1 //===- ReduceFunctions.cpp - Specialized Delta Pass -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements a function which calls the Generic Delta pass in order
10 // to reduce functions (and any instruction that calls it) in the provided
11 // Module.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ReduceFunctions.h"
16 #include "Delta.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/IR/Instructions.h"
19 #include <iterator>
20 #include <vector>
21 
22 using namespace llvm;
23 
24 /// Removes all the Defined Functions
25 /// that aren't inside any of the desired Chunks.
26 static void extractFunctionsFromModule(const std::vector<Chunk> &ChunksToKeep,
27                                        Module *Program) {
28   Oracle O(ChunksToKeep);
29 
30   // Record all out-of-chunk functions.
31   std::vector<std::reference_wrapper<Function>> FuncsToRemove;
32   copy_if(Program->functions(), std::back_inserter(FuncsToRemove),
33           [&O](auto &unused) { return !O.shouldKeep(); });
34 
35   // Then, drop body of each of them. We want to batch this and do nothing else
36   // here so that minimal number of remaining exteranal uses will remain.
37   for (Function &F : FuncsToRemove)
38     F.dropAllReferences();
39 
40   // And finally, we can actually delete them.
41   for (Function &F : FuncsToRemove) {
42     // Replace all *still* remaining uses with undef.
43     F.replaceAllUsesWith(UndefValue::get(F.getType()));
44     // And finally, fully drop it.
45     F.eraseFromParent();
46   }
47 }
48 
49 /// Counts the amount of non-declaration functions and prints their
50 /// respective name & index
51 static int countFunctions(Module *Program) {
52   // TODO: Silence index with --quiet flag
53   errs() << "----------------------------\n";
54   errs() << "Function Index Reference:\n";
55   int FunctionCount = 0;
56   for (auto &F : *Program)
57     errs() << "\t" << ++FunctionCount << ": " << F.getName() << "\n";
58 
59   errs() << "----------------------------\n";
60   return FunctionCount;
61 }
62 
63 void llvm::reduceFunctionsDeltaPass(TestRunner &Test) {
64   errs() << "*** Reducing Functions...\n";
65   int Functions = countFunctions(Test.getProgram());
66   runDeltaPass(Test, Functions, extractFunctionsFromModule);
67   errs() << "----------------------------\n";
68 }
69