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 void llvm::reduceFunctionsDeltaPass(TestRunner &Test) {
52   errs() << "*** Reducing Functions...\n";
53   runDeltaPass(Test, extractFunctionsFromModule);
54   errs() << "----------------------------\n";
55 }
56