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