1 //===- ReduceArguments.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 uninteresting Arguments from declared and defined functions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ReduceArguments.h"
15 #include "Delta.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/IR/Intrinsics.h"
18 #include <set>
19 #include <vector>
20 
21 using namespace llvm;
22 
23 /// Goes over OldF calls and replaces them with a call to NewF
24 static void replaceFunctionCalls(Function &OldF, Function &NewF,
25                                  const std::set<int> &ArgIndexesToKeep) {
26   const auto &Users = OldF.users();
27   for (auto I = Users.begin(), E = Users.end(); I != E; )
28     if (auto *CI = dyn_cast<CallInst>(*I++)) {
29       SmallVector<Value *, 8> Args;
30       for (auto ArgI = CI->arg_begin(), E = CI->arg_end(); ArgI != E; ++ArgI)
31         if (ArgIndexesToKeep.count(ArgI - CI->arg_begin()))
32           Args.push_back(*ArgI);
33 
34       CallInst *NewCI = CallInst::Create(&NewF, Args);
35       NewCI->setCallingConv(NewF.getCallingConv());
36       if (!CI->use_empty())
37         CI->replaceAllUsesWith(NewCI);
38       ReplaceInstWithInst(CI, NewCI);
39     }
40 }
41 
42 /// Returns whether or not this function should be considered a candidate for
43 /// argument removal. Currently, functions with no arguments and intrinsics are
44 /// not considered. Intrinsics aren't considered because their signatures are
45 /// fixed.
46 static bool shouldRemoveArguments(const Function &F) {
47   return !F.arg_empty() && !F.isIntrinsic();
48 }
49 
50 /// Removes out-of-chunk arguments from functions, and modifies their calls
51 /// accordingly. It also removes allocations of out-of-chunk arguments.
52 static void extractArgumentsFromModule(std::vector<Chunk> ChunksToKeep,
53                                        Module *Program) {
54   Oracle O(ChunksToKeep);
55 
56   std::set<Argument *> ArgsToKeep;
57   std::vector<Function *> Funcs;
58   // Get inside-chunk arguments, as well as their parent function
59   for (auto &F : *Program)
60     if (shouldRemoveArguments(F)) {
61       Funcs.push_back(&F);
62       for (auto &A : F.args())
63         if (O.shouldKeep())
64           ArgsToKeep.insert(&A);
65     }
66 
67   for (auto *F : Funcs) {
68     ValueToValueMapTy VMap;
69     std::vector<WeakVH> InstToDelete;
70     for (auto &A : F->args())
71       if (!ArgsToKeep.count(&A)) {
72         // By adding undesired arguments to the VMap, CloneFunction will remove
73         // them from the resulting Function
74         VMap[&A] = UndefValue::get(A.getType());
75         for (auto *U : A.users())
76           if (auto *I = dyn_cast<Instruction>(*&U))
77             InstToDelete.push_back(I);
78       }
79     // Delete any (unique) instruction that uses the argument
80     for (Value *V : InstToDelete) {
81       if (!V)
82         continue;
83       auto *I = cast<Instruction>(V);
84       I->replaceAllUsesWith(UndefValue::get(I->getType()));
85       if (!I->isTerminator())
86         I->eraseFromParent();
87     }
88 
89     // No arguments to reduce
90     if (VMap.empty())
91       continue;
92 
93     std::set<int> ArgIndexesToKeep;
94     for (auto &Arg : enumerate(F->args()))
95       if (ArgsToKeep.count(&Arg.value()))
96         ArgIndexesToKeep.insert(Arg.index());
97 
98     auto *ClonedFunc = CloneFunction(F, VMap);
99     // In order to preserve function order, we move Clone after old Function
100     ClonedFunc->removeFromParent();
101     Program->getFunctionList().insertAfter(F->getIterator(), ClonedFunc);
102 
103     replaceFunctionCalls(*F, *ClonedFunc, ArgIndexesToKeep);
104     // Rename Cloned Function to Old's name
105     std::string FName = std::string(F->getName());
106     F->replaceAllUsesWith(ConstantExpr::getBitCast(ClonedFunc, F->getType()));
107     F->eraseFromParent();
108     ClonedFunc->setName(FName);
109   }
110 }
111 
112 /// Counts the amount of arguments in functions and prints their respective
113 /// name, index, and parent function name
114 static int countArguments(Module *Program) {
115   // TODO: Silence index with --quiet flag
116   outs() << "----------------------------\n";
117   outs() << "Param Index Reference:\n";
118   int ArgsCount = 0;
119   for (auto &F : *Program)
120     if (shouldRemoveArguments(F)) {
121       outs() << "  " << F.getName() << "\n";
122       for (auto &A : F.args())
123         outs() << "\t" << ++ArgsCount << ": " << A.getName() << "\n";
124 
125       outs() << "----------------------------\n";
126     }
127 
128   return ArgsCount;
129 }
130 
131 void llvm::reduceArgumentsDeltaPass(TestRunner &Test) {
132   outs() << "*** Reducing Arguments...\n";
133   int ArgCount = countArguments(Test.getProgram());
134   runDeltaPass(Test, ArgCount, extractArgumentsFromModule);
135 }
136