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(Oracle &O, Module &Program) {
27   // Record all out-of-chunk functions.
28   std::vector<std::reference_wrapper<Function>> FuncsToRemove;
29   copy_if(Program.functions(), std::back_inserter(FuncsToRemove),
30           [&O](Function &F) {
31             // Intrinsics don't have function bodies that are useful to
32             // reduce. Additionally, intrinsics may have additional operand
33             // constraints. But, do drop intrinsics that are not referenced.
34             return (!F.isIntrinsic() || F.use_empty()) && !O.shouldKeep();
35           });
36 
37   // Then, drop body of each of them. We want to batch this and do nothing else
38   // here so that minimal number of remaining exteranal uses will remain.
39   for (Function &F : FuncsToRemove)
40     F.dropAllReferences();
41 
42   // And finally, we can actually delete them.
43   for (Function &F : FuncsToRemove) {
44     // Replace all *still* remaining uses with undef.
45     F.replaceAllUsesWith(UndefValue::get(F.getType()));
46     // And finally, fully drop it.
47     F.eraseFromParent();
48   }
49 }
50 
51 /// Counts the amount of functions and prints their
52 /// respective name & index
53 static int countFunctions(Module &Program) {
54   // TODO: Silence index with --quiet flag
55   errs() << "----------------------------\n";
56   errs() << "Function Index Reference:\n";
57   int FunctionCount = 0;
58   for (auto &F : Program) {
59     if (F.isIntrinsic() && !F.use_empty())
60       continue;
61 
62     errs() << '\t' << ++FunctionCount << ": " << F.getName() << '\n';
63   }
64 
65   errs() << "----------------------------\n";
66   return FunctionCount;
67 }
68 
69 void llvm::reduceFunctionsDeltaPass(TestRunner &Test) {
70   errs() << "*** Reducing Functions...\n";
71   int Functions = countFunctions(Test.getProgram());
72   runDeltaPass(Test, Functions, extractFunctionsFromModule);
73   errs() << "----------------------------\n";
74 }
75