1cb58558cSMatthew Simpson //===- CalledValuePropagation.cpp - Propagate called values -----*- C++ -*-===//
2cb58558cSMatthew Simpson //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6cb58558cSMatthew Simpson //
7cb58558cSMatthew Simpson //===----------------------------------------------------------------------===//
8cb58558cSMatthew Simpson //
9cb58558cSMatthew Simpson // This file implements a transformation that attaches !callees metadata to
10cb58558cSMatthew Simpson // indirect call sites. For a given call site, the metadata, if present,
11cb58558cSMatthew Simpson // indicates the set of functions the call site could possibly target at
12cb58558cSMatthew Simpson // run-time. This metadata is added to indirect call sites when the set of
13cb58558cSMatthew Simpson // possible targets can be determined by analysis and is known to be small. The
14cb58558cSMatthew Simpson // analysis driving the transformation is similar to constant propagation and
15cb58558cSMatthew Simpson // makes uses of the generic sparse propagation solver.
16cb58558cSMatthew Simpson //
17cb58558cSMatthew Simpson //===----------------------------------------------------------------------===//
18cb58558cSMatthew Simpson 
19cb58558cSMatthew Simpson #include "llvm/Transforms/IPO/CalledValuePropagation.h"
20cb58558cSMatthew Simpson #include "llvm/Analysis/SparsePropagation.h"
21cb58558cSMatthew Simpson #include "llvm/Analysis/ValueLatticeUtils.h"
22cb58558cSMatthew Simpson #include "llvm/IR/InstVisitor.h"
23cb58558cSMatthew Simpson #include "llvm/IR/MDBuilder.h"
2405da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
25*4c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
26cb58558cSMatthew Simpson #include "llvm/Transforms/IPO.h"
27cb58558cSMatthew Simpson using namespace llvm;
28cb58558cSMatthew Simpson 
29cb58558cSMatthew Simpson #define DEBUG_TYPE "called-value-propagation"
30cb58558cSMatthew Simpson 
31cb58558cSMatthew Simpson /// The maximum number of functions to track per lattice value. Once the number
32cb58558cSMatthew Simpson /// of functions a call site can possibly target exceeds this threshold, it's
33cb58558cSMatthew Simpson /// lattice value becomes overdefined. The number of possible lattice values is
34cb58558cSMatthew Simpson /// bounded by Ch(F, M), where F is the number of functions in the module and M
35cb58558cSMatthew Simpson /// is MaxFunctionsPerValue. As such, this value should be kept very small. We
36cb58558cSMatthew Simpson /// likely can't do anything useful for call sites with a large number of
37cb58558cSMatthew Simpson /// possible targets, anyway.
38cb58558cSMatthew Simpson static cl::opt<unsigned> MaxFunctionsPerValue(
39cb58558cSMatthew Simpson     "cvp-max-functions-per-value", cl::Hidden, cl::init(4),
40cb58558cSMatthew Simpson     cl::desc("The maximum number of functions to track per lattice value"));
41cb58558cSMatthew Simpson 
42cb58558cSMatthew Simpson namespace {
43cb58558cSMatthew Simpson /// To enable interprocedural analysis, we assign LLVM values to the following
44cb58558cSMatthew Simpson /// groups. The register group represents SSA registers, the return group
45cb58558cSMatthew Simpson /// represents the return values of functions, and the memory group represents
46cb58558cSMatthew Simpson /// in-memory values. An LLVM Value can technically be in more than one group.
47cb58558cSMatthew Simpson /// It's necessary to distinguish these groups so we can, for example, track a
48cb58558cSMatthew Simpson /// global variable separately from the value stored at its location.
49cb58558cSMatthew Simpson enum class IPOGrouping { Register, Return, Memory };
50cb58558cSMatthew Simpson 
51cb58558cSMatthew Simpson /// Our LatticeKeys are PointerIntPairs composed of LLVM values and groupings.
52cb58558cSMatthew Simpson using CVPLatticeKey = PointerIntPair<Value *, 2, IPOGrouping>;
53cb58558cSMatthew Simpson 
54cb58558cSMatthew Simpson /// The lattice value type used by our custom lattice function. It holds the
55cb58558cSMatthew Simpson /// lattice state, and a set of functions.
56cb58558cSMatthew Simpson class CVPLatticeVal {
57cb58558cSMatthew Simpson public:
58cb58558cSMatthew Simpson   /// The states of the lattice values. Only the FunctionSet state is
59cb58558cSMatthew Simpson   /// interesting. It indicates the set of functions to which an LLVM value may
60cb58558cSMatthew Simpson   /// refer.
61cb58558cSMatthew Simpson   enum CVPLatticeStateTy { Undefined, FunctionSet, Overdefined, Untracked };
62cb58558cSMatthew Simpson 
63cb58558cSMatthew Simpson   /// Comparator for sorting the functions set. We want to keep the order
64cb58558cSMatthew Simpson   /// deterministic for testing, etc.
65cb58558cSMatthew Simpson   struct Compare {
66cb58558cSMatthew Simpson     bool operator()(const Function *LHS, const Function *RHS) const {
67cb58558cSMatthew Simpson       return LHS->getName() < RHS->getName();
68cb58558cSMatthew Simpson     }
69cb58558cSMatthew Simpson   };
70cb58558cSMatthew Simpson 
71cb58558cSMatthew Simpson   CVPLatticeVal() : LatticeState(Undefined) {}
72cb58558cSMatthew Simpson   CVPLatticeVal(CVPLatticeStateTy LatticeState) : LatticeState(LatticeState) {}
73c8bd5449SBenjamin Kramer   CVPLatticeVal(std::vector<Function *> &&Functions)
74c8bd5449SBenjamin Kramer       : LatticeState(FunctionSet), Functions(std::move(Functions)) {
75c8bd5449SBenjamin Kramer     assert(std::is_sorted(this->Functions.begin(), this->Functions.end(),
76c8bd5449SBenjamin Kramer                           Compare()));
77c8bd5449SBenjamin Kramer   }
78cb58558cSMatthew Simpson 
79cb58558cSMatthew Simpson   /// Get a reference to the functions held by this lattice value. The number
80cb58558cSMatthew Simpson   /// of functions will be zero for states other than FunctionSet.
81c8bd5449SBenjamin Kramer   const std::vector<Function *> &getFunctions() const {
82cb58558cSMatthew Simpson     return Functions;
83cb58558cSMatthew Simpson   }
84cb58558cSMatthew Simpson 
85cb58558cSMatthew Simpson   /// Returns true if the lattice value is in the FunctionSet state.
86cb58558cSMatthew Simpson   bool isFunctionSet() const { return LatticeState == FunctionSet; }
87cb58558cSMatthew Simpson 
88cb58558cSMatthew Simpson   bool operator==(const CVPLatticeVal &RHS) const {
89cb58558cSMatthew Simpson     return LatticeState == RHS.LatticeState && Functions == RHS.Functions;
90cb58558cSMatthew Simpson   }
91cb58558cSMatthew Simpson 
92cb58558cSMatthew Simpson   bool operator!=(const CVPLatticeVal &RHS) const {
93cb58558cSMatthew Simpson     return LatticeState != RHS.LatticeState || Functions != RHS.Functions;
94cb58558cSMatthew Simpson   }
95cb58558cSMatthew Simpson 
96cb58558cSMatthew Simpson private:
97cb58558cSMatthew Simpson   /// Holds the state this lattice value is in.
98cb58558cSMatthew Simpson   CVPLatticeStateTy LatticeState;
99cb58558cSMatthew Simpson 
100cb58558cSMatthew Simpson   /// Holds functions indicating the possible targets of call sites. This set
101cb58558cSMatthew Simpson   /// is empty for lattice values in the undefined, overdefined, and untracked
102cb58558cSMatthew Simpson   /// states. The maximum size of the set is controlled by
103cb58558cSMatthew Simpson   /// MaxFunctionsPerValue. Since most LLVM values are expected to be in
104cb58558cSMatthew Simpson   /// uninteresting states (i.e., overdefined), CVPLatticeVal objects should be
105cb58558cSMatthew Simpson   /// small and efficiently copyable.
106c8bd5449SBenjamin Kramer   // FIXME: This could be a TinyPtrVector and/or merge with LatticeState.
107c8bd5449SBenjamin Kramer   std::vector<Function *> Functions;
108cb58558cSMatthew Simpson };
109cb58558cSMatthew Simpson 
110cb58558cSMatthew Simpson /// The custom lattice function used by the generic sparse propagation solver.
111cb58558cSMatthew Simpson /// It handles merging lattice values and computing new lattice values for
112cb58558cSMatthew Simpson /// constants, arguments, values returned from trackable functions, and values
113cb58558cSMatthew Simpson /// located in trackable global variables. It also computes the lattice values
114cb58558cSMatthew Simpson /// that change as a result of executing instructions.
115cb58558cSMatthew Simpson class CVPLatticeFunc
116cb58558cSMatthew Simpson     : public AbstractLatticeFunction<CVPLatticeKey, CVPLatticeVal> {
117cb58558cSMatthew Simpson public:
118cb58558cSMatthew Simpson   CVPLatticeFunc()
119cb58558cSMatthew Simpson       : AbstractLatticeFunction(CVPLatticeVal(CVPLatticeVal::Undefined),
120cb58558cSMatthew Simpson                                 CVPLatticeVal(CVPLatticeVal::Overdefined),
121cb58558cSMatthew Simpson                                 CVPLatticeVal(CVPLatticeVal::Untracked)) {}
122cb58558cSMatthew Simpson 
123cb58558cSMatthew Simpson   /// Compute and return a CVPLatticeVal for the given CVPLatticeKey.
124cb58558cSMatthew Simpson   CVPLatticeVal ComputeLatticeVal(CVPLatticeKey Key) override {
125cb58558cSMatthew Simpson     switch (Key.getInt()) {
126cb58558cSMatthew Simpson     case IPOGrouping::Register:
127cb58558cSMatthew Simpson       if (isa<Instruction>(Key.getPointer())) {
128cb58558cSMatthew Simpson         return getUndefVal();
129cb58558cSMatthew Simpson       } else if (auto *A = dyn_cast<Argument>(Key.getPointer())) {
130cb58558cSMatthew Simpson         if (canTrackArgumentsInterprocedurally(A->getParent()))
131cb58558cSMatthew Simpson           return getUndefVal();
132cb58558cSMatthew Simpson       } else if (auto *C = dyn_cast<Constant>(Key.getPointer())) {
133cb58558cSMatthew Simpson         return computeConstant(C);
134cb58558cSMatthew Simpson       }
135cb58558cSMatthew Simpson       return getOverdefinedVal();
136cb58558cSMatthew Simpson     case IPOGrouping::Memory:
137cb58558cSMatthew Simpson     case IPOGrouping::Return:
138cb58558cSMatthew Simpson       if (auto *GV = dyn_cast<GlobalVariable>(Key.getPointer())) {
139cb58558cSMatthew Simpson         if (canTrackGlobalVariableInterprocedurally(GV))
140cb58558cSMatthew Simpson           return computeConstant(GV->getInitializer());
141cb58558cSMatthew Simpson       } else if (auto *F = cast<Function>(Key.getPointer()))
142cb58558cSMatthew Simpson         if (canTrackReturnsInterprocedurally(F))
143cb58558cSMatthew Simpson           return getUndefVal();
144cb58558cSMatthew Simpson     }
145cb58558cSMatthew Simpson     return getOverdefinedVal();
146cb58558cSMatthew Simpson   }
147cb58558cSMatthew Simpson 
148cb58558cSMatthew Simpson   /// Merge the two given lattice values. The interesting cases are merging two
149cb58558cSMatthew Simpson   /// FunctionSet values and a FunctionSet value with an Undefined value. For
150cb58558cSMatthew Simpson   /// these cases, we simply union the function sets. If the size of the union
151cb58558cSMatthew Simpson   /// is greater than the maximum functions we track, the merged value is
152cb58558cSMatthew Simpson   /// overdefined.
153cb58558cSMatthew Simpson   CVPLatticeVal MergeValues(CVPLatticeVal X, CVPLatticeVal Y) override {
154cb58558cSMatthew Simpson     if (X == getOverdefinedVal() || Y == getOverdefinedVal())
155cb58558cSMatthew Simpson       return getOverdefinedVal();
156cb58558cSMatthew Simpson     if (X == getUndefVal() && Y == getUndefVal())
157cb58558cSMatthew Simpson       return getUndefVal();
158c8bd5449SBenjamin Kramer     std::vector<Function *> Union;
159cb58558cSMatthew Simpson     std::set_union(X.getFunctions().begin(), X.getFunctions().end(),
160cb58558cSMatthew Simpson                    Y.getFunctions().begin(), Y.getFunctions().end(),
161c8bd5449SBenjamin Kramer                    std::back_inserter(Union), CVPLatticeVal::Compare{});
162cb58558cSMatthew Simpson     if (Union.size() > MaxFunctionsPerValue)
163cb58558cSMatthew Simpson       return getOverdefinedVal();
164cb58558cSMatthew Simpson     return CVPLatticeVal(std::move(Union));
165cb58558cSMatthew Simpson   }
166cb58558cSMatthew Simpson 
167cb58558cSMatthew Simpson   /// Compute the lattice values that change as a result of executing the given
168cb58558cSMatthew Simpson   /// instruction. The changed values are stored in \p ChangedValues. We handle
169cb58558cSMatthew Simpson   /// just a few kinds of instructions since we're only propagating values that
170cb58558cSMatthew Simpson   /// can be called.
171cb58558cSMatthew Simpson   void ComputeInstructionState(
172cb58558cSMatthew Simpson       Instruction &I, DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
173cb58558cSMatthew Simpson       SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) override {
174cb58558cSMatthew Simpson     switch (I.getOpcode()) {
175cb58558cSMatthew Simpson     case Instruction::Call:
176cb58558cSMatthew Simpson       return visitCallSite(cast<CallInst>(&I), ChangedValues, SS);
177cb58558cSMatthew Simpson     case Instruction::Invoke:
178cb58558cSMatthew Simpson       return visitCallSite(cast<InvokeInst>(&I), ChangedValues, SS);
179cb58558cSMatthew Simpson     case Instruction::Load:
180cb58558cSMatthew Simpson       return visitLoad(*cast<LoadInst>(&I), ChangedValues, SS);
181cb58558cSMatthew Simpson     case Instruction::Ret:
182cb58558cSMatthew Simpson       return visitReturn(*cast<ReturnInst>(&I), ChangedValues, SS);
183cb58558cSMatthew Simpson     case Instruction::Select:
184cb58558cSMatthew Simpson       return visitSelect(*cast<SelectInst>(&I), ChangedValues, SS);
185cb58558cSMatthew Simpson     case Instruction::Store:
186cb58558cSMatthew Simpson       return visitStore(*cast<StoreInst>(&I), ChangedValues, SS);
187cb58558cSMatthew Simpson     default:
188cb58558cSMatthew Simpson       return visitInst(I, ChangedValues, SS);
189cb58558cSMatthew Simpson     }
190cb58558cSMatthew Simpson   }
191cb58558cSMatthew Simpson 
192cb58558cSMatthew Simpson   /// Print the given CVPLatticeVal to the specified stream.
193cb58558cSMatthew Simpson   void PrintLatticeVal(CVPLatticeVal LV, raw_ostream &OS) override {
194cb58558cSMatthew Simpson     if (LV == getUndefVal())
195cb58558cSMatthew Simpson       OS << "Undefined  ";
196cb58558cSMatthew Simpson     else if (LV == getOverdefinedVal())
197cb58558cSMatthew Simpson       OS << "Overdefined";
198cb58558cSMatthew Simpson     else if (LV == getUntrackedVal())
199cb58558cSMatthew Simpson       OS << "Untracked  ";
200cb58558cSMatthew Simpson     else
201cb58558cSMatthew Simpson       OS << "FunctionSet";
202cb58558cSMatthew Simpson   }
203cb58558cSMatthew Simpson 
204cb58558cSMatthew Simpson   /// Print the given CVPLatticeKey to the specified stream.
205cb58558cSMatthew Simpson   void PrintLatticeKey(CVPLatticeKey Key, raw_ostream &OS) override {
206cb58558cSMatthew Simpson     if (Key.getInt() == IPOGrouping::Register)
207cb58558cSMatthew Simpson       OS << "<reg> ";
208cb58558cSMatthew Simpson     else if (Key.getInt() == IPOGrouping::Memory)
209cb58558cSMatthew Simpson       OS << "<mem> ";
210cb58558cSMatthew Simpson     else if (Key.getInt() == IPOGrouping::Return)
211cb58558cSMatthew Simpson       OS << "<ret> ";
212cb58558cSMatthew Simpson     if (isa<Function>(Key.getPointer()))
213cb58558cSMatthew Simpson       OS << Key.getPointer()->getName();
214cb58558cSMatthew Simpson     else
215cb58558cSMatthew Simpson       OS << *Key.getPointer();
216cb58558cSMatthew Simpson   }
217cb58558cSMatthew Simpson 
218cb58558cSMatthew Simpson   /// We collect a set of indirect calls when visiting call sites. This method
219cb58558cSMatthew Simpson   /// returns a reference to that set.
220cb58558cSMatthew Simpson   SmallPtrSetImpl<Instruction *> &getIndirectCalls() { return IndirectCalls; }
221cb58558cSMatthew Simpson 
222cb58558cSMatthew Simpson private:
223cb58558cSMatthew Simpson   /// Holds the indirect calls we encounter during the analysis. We will attach
224cb58558cSMatthew Simpson   /// metadata to these calls after the analysis indicating the functions the
225cb58558cSMatthew Simpson   /// calls can possibly target.
226cb58558cSMatthew Simpson   SmallPtrSet<Instruction *, 32> IndirectCalls;
227cb58558cSMatthew Simpson 
228cb58558cSMatthew Simpson   /// Compute a new lattice value for the given constant. The constant, after
229cb58558cSMatthew Simpson   /// stripping any pointer casts, should be a Function. We ignore null
230cb58558cSMatthew Simpson   /// pointers as an optimization, since calling these values is undefined
231cb58558cSMatthew Simpson   /// behavior.
232cb58558cSMatthew Simpson   CVPLatticeVal computeConstant(Constant *C) {
233cb58558cSMatthew Simpson     if (isa<ConstantPointerNull>(C))
234cb58558cSMatthew Simpson       return CVPLatticeVal(CVPLatticeVal::FunctionSet);
235cb58558cSMatthew Simpson     if (auto *F = dyn_cast<Function>(C->stripPointerCasts()))
236cb58558cSMatthew Simpson       return CVPLatticeVal({F});
237cb58558cSMatthew Simpson     return getOverdefinedVal();
238cb58558cSMatthew Simpson   }
239cb58558cSMatthew Simpson 
240cb58558cSMatthew Simpson   /// Handle return instructions. The function's return state is the merge of
241cb58558cSMatthew Simpson   /// the returned value state and the function's return state.
242cb58558cSMatthew Simpson   void visitReturn(ReturnInst &I,
243cb58558cSMatthew Simpson                    DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
244cb58558cSMatthew Simpson                    SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
245cb58558cSMatthew Simpson     Function *F = I.getParent()->getParent();
246cb58558cSMatthew Simpson     if (F->getReturnType()->isVoidTy())
247cb58558cSMatthew Simpson       return;
248cb58558cSMatthew Simpson     auto RegI = CVPLatticeKey(I.getReturnValue(), IPOGrouping::Register);
249cb58558cSMatthew Simpson     auto RetF = CVPLatticeKey(F, IPOGrouping::Return);
250cb58558cSMatthew Simpson     ChangedValues[RetF] =
251cb58558cSMatthew Simpson         MergeValues(SS.getValueState(RegI), SS.getValueState(RetF));
252cb58558cSMatthew Simpson   }
253cb58558cSMatthew Simpson 
254cb58558cSMatthew Simpson   /// Handle call sites. The state of a called function's formal arguments is
255cb58558cSMatthew Simpson   /// the merge of the argument state with the call sites corresponding actual
256cb58558cSMatthew Simpson   /// argument state. The call site state is the merge of the call site state
257cb58558cSMatthew Simpson   /// with the returned value state of the called function.
258cb58558cSMatthew Simpson   void visitCallSite(CallSite CS,
259cb58558cSMatthew Simpson                      DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
260cb58558cSMatthew Simpson                      SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
261cb58558cSMatthew Simpson     Function *F = CS.getCalledFunction();
262cb58558cSMatthew Simpson     Instruction *I = CS.getInstruction();
263cb58558cSMatthew Simpson     auto RegI = CVPLatticeKey(I, IPOGrouping::Register);
264cb58558cSMatthew Simpson 
265cb58558cSMatthew Simpson     // If this is an indirect call, save it so we can quickly revisit it when
266cb58558cSMatthew Simpson     // attaching metadata.
267cb58558cSMatthew Simpson     if (!F)
268cb58558cSMatthew Simpson       IndirectCalls.insert(I);
269cb58558cSMatthew Simpson 
270cb58558cSMatthew Simpson     // If we can't track the function's return values, there's nothing to do.
271cb58558cSMatthew Simpson     if (!F || !canTrackReturnsInterprocedurally(F)) {
272b467233dSXin Tong       // Void return, No need to create and update CVPLattice state as no one
273b467233dSXin Tong       // can use it.
274b467233dSXin Tong       if (I->getType()->isVoidTy())
275b467233dSXin Tong         return;
276cb58558cSMatthew Simpson       ChangedValues[RegI] = getOverdefinedVal();
277cb58558cSMatthew Simpson       return;
278cb58558cSMatthew Simpson     }
279cb58558cSMatthew Simpson 
280cb58558cSMatthew Simpson     // Inform the solver that the called function is executable, and perform
281cb58558cSMatthew Simpson     // the merges for the arguments and return value.
282cb58558cSMatthew Simpson     SS.MarkBlockExecutable(&F->front());
283cb58558cSMatthew Simpson     auto RetF = CVPLatticeKey(F, IPOGrouping::Return);
284cb58558cSMatthew Simpson     for (Argument &A : F->args()) {
285cb58558cSMatthew Simpson       auto RegFormal = CVPLatticeKey(&A, IPOGrouping::Register);
286cb58558cSMatthew Simpson       auto RegActual =
287cb58558cSMatthew Simpson           CVPLatticeKey(CS.getArgument(A.getArgNo()), IPOGrouping::Register);
288cb58558cSMatthew Simpson       ChangedValues[RegFormal] =
289cb58558cSMatthew Simpson           MergeValues(SS.getValueState(RegFormal), SS.getValueState(RegActual));
290cb58558cSMatthew Simpson     }
291b467233dSXin Tong 
292b467233dSXin Tong     // Void return, No need to create and update CVPLattice state as no one can
293b467233dSXin Tong     // use it.
294b467233dSXin Tong     if (I->getType()->isVoidTy())
295b467233dSXin Tong       return;
296b467233dSXin Tong 
297cb58558cSMatthew Simpson     ChangedValues[RegI] =
298cb58558cSMatthew Simpson         MergeValues(SS.getValueState(RegI), SS.getValueState(RetF));
299cb58558cSMatthew Simpson   }
300cb58558cSMatthew Simpson 
301cb58558cSMatthew Simpson   /// Handle select instructions. The select instruction state is the merge the
302cb58558cSMatthew Simpson   /// true and false value states.
303cb58558cSMatthew Simpson   void visitSelect(SelectInst &I,
304cb58558cSMatthew Simpson                    DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
305cb58558cSMatthew Simpson                    SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
306cb58558cSMatthew Simpson     auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);
307cb58558cSMatthew Simpson     auto RegT = CVPLatticeKey(I.getTrueValue(), IPOGrouping::Register);
308cb58558cSMatthew Simpson     auto RegF = CVPLatticeKey(I.getFalseValue(), IPOGrouping::Register);
309cb58558cSMatthew Simpson     ChangedValues[RegI] =
310cb58558cSMatthew Simpson         MergeValues(SS.getValueState(RegT), SS.getValueState(RegF));
311cb58558cSMatthew Simpson   }
312cb58558cSMatthew Simpson 
313cb58558cSMatthew Simpson   /// Handle load instructions. If the pointer operand of the load is a global
314cb58558cSMatthew Simpson   /// variable, we attempt to track the value. The loaded value state is the
315cb58558cSMatthew Simpson   /// merge of the loaded value state with the global variable state.
316cb58558cSMatthew Simpson   void visitLoad(LoadInst &I,
317cb58558cSMatthew Simpson                  DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
318cb58558cSMatthew Simpson                  SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
319cb58558cSMatthew Simpson     auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);
320cb58558cSMatthew Simpson     if (auto *GV = dyn_cast<GlobalVariable>(I.getPointerOperand())) {
321cb58558cSMatthew Simpson       auto MemGV = CVPLatticeKey(GV, IPOGrouping::Memory);
322cb58558cSMatthew Simpson       ChangedValues[RegI] =
323cb58558cSMatthew Simpson           MergeValues(SS.getValueState(RegI), SS.getValueState(MemGV));
324cb58558cSMatthew Simpson     } else {
325cb58558cSMatthew Simpson       ChangedValues[RegI] = getOverdefinedVal();
326cb58558cSMatthew Simpson     }
327cb58558cSMatthew Simpson   }
328cb58558cSMatthew Simpson 
329cb58558cSMatthew Simpson   /// Handle store instructions. If the pointer operand of the store is a
330cb58558cSMatthew Simpson   /// global variable, we attempt to track the value. The global variable state
331cb58558cSMatthew Simpson   /// is the merge of the stored value state with the global variable state.
332cb58558cSMatthew Simpson   void visitStore(StoreInst &I,
333cb58558cSMatthew Simpson                   DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
334cb58558cSMatthew Simpson                   SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
335cb58558cSMatthew Simpson     auto *GV = dyn_cast<GlobalVariable>(I.getPointerOperand());
336cb58558cSMatthew Simpson     if (!GV)
337cb58558cSMatthew Simpson       return;
338cb58558cSMatthew Simpson     auto RegI = CVPLatticeKey(I.getValueOperand(), IPOGrouping::Register);
339cb58558cSMatthew Simpson     auto MemGV = CVPLatticeKey(GV, IPOGrouping::Memory);
340cb58558cSMatthew Simpson     ChangedValues[MemGV] =
341cb58558cSMatthew Simpson         MergeValues(SS.getValueState(RegI), SS.getValueState(MemGV));
342cb58558cSMatthew Simpson   }
343cb58558cSMatthew Simpson 
344cb58558cSMatthew Simpson   /// Handle all other instructions. All other instructions are marked
345cb58558cSMatthew Simpson   /// overdefined.
346cb58558cSMatthew Simpson   void visitInst(Instruction &I,
347cb58558cSMatthew Simpson                  DenseMap<CVPLatticeKey, CVPLatticeVal> &ChangedValues,
348cb58558cSMatthew Simpson                  SparseSolver<CVPLatticeKey, CVPLatticeVal> &SS) {
3498a505c64SXin Tong     // Simply bail if this instruction has no user.
3508a505c64SXin Tong     if (I.use_empty())
3518a505c64SXin Tong       return;
352cb58558cSMatthew Simpson     auto RegI = CVPLatticeKey(&I, IPOGrouping::Register);
353cb58558cSMatthew Simpson     ChangedValues[RegI] = getOverdefinedVal();
354cb58558cSMatthew Simpson   }
355cb58558cSMatthew Simpson };
356cb58558cSMatthew Simpson } // namespace
357cb58558cSMatthew Simpson 
358cb58558cSMatthew Simpson namespace llvm {
359cb58558cSMatthew Simpson /// A specialization of LatticeKeyInfo for CVPLatticeKeys. The generic solver
360cb58558cSMatthew Simpson /// must translate between LatticeKeys and LLVM Values when adding Values to
361cb58558cSMatthew Simpson /// its work list and inspecting the state of control-flow related values.
362cb58558cSMatthew Simpson template <> struct LatticeKeyInfo<CVPLatticeKey> {
363cb58558cSMatthew Simpson   static inline Value *getValueFromLatticeKey(CVPLatticeKey Key) {
364cb58558cSMatthew Simpson     return Key.getPointer();
365cb58558cSMatthew Simpson   }
366cb58558cSMatthew Simpson   static inline CVPLatticeKey getLatticeKeyFromValue(Value *V) {
367cb58558cSMatthew Simpson     return CVPLatticeKey(V, IPOGrouping::Register);
368cb58558cSMatthew Simpson   }
369cb58558cSMatthew Simpson };
370cb58558cSMatthew Simpson } // namespace llvm
371cb58558cSMatthew Simpson 
372cb58558cSMatthew Simpson static bool runCVP(Module &M) {
373cb58558cSMatthew Simpson   // Our custom lattice function and generic sparse propagation solver.
374cb58558cSMatthew Simpson   CVPLatticeFunc Lattice;
375cb58558cSMatthew Simpson   SparseSolver<CVPLatticeKey, CVPLatticeVal> Solver(&Lattice);
376cb58558cSMatthew Simpson 
377cb58558cSMatthew Simpson   // For each function in the module, if we can't track its arguments, let the
378cb58558cSMatthew Simpson   // generic solver assume it is executable.
379cb58558cSMatthew Simpson   for (Function &F : M)
380cb58558cSMatthew Simpson     if (!F.isDeclaration() && !canTrackArgumentsInterprocedurally(&F))
381cb58558cSMatthew Simpson       Solver.MarkBlockExecutable(&F.front());
382cb58558cSMatthew Simpson 
383cb58558cSMatthew Simpson   // Solver our custom lattice. In doing so, we will also build a set of
384cb58558cSMatthew Simpson   // indirect call sites.
385cb58558cSMatthew Simpson   Solver.Solve();
386cb58558cSMatthew Simpson 
387cb58558cSMatthew Simpson   // Attach metadata to the indirect call sites that were collected indicating
388cb58558cSMatthew Simpson   // the set of functions they can possibly target.
389cb58558cSMatthew Simpson   bool Changed = false;
390cb58558cSMatthew Simpson   MDBuilder MDB(M.getContext());
391cb58558cSMatthew Simpson   for (Instruction *C : Lattice.getIndirectCalls()) {
392cb58558cSMatthew Simpson     CallSite CS(C);
393cb58558cSMatthew Simpson     auto RegI = CVPLatticeKey(CS.getCalledValue(), IPOGrouping::Register);
394cb58558cSMatthew Simpson     CVPLatticeVal LV = Solver.getExistingValueState(RegI);
395cb58558cSMatthew Simpson     if (!LV.isFunctionSet() || LV.getFunctions().empty())
396cb58558cSMatthew Simpson       continue;
397c8bd5449SBenjamin Kramer     MDNode *Callees = MDB.createCallees(LV.getFunctions());
398cb58558cSMatthew Simpson     C->setMetadata(LLVMContext::MD_callees, Callees);
399cb58558cSMatthew Simpson     Changed = true;
400cb58558cSMatthew Simpson   }
401cb58558cSMatthew Simpson 
402cb58558cSMatthew Simpson   return Changed;
403cb58558cSMatthew Simpson }
404cb58558cSMatthew Simpson 
405cb58558cSMatthew Simpson PreservedAnalyses CalledValuePropagationPass::run(Module &M,
406cb58558cSMatthew Simpson                                                   ModuleAnalysisManager &) {
407cb58558cSMatthew Simpson   runCVP(M);
408cb58558cSMatthew Simpson   return PreservedAnalyses::all();
409cb58558cSMatthew Simpson }
410cb58558cSMatthew Simpson 
411cb58558cSMatthew Simpson namespace {
412cb58558cSMatthew Simpson class CalledValuePropagationLegacyPass : public ModulePass {
413cb58558cSMatthew Simpson public:
414cb58558cSMatthew Simpson   static char ID;
415cb58558cSMatthew Simpson 
416cb58558cSMatthew Simpson   void getAnalysisUsage(AnalysisUsage &AU) const override {
417cb58558cSMatthew Simpson     AU.setPreservesAll();
418cb58558cSMatthew Simpson   }
419cb58558cSMatthew Simpson 
420cb58558cSMatthew Simpson   CalledValuePropagationLegacyPass() : ModulePass(ID) {
421cb58558cSMatthew Simpson     initializeCalledValuePropagationLegacyPassPass(
422cb58558cSMatthew Simpson         *PassRegistry::getPassRegistry());
423cb58558cSMatthew Simpson   }
424cb58558cSMatthew Simpson 
425cb58558cSMatthew Simpson   bool runOnModule(Module &M) override {
426cb58558cSMatthew Simpson     if (skipModule(M))
427cb58558cSMatthew Simpson       return false;
428cb58558cSMatthew Simpson     return runCVP(M);
429cb58558cSMatthew Simpson   }
430cb58558cSMatthew Simpson };
431cb58558cSMatthew Simpson } // namespace
432cb58558cSMatthew Simpson 
433cb58558cSMatthew Simpson char CalledValuePropagationLegacyPass::ID = 0;
434cb58558cSMatthew Simpson INITIALIZE_PASS(CalledValuePropagationLegacyPass, "called-value-propagation",
435cb58558cSMatthew Simpson                 "Called Value Propagation", false, false)
436cb58558cSMatthew Simpson 
437cb58558cSMatthew Simpson ModulePass *llvm::createCalledValuePropagationPass() {
438cb58558cSMatthew Simpson   return new CalledValuePropagationLegacyPass();
439cb58558cSMatthew Simpson }
440