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